How to handle JPA unique constraint violations?

Viewed 59021

When a unique constraint is violated, a javax.persistence.RollbackException is thrown. But there could be multiple reasons to throw a RollbackException. How can I find out that a unique constraint was violated?

try {
    repository.save(article);
}
catch(javax.persistence.RollbackException e) {
    // how to find out the reason for the rollback exception?
}
8 Answers

This might very late for you but here's how I solved it for PostGres.

catch (DataIntegrityViolationException e) {

            for (Throwable t = e.getCause(); t != null; t = t.getCause()) {

                if (PSQLException.class.equals(t.getClass())) {
                    PSQLException postgresException = (PSQLException) t;

                    // In Postgres SQLState 23505=unique_violation
                    if ("23505".equals(postgresException.getSQLState())) {
                        throw new CustomDataAlreadyExistsException("YourErrorCode", e);
                    }
                }
            }
            throw new SomeOtherException("YourErrorCode2", e);

        }

You have to catch javax.persistence.PersistenceException. Thrown exception is org.hibernate.exception.ConstraintViolationException.

Exception Message : org.hibernate.exception.ConstraintViolationException: Duplicate entry '893073116V-1234567' for key 'nic_account_no'

Related