views:

95

answers:

4

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?
}
+1  A: 

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

Aaron Digulla
... and then parsing `getCause().getMessag()`?
deamon
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
A: 

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

hakish
I'm not planning to handle exceptions manually :-)
deamon
A: 

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
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
And how would I know what field caused the constraint violation?
deamon
+2  A: 

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.

Pascal Thivent
Thank you very much for the enlightenment!
deamon