如何在mybatis中捕获SQLException

问题描述 投票:0回答:1

我试图在 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异常。

java mybatis sqlexception
1个回答
0
投票

尽管没有记录,执行

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
    }
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.