Handling iBatis NestedSQLException

2019-07-05 06:11发布

问题:

I have a java app that try to insert a row into the table and com.​ibatis.​common.​jdbc.​exception.NestedSQLException is thrown with the Cause com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException When I try to insert dublicate data for a unique-key constraint.

How do I catch that exception?

回答1:

To get to the root cause you can do something like this:

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
    }
}


回答2:

In case it helps someone. @tibtof's is correct and got me to:

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();
}


标签: java ibatis