2

これがコード サンプルです。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'
4

2 に答える 2

4

PersistenceException通常どおりにキャプチャできます。

try {
  ...
} catch (PersistenceException pe) {

}

Exceptionただし、これが実際のものをラップしていることを忘れないでください。

MyBatisコードから

} catch (Exception e) {
  throw ExceptionFactory.wrapException("Error committing transaction.  Cause: " + e, e);
}

そのため、原因を把握したい場合は、メソッドPersistenceExceptionを使用する必要があります.getCause()PersistenceException

MyBatis は独自のPersistenceException( TooManyResultExceptionBindingException...) クラスを起動すること Exceptionもできることに注意してください。

于 2014-02-10T13:45:55.053 に答える