3

テーブルに行を挿入しようとする Java アプリがあり 、一意キー制約の重複データを挿入しようとするとcom.​ibatis.​common.​jdbc.​exception.NestedSQLException原因でスローされます。com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException

その例外をキャッチするにはどうすればよいですか?

4

2 に答える 2

3

根本原因にたどり着くには、次のようなことができます。

try {
    //insert
} catch (NestedSQLException e) {
    Throwable t = e;
    while(t.getCause() != null) {
        t = t.getCause();
    }
    //in your situation, now t should be MySQLIntegrityConstraintViolationException 
    if (t instanceOf MySQLIntegrityConstraintViolationException) {
        //do something
    }
}
于 2012-11-28T10:22:55.410 に答える
2

それが誰かを助ける場合に備えて。@tibtof は正しく、次のようになりました。

public int insert(MyObject myObject) {
    int recCount = -1;
    try {
        recCount = insert(myObject, MyObjectMapper.class);
    } catch (Throwable e) {
        Throwable t = e;
        while (t.getCause() != null) {
            t = t.getCause();
            if (t instanceof SQLIntegrityConstraintViolationException) {
                // get out gracefully.
                recCount = -1;
                return recCount;
            }
        }
        //Something else wicked wrong happened. 
        LogUtils.error(log, e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    }
    return webGroup.getWebGroupId().intValue();
}
于 2013-03-22T14:19:55.050 に答える