项目中在更新数据库时出现异常,org.springframework.dao.DataIntegrityViolationException,当然如果控制台直接报这个异常问题的解决估计也不至于让我写篇博客。
先说这个异常代表的含义吧:
这个异常的意思就是在更新(update或insert)数据库时,新的数据违反了完整性,例如主键重复,我这里的问题是
数据库的id字段未设置自增,默认值也没设,在插入的时候就出现了这个异常
,问题的解决很简单,修改数据库id字段为自增字段,完美解决。
出现这个问题的时候应该去查看更新的字段的数据与数据库中对应字段的属性是否有冲突的地方,或者是待更新的数据本身的问题。
接下来是重点,为什么这个异常没有第一时间发现,简单点说就是异常被封装了,在业务层很多异常直接被捕获使用一个handlerException进行处理,返回给封装的错误信息,而且这个异常被捕获处理之后,控制台也无法显示。
定义解决未被业务controller层吸收的exception @ExceptionHandler ( Exception . class ) @ResponseStatus ( HttpStatus . OK ) @ResponseBody public Object handlerException ( HttpServletRequest request , Exception ex ) { Map < String , Object > responseData = new HashMap < > ( ) ; if ( ex instanceof BusinessException ) { BusinessException businessException = ( BusinessException ) ex ; responseData . put ( "errCode" , businessException . getErrCode ( ) ) ; responseData . put ( "errMsg" , businessException . getErrMsg ( ) ) ; } else { responseData . put ( "errCode" , UNKNOWN_ERROR . getErrCode ( ) ) ; responseData . put ( "errMsg" , UNKNOWN_ERROR . getErrMsg ( ) ) ; return CommonReturnType . create ( responseData , "fail" ) ;这是主要原因,其次是从前端的封装错误信息中应该直接能意识到是在这个未被业务层处理的Exception中的,不应该浪费时间在debug其他函数上的,未来再debug的时候希望能从项目的全局去思考问题,而不是揪住错的这一个点。
记一次奇怪的 Data Integ rityViolat ion Exception 异常处理 梦开始的地方 最近开发的时候出现了一次 Data Integ rityViolat ion Exception 异常,当时我也没太在意,因为开发里出现一个小小的bug也是正常的,于是我就开始百度,然后我就发现了事情的不对劲。因为百度出来的这个都是说是在更新数据库时出现的异常,但是我其实是做的查询操作。 先说一下用到的框架,是SpringBoot+Mybatis,当时是需要做一个数据统计。结构大概如下: VO,num1和num2 好不容易部署上去的项目,今天却被告知出现bug,找了好半天才发现bug的源头,又花了小半天才解决掉,同事还说还好是花了大半天时间给找到bug并解决了,不然搞到明天还没解决就尴尬了……言归正传,前端页面报错如下: org.springframework.dao. Data Integ rityViolat ion Exception : Could not execute JDBC batch update; ... Caused by: java.lang.ClassNotFound Exception : org.springframework.dao. Data Integ rityViolat ion Exception at java.net.URLClassLoader$1.run(Unknown Source) at java.security.Acc... 主要是sql语句查询错误,因为查询条件字段pid在两张表中都存在,计算机分不清到底是那张表的查询字段org.springframework.web.util.NestedServlet Exception : Request processing failed; nested exception is org.springframework.dao. Data Integ rityViolat ion Exce... Integ rity Violat ion Exception ,违背数据完整性异常) ,嵌套的异常通常是 org.hibernate. exception .ConstraintViolat ion Exception (Constrai 1.封装集合中字段名与数据库列名不一致,检查是否一致以及是否有该字段; 2.使用lombok或是其他操作导致没有无参构造或是无get/set; 3.使用Druid,因为版本问题导致对于时间类型LocalDateTime.class处理异常;此种处理方案:不使用Druid或是使用其他数据库连接源进行替换或是Druid版本升级. org.springframework.dao. Data Integ rityViolat ion Exception : could not execute statement; SQL [n/a]; constraint [UNQ_code]; nested exception is org.hibernate. exception .ConstraintViolat ion Exception : could not execute statement Data Integ rityViolat ion Exception 唯一 Not Using Commons Logging ................................................................... 12 Using SLF4J ............................................................................................ 13 Using Log4J ............................................................................................. 14 II. What’s New in Spring Framework 4.x .................................................................................... 16 3. New Features and Enhancements in Spring Framework 4.0 ............................................ 17 3.1. Improved Getting Started Experience .................................................................. 17 3.2. Removed Deprecated Packages and Methods .................................................... 17 3.3. Java 8 (as well as 6 and 7) ............................................................................... 17 3.4. Java EE 6 and 7 ............................................................................................... 18 3.5. Groovy Bean Definit ion DSL .............................................................................. 18 3.6. Core Container Improvements ............................................................................ 19 3.7. General Web Improvements ............................................................................... 19 3.8. WebSocket, SockJS, and STOMP Messaging ..................................................... 19 3.9. Testing Improvements ........................................................................................ 20 III. Core Technologies .............................................................................................................. 21 4. The IoC container ........................................................................................................ 22 4.1. Introduct ion to the Spring IoC container and beans .............................................. 22 4.2. Container overview ............................................................................................ 22 Configurat ion meta data ..................................................................................... 23 Instantiating a container .................................................................................... 24 Composing XML-based configurat ion meta data .......................................... 25 Using the container .......................................................................................... 26 4.3. Bean overview ................................................................................................... 27 Naming beans .................................................................................................. 28 Aliasing a bean outside the bean definit ion ................................................ 28 Instantiating beans ........................................................................................... 29 Instantiat ion with a constructor .................................................................. 29 Instantiat ion with a static factory method .................................................... 30 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentat ion iii Instantiat ion using an instance factory method ........................................... 30 4.4. Dependencies ................................................................................................... 32 Dependency inject ion ....................................................................................... 32 Constructor-based dependency inject ion .................................................... 32 Setter-based dependency inject ion ............................................................ 34 Dependency resolut ion process ................................................................. 35 Examples of dependency inject ion ............................................................. 36 Dependencies and configurat ion in detail ........................................................... 38 Straight values (primitives, Strings, and so on) ........................................... 38 References to other beans (collaborators) .................................................. 40 Inner beans .............................................................................................. 41 Collect ion s ............................................................................................... 41 Null and empty string values ..................................................................... 44 XML shortcut with the p-namespace .......................................................... 44 XML shortcut with the c-namespace .......................................................... 46 Compound property names ....................................................................... 46 Using depends-on ............................................................................................ 47 Lazy-initialized beans ....................................................................................... 47 Autowiring collaborators .................................................................................... 48 Limitat ion s and disadvantages of autowiring ............................................... 49 Excluding a bean from autowiring .............................................................. 50 Method inject ion ............................................................................................... 50 Lookup method inject ion ........................................................................... 51 Arbitrary method replacement ................................................................... 53 4.5. Bean scopes ..................................................................................................... 54 The singleton scope ......................................................................................... 55 The prototype scope ......................................................................................... 55 Singleton beans with prototype-bean dependencies ............................................ 56 Request, sess ion , and global sess ion scopes .................................................... 56 Initial web configurat ion ............................................................................ 57 Request scope ......................................................................................... 58 Sess ion scope .......................................................................................... 58 Global sess ion scope ............................................................................... 58 Scoped beans as dependencies ................................................................ 58 Custom scopes ................................................................................................ 60 Creating a custom scope .......................................................................... 60 Using a custom scope .............................................................................. 61 4.6. Customizing the nature of a bean ....................................................................... 62 Lifecycle callbacks ............................................................................................ 62 Initializat ion callbacks ............................................................................... 63 Destruct ion callbacks ................................................................................ 64 Default initializat ion and destroy methods .................................................. 64 Combining lifecycle mechanisms ............................................................... 66 Startup and shutdown callbacks ................................................................ 66 Shutting down the Spring IoC container gracefully in non-web applicat ion s ................................................................................................................. 68 Applicat ion ContextAware and BeanNameAware ................................................. 68 Other Aware interfaces ..................................................................................... 69 4.7. Bean definit ion inheritance ................................................................................. 71 4.8. Container Extens ion Points ................................................................................ 72 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentat ion iv Customizing beans using a BeanPostProcessor ................................................. 72 Example: Hello World, BeanPostProcessor-style ........................................ 74 Example: The RequiredAnnotat ion BeanPostProcessor ............................... 75 Customizing configurat ion meta data with a BeanFactoryPostProcessor ................ 75 Example: the Class name substitut ion PropertyPlaceholderConfigurer .......... 76 Example: the PropertyOverrideConfigurer .................................................. 77 Customizing instantiat ion logic with a FactoryBean ............................................. 78 4.9. Annotat ion -based container configurat ion ............................................................ 79 @Required ....................................................................................................... 80 @Autowired ..................................................................................................... 80 Fine-tuning annotat ion -based autowiring with qualifiers ....................................... 83 Using generics as autowiring qualifiers .............................................................. 89 CustomAutowireConfigurer ................................................................................ 90 @Resource ...................................................................................................... 90 @PostConstruct and @PreDestroy .................................................................... 92 4.10. Classpath scanning and managed components ................................................. 92 @Component and further stereotype annotat ion s ............................................... 93 Meta-annotat ion s .............................................................................................. 93 Automatically detecting classes and registering bean definit ion s .......................... 94 Using filters to customize scanning ................................................................... 95 Defining bean meta data within components ....................................................... 96 Naming autodetected components ..................................................................... 97 Providing a scope for autodetected components ................................................ 98 Providing qualifier meta data with annotat ion s ..................................................... 99 4.11. Using JSR 330 Standard Annotat ion s ............................................................... 99 Dependency Inject ion with @Inject and @Named ............................................. 100 @Named: a standard equivalent to the @Component annotat ion ....................... 100 Limitat ion s of the standard approach ............................................................... 101 4.12. Java-based container configurat ion ................................................................. 102 Basic concepts: @Bean and @Configurat ion ................................................... 102 Instantiating the Spring container using Annotat ion ConfigApplicat ion Context ....... 103 Simple construct ion ................................................................................ 103 Building the container programmatically using register(Class<?>…) ........... 104 Enabling component scanning with scan(String…) .................................... 104 Support for web applicat ion s with Annotat ion ConfigWebApplicat ion Context ............................................................................................................... 105 Using the @Bean annotat ion .......................................................................... 106 Declaring a bean .................................................................................... 107 Receiving lifecycle callbacks ................................................................... 107 Specifying bean scope ............................................................................ 108 Customizing bean naming ....................................................................... 109 Bean aliasing ......................................................................................... 109 Bean descript ion ..................................................................................... 110 Using the @Configurat ion annotat ion ............................................................... 110 Injecting inter-bean dependencies ............................................................ 110 Lookup method inject ion ......................................................................... 111 Further informat ion about how Java-based configurat ion works internally .... 111 Composing Java-based configurat ion s ............................................................. 112 Using the @Import annotat ion ................................................................. 112 Condit ion ally including @Configurat ion classes or @Beans ....................... 116 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentat ion v Combining Java and XML configurat ion ................................................... 117 4.13. Bean definit ion profiles and environment abstract ion ........................................ 120 4.14. PropertySource Abstract ion ............................................................................ 120 4.15. Registering a LoadTimeWeaver ...................................................................... 120 4.16. Addit ion al Capabilities of the Applicat ion Context .............................................. 120 Internat ion alizat ion using MessageSource ........................................................ 121 Standard and Custom Events .......................................................................... 124 Convenient access to low-level resources ........................................................ 127 Convenient Applicat ion Context instantiat ion for web applicat ion s ....................... 128 Deploying a Spring Applicat ion Context as a J2EE RAR file ............................... 128 4.17. The BeanFactory ........................................................................................... 129 BeanFactory or Applicat ion Context? ................................................................ 129 Glue code and the evil singleton ..................................................................... 131 5. Resources .................................................................................................................. 132 5.1. Introduct ion ..................................................................................................... 132 5.2. The Resource interface .................................................................................... 132 5.3. Built-in Resource implementat ion s .................................................................... 133 UrlResource ................................................................................................... 133 ClassPathResource ........................................................................................ 133 FileSystemResource ....................................................................................... 134 ServletContextResource .................................................................................. 134 InputStreamResource ..................................................................................... 134 ByteArrayResource ......................................................................................... 134 5.4. The ResourceLoader ....................................................................................... 134 5.5. The ResourceLoaderAware interface ................................................................ 135 5.6. Resources as dependencies ............................................................................. 136 5.7. Applicat ion contexts and Resource paths .......................................................... 137 Constructing applicat ion contexts ..................................................................... 137 Constructing ClassPathXmlApplicat ion Context instances - shortcuts .......... 137 Wildcards in applicat ion context constructor resource paths ............................... 138 Ant-style Patterns ................................................................................... 138 The Classpath*: portability classpath*: prefix ............................................ 139 Other notes relating to wildcards ............................................................. 139 FileSystemResource caveats .......................................................................... 140 6. Validat ion , Data Binding, and Type Convers ion ............................................................ 141 6.1. Introduct ion ..................................................................................................... 141 6.2. Validat ion using Spring’s Validator interface ...................................................... 141 6.3. Resolving codes to error messages .................................................................. 143 6.4. Bean manipulat ion and the BeanWrapper ......................................................... 144 Setting and getting basic and nested properties ............................................... 144 Built-in PropertyEditor implementat ion s ............................................................ 146 Registering addit ion al custom PropertyEditors .......................................... 149 6.5. Spring Type Convers ion ................................................................................... 151 Converter SPI ................................................................................................ 151 ConverterFactory ............................................................................................ 152 GenericConverter ........................................................................................... 153 Condit ion alGenericConverter ................................................................... 154 Convers ion Service API ................................................................................... 154 Configuring a Convers ion Service ..................................................................... 154 Using a Convers ion Service programmatically ................................................... 155 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentat ion vi 6.6. Spring Field Formatting .................................................................................... 155 Formatter SPI ................................................................................................. 156 Annotat ion -driven Formatting ........................................................................... 157 Format Annotat ion API ............................................................................ 158 FormatterRegistry SPI ..................................................................................... 159 FormatterRegistrar SPI ................................................................................... 159 Configuring Formatting in Spring MVC ............................................................. 159 6.7. Configuring a global date & time format ............................................................ 161 6.8. Spring Validat ion ............................................................................................. 163 Overview of the JSR-303 Bean Validat ion API ................................................. 163 Configuring a Bean Validat ion Provider ............................................................ 164 Injecting a Validator ................................................................................ 164 Configuring Custom Constraints .............................................................. 164 Addit ion al Configurat ion Opt ion s .............................................................. 165 Configuring a Data Binder ................................................................................ 165 Spring MVC 3 Validat ion ................................................................................. 166 Triggering @Controller Input Validat ion .................................................... 166 Configuring a Validator for use by Spring MVC ......................................... 166 Configuring a JSR-303/JSR-349 Validator for use by Spring MVC .............. 167 7. Spring Express ion Language (SpEL) ........................................................................... 168 7.1. Introduct ion ..................................................................................................... 168 7.2. Feature Overview ............................................................................................ 168 7.3. Express ion Evaluat ion using Spring’s Express ion Interface ................................. 169 The Evaluat ion Context interface ...................................................................... 171 Type Convers ion .................................................................................... 171 7.4. Express ion support for defining bean definit ion s ................................................ 172 XML based configurat ion ................................................................................ 172 Annotat ion -based configurat ion ........................................................................ 173 7.5. Language Reference ........................................................................................ 174 Literal express ion s .......................................................................................... 174 Properties, Arrays, Lists, Maps, Indexers ......................................................... 174 Inline lists ....................................................................................................... 175 Array construct ion ........................................................................................... 175 Methods ......................................................................................................... 176 Operators ....................................................................................................... 176 Relat ion al operators ................................................................................ 176 Logical operators .................................................................................... 177 Mathematical operators ........................................................................... 177 Assignment .................................................................................................... 178 Types ............................................................................................................. 178 Constructors ................................................................................................... 179 Variables ........................................................................................................ 179 The #this and #root variables .................................................................. 179 Funct ion s ....................................................................................................... 180 Bean references ............................................................................................. 180 Ternary Operator (If-Then-Else) ....................................................................... 180 The Elvis Operator ......................................................................................... 181 Safe Navigat ion operator ................................................................................ 181 Collect ion Select ion ........................................................................................ 182 Collect ion Project ion ....................................................................................... 182 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentat ion vii Express ion templating ..................................................................................... 183 7.6. Classes used in the examples .......................................................................... 183 8. Aspect Oriented Programming with Spring ................................................................... 187 8.1. Introduct ion ..................................................................................................... 187 AOP concepts ................................................................................................ 187 Spring AOP capabilities and goals ................................................................... 189 AOP Proxies .................................................................................................. 190 8.2. @AspectJ support ........................................................................................... 190 Enabling @AspectJ Support ............................................................................ 190 Enabling @AspectJ Support with Java configurat ion ................................. 190 Enabling @AspectJ Support with XML configurat ion ................................. 191 Declaring an aspect ........................................................................................ 191 Declaring a pointcut ........................................................................................ 192 Supported Pointcut Designators .............................................................. 192 Combining pointcut express ion s .............................................................. 194 Sharing common pointcut definit ion s ........................................................ 194 Examples ............................................................................................... 196 Writing good pointcuts ............................................................................ 198 Declaring advice ............................................................................................. 199 Before advice ......................................................................................... 199 After returning advice .............................................................................. 200 After throwing advice .............................................................................. 200 After (finally) advice ................................................................................ 201 Around advice ........................................................................................ 202 Advice parameters .................................................................................. 203 Advice ordering ...................................................................................... 206 Introduct ion s ................................................................................................... 206 Aspect instantiat ion models ............................................................................. 207 Example ......................................................................................................... 208 8.3. Schema-based AOP support ............................................................................ 209 Declaring an aspect ........................................................................................ 210 Declaring a pointcut ........................................................................................ 210 Declaring advice ............................................................................................. 212 Before advice ......................................................................................... 212 After returning advice .............................................................................. 212 After throwing advice .............................................................................. 213 After (finally) advice ................................................................................ 214 Around advice ........................................................................................ 214 Advice parameters .................................................................................. 215 Advice ordering ...................................................................................... 216 Introduct ion s ................................................................................................... 217 Aspect instantiat ion models ............................................................................. 217 Advisors ......................................................................................................... 217 Example ......................................................................................................... 218 8.4. Choosing which AOP declarat ion style to use .................................................... 220 Spring AOP or full AspectJ? ........................................................................... 220 @AspectJ or XML for Spring AOP? ................................................................. 221 8.5. Mixing aspect types ......................................................................................... 222 8.6. Proxying mechanisms ...................................................................................... 222 Understanding AOP proxies ............................................................................ 223 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentat ion viii 8.7. Programmatic creat ion of @AspectJ Proxies ..................................................... 225 8.8. Using AspectJ with Spring applicat ion s ............................................................. 225 Using AspectJ to dependency inject domain objects with Spring ........................ 226 Unit testing @Configurable objects .......................................................... 228 Working with multiple applicat ion contexts ................................................ 228 Other Spring aspects for AspectJ .................................................................... 229 Configuring AspectJ aspects using Spring IoC ................................................. 229 Load-time weaving with AspectJ in the Spring Framework ................................. 230 A first example ....................................................................................... 231 Aspects .................................................................................................. 234 ' META-INF/aop.xml' ............................................................................... 234 Required libraries (JARS) ........................................................................ 234 Spring configurat ion ................................................................................ 235 Environment-specific configurat ion ........................................................... 237 8.9. Further Resources ........................................................................................... 239 9. Spring AOP APIs ....................................................................................................... 240 9.1. Introduct ion ..................................................................................................... 240 9.2. Pointcut API in Spring ...................................................................................... 240 Concepts ........................................................................................................ 240 Operat ion s on pointcuts .................................................................................. 241 AspectJ express ion pointcuts .......................................................................... 241 Convenience pointcut implementat ion s ............................................................ 241 Static pointcuts ....................................................................................... 241 Dynamic pointcuts .................................................................................. 242 Pointcut superclasses ..................................................................................... 243 Custom pointcuts ............................................................................................ 243 9.3. Advice API in Spring ........................................................................................ 243 Advice lifecycles ............................................................................................. 243 Advice types in Spring .................................................................................... 244 Intercept ion around advice ...................................................................... 244 Before advice ......................................................................................... 244 Throws advice ........................................................................................ 245 After Returning advice ............................................................................ 246 Introduct ion advice .................................................................................. 247 9.4. Advisor API in Spring ....................................................................................... 249 9.5. Using the ProxyFactoryBean to create AOP proxies ........................................... 250 Basics ............................................................................................................ 250 JavaBean properties ....................................................................................... 250 JDK- and CGLIB-based proxies ...................................................................... 251 Proxying interfaces ......................................................................................... 252 Proxying classes ............................................................................................ 254 Using global advisors ...................................................................................... 255 9.6. Concise proxy definit ion s ................................................................................. 255 9.7. Creating AOP proxies programmatically with the ProxyFactory ............................ 256 9.8. Manipulating advised objects ............................................................................ 257 9.9. Using the "auto-proxy" facility ........................................................................... 258 Autoproxy bean definit ion s .............................................................................. 258 BeanNameAutoProxyCreator ................................................................... 259 DefaultAdvisorAutoProxyCreator .............................................................. 259 AbstractAdvisorAutoProxyCreator ............................................................ 260 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentat ion ix Using meta data -driven auto-proxying ............................................................... 260 9.10. Using TargetSources ...................................................................................... 262 Hot swappable target sources ......................................................................... 263 Pooling target sources .................................................................................... 263 Prototype target sources ................................................................................. 265 ThreadLocal target sources ............................................................................. 265 9.11. Defining new Advice types ............................................................................. 265 9.12. Further resources ........................................................................................... 266 10. Testing ..................................................................................................................... 267 10.1. Introduct ion to Spring Testing ......................................................................... 267 10.2. Unit Testing ................................................................................................... 267 Mock Objects ................................................................................................. 267 Environment ........................................................................................... 267 JNDI ...................................................................................................... 267 Servlet API ............................................................................................. 267 Portlet API ............................................................................................. 268 Unit Testing support Classes .......................................................................... 268 General utilities ...................................................................................... 268 Spring MVC ........................................................................................... 268 10.3. Integ rat ion Testing ......................................................................................... 268 Overview ........................................................................................................ 268 Goals of Integ rat ion Testing ............................................................................ 269 Context management and caching ........................................................... 269 Dependency Inject ion of test fixtures ....................................................... 269 Transact ion management ........................................................................ 270 Support classes for integ rat ion testing ..................................................... 270 JDBC Testing Support .................................................................................... 271 Annotat ion s .................................................................................................... 271 Spring Testing Annotat ion s ..................................................................... 271 Standard Annotat ion Support .................................................................. 276 Spring JUnit Testing Annotat ion s ............................................................. 277 Meta-Annotat ion Support for Testing ........................................................ 278 Spring TestContext Framework ....................................................................... 279 Key abstract ion s ..................................................................................... 280 Context management .............................................................................. 281 Dependency inject ion of test fixtures ........................................................ 297 Testing request and sess ion scoped beans .............................................. 299 Transact ion management ........................................................................ 301 TestContext Framework support classes .................................................. 304 Spring MVC Test Framework .......................................................................... 306 Server-Side Tests ................................................................................... 306 Client-Side REST Tests .......................................................................... 312 PetClinic Example .......................................................................................... 313 10.4. Further Resources ......................................................................................... 314 IV. Data Access ..................................................................................................................... 316 11. Transact ion Management .......................................................................................... 317 11.1. Introduct ion to Spring Framework transact ion management .............................. 317 11.2. Advantages of the Spring Framework’s transact ion support model ..................... 317 Global transact ion s ......................................................................................... 317 Local transact ion s ........................................................................................... 318 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentat ion x Spring Framework’s consistent programming model ......................................... 318 11.3. Understanding the Spring Framework transact ion abstract ion ............................ 319 11.4. Synchronizing resources with transact ion s ....................................................... 323 High-level synchronizat ion approach ................................................................ 323 Low-level synchronizat ion approach ................................................................. 323 Transact ion Aware Data SourceProxy ................................................................. 324 11.5. Declarative transact ion management ............................................................... 324 Understanding the Spring Framework’s declarative transact ion implementat ion ... 325 Example of declarative transact ion implementat ion ........................................... 326 Rolling back a declarative transact ion .............................................................. 330 Configuring different transact ion al semantics for different beans ........................ 331 <tx:advice/> settings ....................................................................................... 333 Using @Transact ion al ..................................................................................... 335 @Transact ion al settings .......................................................................... 339 Multiple Transact ion Managers with @Transact ion al ................................. 340 Custom shortcut annotat ion s ................................................................... 341 Transact ion propagat ion .................................................................................. 341 Required ................................................................................................ 342 RequiresNew .......................................................................................... 342 Nested ................................................................................................... 343 Advising transact ion al operat ion s ..................................................................... 343 Using @Transact ion al with AspectJ ................................................................. 346 11.6. Programmatic transact ion management ........................................................... 347 Using the Transact ion Template ....................................................................... 347 Specifying transact ion settings ................................................................ 349 Using the PlatformTransact ion Manager ............................................................ 349 11.7. Choosing between programmatic and declarative transact ion management ........ 350 11.8. Applicat ion server-specific integ rat ion .............................................................. 350 IBM WebSphere ............................................................................................. 351 Oracle WebLogic Server ................................................................................. 351 11.9. Solut ion s to common problems ....................................................................... 351 Use of the wrong transact ion manager for a specific Data Source ....................... 351 11.10. Further Resources ....................................................................................... 351 12. DAO support ............................................................................................................ 352 12.1. Introduct ion .................................................................................................... 352 12.2. Consistent exception hierarchy ....................................................................... 352 12.3. Annotat ion s used for configuring DAO or Repository classes ............................ 353 13. Data access with JDBC ............................................................................................ 355 13.1. Introduct ion to Spring Framework JDBC .......................................................... 355 Choosing an approach for JDBC data base access ........................................... 355 Package hierarchy .......................................................................................... 356 13.2. Using the JDBC core classes to control basic JDBC processing and error handling ................................................................................................................. 357 JdbcTemplate ................................................................................................. 357 Examples of JdbcTemplate class usage ................................................... 357 JdbcTemplate best practices ................................................................... 359 NamedParameterJdbcTemplate ....................................................................... 361 SQL Exception Translator .................................................................................. 363 Executing statements ...................................................................................... 365 Running queries ............................................................................................. 365 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentat ion xi Updating the data base .................................................................................... 366 Retrieving auto-generated keys ....................................................................... 367 13.3. Controlling data base connect ion s .................................................................... 367 Data Source .................................................................................................... 367 Data SourceUtils .............................................................................................. 369 Smart Data Source ........................................................................................... 369 Abstract Data Source ........................................................................................ 369 SingleConnect ion Data Source .......................................................................... 369 DriverManager Data Source .............................................................................. 369 Transact ion Aware Data SourceProxy ................................................................. 370 Data SourceTransact ion Manager ...................................................................... 370 NativeJdbcExtractor ........................................................................................ 370 13.4. JDBC batch operat ion s .................................................................................. 371 Basic batch operat ion s with the JdbcTemplate ................................................. 371 Batch operat ion s with a List of objects ............................................................. 372 Batch operat ion s with multiple batches ............................................................ 373 13.5. Simplifying JDBC operat ion s with the SimpleJdbc classes ................................ 374 Inserting data using SimpleJdbcInsert .............................................................. 374 Retrieving auto-generated keys using SimpleJdbcInsert .................................... 375 Specifying columns for a SimpleJdbcInsert ...................................................... 376 Using SqlParameterSource to provide parameter values ................................... 376 Calling a stored procedure with SimpleJdbcCall ............................................... 377 Explicitly declaring parameters to use for a SimpleJdbcCall ............................... 379 How to define SqlParameters .......................................................................... 380 Calling a stored funct ion using SimpleJdbcCall ................................................. 381 Returning ResultSet/REF Cursor from a SimpleJdbcCall ................................... 381 13.6. Modeling JDBC operat ion s as Java objects ..................................................... 382 SqlQuery ........................................................................................................ 383 MappingSqlQuery ........................................................................................... 383 SqlUpdate ...................................................................................................... 384 StoredProcedure ............................................................................................. 385 13.7. Common problems with parameter and data value handling .............................. 388 Providing SQL type informat ion for parameters ................................................. 389 Handling BLOB and CLOB objects .................................................................. 389 Passing in lists of values for IN clause ............................................................ 390 Handling complex types for stored procedure calls ........................................... 391 13.8. Embedded data base support .......................................................................... 392 Why use an embedded data base? .................................................................. 392 Creating an embedded data base instance using Spring XML ............................ 392 Creating an embedded data base instance programmatically .............................. 392 Extending the embedded data base support ...................................................... 393 Using HSQL ................................................................................................... 393 Using H2 ........................................................................................................ 393 Using Derby ................................................................................................... 393 Testing data access logic with an embedded data base ..................................... 393 13.9. Initializing a Data Source ................................................................................. 394 Initializing a data base instance using Spring XML ............................................. 394 Initializat ion of Other Components that Depend on the Data base ............... 395 14. Object Relat ion al Mapping (ORM) Data Access .......................................................... 397 14.1. Introduct ion to ORM with Spring ..................................................................... 397 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentat ion xii 14.2. General ORM integ rat ion considerat ion s ......................................................... 398 Resource and transact ion management ........................................................... 398 Exception translat ion ....................................................................................... 399 14.3. Hibernate ....................................................................................................... 399 Sess ion Factory setup in a Spring container ...................................................... 400 Implementing DAOs based on plain Hibernate 3 API ........................................ 400 Declarative transact ion demarcat ion ................................................................ 402 Programmatic transact ion demarcat ion ............................................................ 404 Transact ion management strategies ................................................................ 405 Comparing container-managed and locally defined resources ............................ 407 Spurious applicat ion server warnings with Hibernate ......................................... 408 14.4. JDO .............................................................................................................. 409 PersistenceManagerFactory setup ................................................................... 409 Implementing DAOs based on the plain JDO API ............................................. 410 Transact ion management ................................................................................ 412 JdoDialect ...................................................................................................... 413 14.5. JPA ............................................................................................................... 414 Three opt ion s for JPA setup in a Spring environment ........................................ 414 LocalEntityManagerFactoryBean .............................................................. 414 Obtaining an EntityManagerFactory from JNDI ......................................... 415 LocalContainerEntityManagerFactoryBean ............................................... 415 Dealing with multiple persistence units ..................................................... 417 Implementing DAOs based on plain JPA .......................................................... 418 Transact ion Management ................................................................................ 420 JpaDialect ...................................................................................................... 421 15. Marshalling XML using O/X Mappers ......................................................................... 423 15.1. Introduct ion .................................................................................................... 423 Ease of configurat ion ...................................................................................... 423 Consistent Interfaces ...................................................................................... 423 Consistent Exception Hierarchy ....................................................................... 423 15.2. Marshaller and Unmarshaller .......................................................................... 423 Marshaller ...................................................................................................... 423 Unmarshaller .................................................................................................. 424 XmlMapping Exception ..................................................................................... 425 15.3. Using Marshaller and Unmarshaller ................................................................. 425 15.4. XML Schema-based Configurat ion .................................................................. 427 15.5. JAXB ............................................................................................................. 427 Jaxb2Marshaller ............................................................................................. 428 XML Schema-based Configurat ion ........................................................... 428 15.6. Castor ........................................................................................................... 429 CastorMarshaller ............................................................................................ 429 Mapping ......................................................................................................... 429 XML Schema-based Configurat ion ........................................................... 429 15.7. XMLBeans ..................................................................................................... 430 XmlBeansMarshaller ....................................................................................... 430 XML Schema-based Configurat ion ........................................................... 430 15.8. JiBX .............................................................................................................. 431 JibxMarshaller ................................................................................................ 431 XML Schema-based Configurat ion ........................................................... 431 15.9. XStream ........................................................................................................ 432 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentat ion xiii XStreamMarshaller ......................................................................................... 432 V. The Web ........................................................................................................................... 434 16. Web MVC framework ................................................................................................ 435 16.1. Introduct ion to Spring Web MVC framework .................................................... 435 Features of Spring Web MVC ......................................................................... 436 Pluggability of other MVC implementat ion s ...................................................... 437 16.2. The DispatcherServlet .................................................................................... 437 Special Bean Types In the WebApplicat ion Context ........................................... 440 Default DispatcherServlet Configurat ion ........................................................... 441 DispatcherServlet Processing Sequence .......................................................... 441 16.3. Implementing Controllers ................................................................................ 443 Defining a controller with @Controller .............................................................. 443 Mapping Requests With Using @RequestMapping ........................................... 444 New Support Classes for @RequestMapping methods in Spring MVC 3.1 .. 446 URI Template Patterns ........................................................................... 447 URI Template Patterns with Regular Express ion s ..................................... 448 Path Patterns ......................................................................................... 449 Patterns with Placeholders ...................................................................... 449 Matrix Variables ...................................................................................... 449 Consumable Media Types ....................................................................... 450 Producible Media Types .......................................................................... 451 Request Parameters and Header Values ................................................. 451 Defining @RequestMapping handler methods .................................................. 452 Supported method argument types .......................................................... 452 Supported method return types ............................................................... 454 Binding request parameters to method parameters with @RequestParam ... 455 Mapping the request body with the @RequestBody annotat ion .................. 456 Mapping the response body with the @ResponseBody annotat ion ............. 457 Creating REST Controllers with the @RestController annotat ion ................ 457 Using HttpEntity ...................................................................................... 457 Using @ModelAttribute on a method ....................................................... 458 Using @ModelAttribute on a method argument ......................................... 459 Using @Sess ion Attributes to store model attributes in the HTTP sess ion between requests ................................................................................... 461 Specifying redirect and flash attributes ..................................................... 461 Working with "applicat ion /x-www-form-urlencoded" data ............................ 462 Mapping cookie values with the @CookieValue annotat ion ........................ 462 Mapping request header attributes with the @RequestHeader annotat ion ... 463 Method Parameters And Type Convers ion ............................................... 463 Customizing Web Data Binder initializat ion ................................................. 464 Support for the Last-Modified Response Header To Facilitate Content Caching ................................................................................................. 465 Assisting Controllers with the @ControllerAdvice annotat ion ...................... 465 Asynchronous Request Processing .................................................................. 466 Exception Handling for Async Requests ................................................... 467 Intercepting Async Requests ................................................................... 467 Configurat ion for Async Request Processing ............................................ 468 Testing Controllers ......................................................................................... 469 16.4. Handler mappings .......................................................................................... 469 Intercepting requests with a HandlerInterceptor ................................................ 469 Spring Framework 4.0.0.RELEASE Spring Framework Reference Documentat ion xiv 16.5. Resolving views ............................................................................................. 471 Resolving views with the ViewResolver interface .............................................. 471 Chaining ViewResolvers ................................................................................. 473 Redirecting to views ....................................................................................... 474 RedirectView .......................................................................................... 474 The redirect: prefix ................................................................................. 475 The forward: prefix ................................................................................. 475 ContentNegotiatingViewResolver ..................................................................... 475 16.6. Using flash attributes ..................................................................................... 478 16.7. Building URIs ................................................................................................. 479 16.8. Building URIs to Controllers and methods ....................................................... 480 16.9. Using locales ................................................................................................. 480 Obtaining Time Zone Informat ion .................................................................... 481 AcceptHeaderLocaleResolver .......................................................................... 481 CookieLocaleResolver ..................................................................................... 481 Sess ion LocaleResolver ................................................................................... 481 LocaleChangeInterceptor ................................................................................ 482 16.10. Using themes ............................................................................................... 482 Overview of themes ........................................................................................ 482 Defining themes ............................................................................................. 482 Theme resolvers ............................................................................................. 483 16.11. Spring’s multipart (file upload) support ........................................................... 483 Introduct ion .................................................................................................... 483 Using a MultipartResolver with Commons FileUpload ........................................ 484 Using a MultipartResolver with Servlet 3.0 ....................................................... 484 Handling a file upload in a form ...................................................................... 484 Handling a file upload request from programmatic clients .................................. 486 16.12. Handling exception s ..................................................................................... 486 Handler Exception Resolver ............ 报错org.springframework.dao. Data Integ rityViolat ion Exception 原因:最简单的原因可能是数据库外键字段选择了不能为空。 办法:在数据库相应表中改为允许为空即可。 今天出现了这个问题:org.springframework.dao. Data Integ rityViolat ion Exception : Could not execute JDBC batch update; nested exception is org.hibernate. exception . Data Exception : Could not execute JDBC batch updateor... org.springframework.dao. Data Integ rityViolat ion Exception org.springframework.dao. Data Integ rityViolat ion Exception : ### Error updating data base. Cause: java.sql.SQL Exception : Field 'id' doesn't have a default value ### The error may exist in cn/livorth 统一的异常体系 统一的异常体系是整合不同的持久化实现技术(Hibernate、iBatis、JPA、JDO)的关键,Spring提供了一套和实现技术无关、面向DAO层语义的异常体系,并通过转换器将不同持久化技术的异常转换成Spirng的异常。 Spring的DAO异常体系 在很多传统的API或框架中,检查型异常被过多的使用,以至于使用API时,代码里面充满了try/catch样板式的代码。很多情况...