我试图在 mybatis 上捕获
SQLException
,但它不允许我使用它。
try{
session.insert("insertMyData", insertData);
}
catch (SQLException sqle) { // mybatis not supporting SQLException
//exception handling code
}
所以我尝试使用
SqlSessionException
try{
session.insert("insertMyData", insertData);
}
catch (SqlSessionException sqle) { // mybatis support this
//exception handling code
}
但使用此方法的问题是并非所有 SQL 异常都会被捕获。如果我尝试插入重复数据,它不会捕获
SQLIntegrityConstraintViolationException
mybatis中有没有办法捕获所有SQL异常。
尽管没有记录,执行
SqlSession#insert
或 SqlSession#selectList
或任何其他 API 方法,如果出现错误,最终都会出现 PersistenceException
。 可以在此处找到 源代码。
这很重要,因为此异常的
cause
将是您正在寻找的驱动程序特定的 SQLException
:
try {
sqlSession.insert("anything", object);
} catch (PersistenceException e){
Throwable cause = e.getCause(); // Here is the native SQLException from the driver
}