31

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?
}
Rob Hruska
  • 115,151
  • 29
  • 164
  • 188
deamon
  • 83,933
  • 102
  • 303
  • 431

8 Answers8

21

How can I find out that a unique constraint was violated?

Exception are chained, you have to call getCause() recursively to get the provider specific exception (and maybe go down to the SQLException) to translate it into something your application can handle nicely for your user. The following will print the chain of exception:

for (t = e.getCause(); t != null; t = t.getCause()) {
    logger.debug("Exception:" + t);
}

For the exception handling and the "translation", you could do something like what Spring does (see the various JpaDialect classes, e.g. HibernateJpaDialect to get an idea).

All this is not nice, this code won't be portable and finding what attribute(s) caused the violation won't be easy. This somehow confirms that there is no elegant and portable way to handle constraint violations in JPA.

Community
  • 1
  • 1
Pascal Thivent
  • 549,808
  • 132
  • 1,049
  • 1,115
5

You can use the following :

If you are using spring framework then you can use :

org.springframework.dao.DataIntegrityViolationException

If standard JPA following can be used

org.hibernate.exception.ConstraintViolationException

At sql level following can be used :

java.sql.SQLIntegrityConstraintViolationException

Nico Van Belle
  • 4,557
  • 4
  • 27
  • 46
AaMng
  • 169
  • 2
  • 4
3

Use e.getCause() to examine what caused the rollback.

Aaron Digulla
  • 310,263
  • 103
  • 579
  • 794
  • 1
    ... and then parsing `getCause().getMessag()`? – deamon Aug 17 '10 at 12:28
  • 2
    That depends on what exception you will get. If it's an `SQLException,` check the error and SQLStatus. But some frameworks like Spring translate these to something more meaningful (`DataIntegrityViolationException`). – Aaron Digulla Aug 18 '10 at 07:38
3

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

        }
AjayPS
  • 31
  • 4
2

compiler returns the exception SQLIntegrityConstraintViolationException, while trying to violate unique constraint.

Use the following catch block concept, to handle proper exceptions.

catch(SQLIntegrityConstraintViolationException e) 
{
  // Error message for integrity constraint violation
}
catch(Exception e)
{
 // Other error messages
}
abhijitcaps
  • 574
  • 7
  • 7
0

i think printing the stack trace will help you to know this. e.printStackTrace();

hakish
  • 3,890
  • 7
  • 37
  • 55
0

You can do like this :

StringWriter writer=new StringWriter(); //remains the message from stack trace.
e.printStackTrace(new PrintWriter(writer));
String message=writer.toString(); // gets the message of full stack trace.

And then view the information of exception.

Mercy
  • 47
  • 3
  • Ok, but what should I do with the StackTrace? Parsing a string with the stack trace is somewhat ugly, but perhaps the only possibility. – deamon Aug 17 '10 at 14:38
  • 1
    And how would I know what field caused the constraint violation? – deamon Aug 17 '10 at 15:23
0

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'

codezoner
  • 984
  • 2
  • 11
  • 29