下面是代码示例,我想捕获mybatis抛出的异常:
String resource = "com/sureone/server/db/mybatis-config.xml";
Reader reader = null;
try {
reader = Resources.getResourceAsReader(resource);
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
sqlSession = factory.openSession(true);
tUserMapper = sqlSession.getMapper(TUserMapper.class);
if(tUserMapper.insert(user)>0){ <===Exception throwed here for duplicate entry problem
return verifyLogin(user.getAccount(),user.getPassword());
}
return null;
我要捕获的异常:
org.apache.ibatis.exceptions.PersistenceException:
### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'userName' for key 'account_UNIQUE'
最佳答案
您可以像往常一样捕获PersistenceException
:
try {
...
} catch (PersistenceException pe) {
}
但不要忘记这个 Exception
包装了真正的异常:
来自 MyBatis 代码
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error committing transaction. Cause: " + e, e);
}
因此,如果您想了解 PersistenceException
的原因,您必须对 PersistenceException< 使用
.getCause()
方法
注意 MyBatis 也可以启动它自己的 PersistenceException
(TooManyResultException
,BindingException
...) 类,那些不会有原因 Exception
包装。
关于java - 如何捕获mybatis异常 "org.apache.ibatis.exceptions.PersistenceException"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16755443/