DuplicateKeyException和MySQLIntegrityConstraintViolationException异常

主题:org.springframework.dao.DuplicateKeyException
和com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException

违反唯一约束索引报错信息:
org.springframework.dao.DuplicateKeyException: 
### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1111' for key 'abc'
### The error may involve cn.richinfo.spring.mapper.TYqbdhzUserprizeMapper.insertSelective-Inline
### The error occurred while setting parameters
### SQL: insert into t_abc ( openid, mobile, createtime ) values ( ?, ?, ? )
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1111' for key 'uni_t_yqbdhz_userprize_mobile'
; SQL []; Duplicate entry '1111' for key ''; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1111' for key ''
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:241)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:73)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:371)
at com.sun.proxy.$Proxy9.insert(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.insert(SqlSessionTemplate.java:240)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:51)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:52)
at com.sun.proxy.$Proxy14.insertSelective(Unknown Source)
at cn.richinfo.spring.service.PrizeService.insertSelective(PrizeService.java:18)
at cn.richinfo.spring.service.PrizeService$$FastClassByCGLIB$$af64197c.invoke()
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at cn.**.spring.service.PrizeService$$EnhancerByCGLIB$$6df4d56c.insertSelective()
at cn.**.spring.web.HomeController.goToDraw(HomeController.java:260)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)





疑问:1)使用
try{
}catch(com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException){
//无法捕获该异常
}
2)而使用
try{
}catch(org.springframework.dao.DuplicateKeyException:){
//可以捕获该异常
}

解答:

Spring3 Mybatis 异常处理


通常在 Dao 层将所有异常都转嫁到 Spring 的 RuntimeException 体系中来 -- org.springframework.dao.DataAccessException
Spring的DAO框架没有抛出与特定技术相关的异常,例如SQLException或HibernateException,抛出的异常都是 与特定技术无关的org.springframework.dao.DataAccessException类的子类,避免系统与某种特殊的持久层实现耦 合在一起。DataAccessException是RuntimeException,是一个无须检测的异常,不要求代码去处理这类异常,遵循了 Spring的一般理念:异常检测会使代码到处是不相关的catch或throws语句,使代码杂乱无章;并且 NestedRuntimeException的子类,是可以通过NestedRuntimeException的getCause()方法获得导致该异 常的另一个异常。Spring的异常分类有
Spring的DAO异常层次
异常
何时抛出
CleanupFailureDataAccessException 一项操作成功地执行,但在释放数据库资源时发生异常(例如,关闭一个Connection)
DataAccessResourceFailureException 数据访问资源彻底失败,例如不能连接数据库
DataIntegrityViolationException Insert或Update数据时违反了完整性,例如违反了惟一性限制
DataRetrievalFailureException 某些数据不能被检测到,例如不能通过关键字找到一条记录
DeadlockLoserDataAccessException 当前的操作因为死锁而失败
IncorrectUpdateSemanticsDataAccessException Update时发生某些没有预料到的情况,例如更改超过预期的记录数。当这个异常被抛出时,执行着的事务不会被回滚
InvalidDataAccessApiusageException 一个数据访问的JAVA API没有正确使用,例如必须在执行前编译好的查询编译失败了
invalidDataAccessResourceUsageException 错误使用数据访问资源,例如用错误的SQL语法访问关系型数据库
OptimisticLockingFailureException 乐观锁的失败。这将由ORM工具或用户的DAO实现抛出
TypemismatchDataAccessException Java类型和数据类型不匹配,例如试图把String类型插入到数据库的数值型字段中
UncategorizedDataAccessException 有错误发生,但无法归类到某一更为具体的异常中
Spring的DAO异常层次是如此的细致缜密,服务对象能够精确地选择需要捕获哪些异常,捕获的异常对用户更有用的信息,哪些异常可以让她继续在调用堆栈中向上传递。
于是,我们在dao中只需要抛出这个运行时异常,我们就可以在
/**
* 根据时间获取日KPI数据
* @param date 日期
* @return
*/
public List getKPIOfDayDataByDate(String date) throws DataAccessException;
并在它的实现类中也抛出这么个异常。
这样,在调用这个方法的时候,我们捕获这个异常即可:
try {
list = kpiDao.getKPIOfDayDataByDate(date);
} catch(DataAccessException e) {
System.out.println("test:" + e.getMessage());
}
这样就可以捕获相应的异常了。
这是打印出来的信息
test:nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure



Spring API:
http://docs.spring.io/spring/docs/4.2.x/javadoc-api/
转载:
https://my.oschina.net/yyjava/blog/160380

你可能感兴趣的:(Java)