Search code examples
javaibatis

Handling iBatis NestedSQLException


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?


Solution

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