javajpajavadb

How to catch java.sql.SQLIntegrityConstraintViolationException?


My application uses JPA+JavaDB and when I try to persist an object that violates a constraint I get SQLIntegrityConstraintViolationException on console.

That is OK but I can't catch that exception, why?


This is a sample of my code where I would like to catch the exception. If I look at the documentation of persist(), there is no sign of SQLIntegrityConstraintViolationException.

em.getTransaction().begin();
em.persist(object);
em.getTransaction().commit();

Part of the console stack trace:

[EL Warning]: 2013-09-15 16:38:57.571--UnitOfWork(459929151)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: A instrução foi interrompida, porque iria gerar um valor duplicado da chave em uma restrição de chave primária ou de unicidade identificada por 'SQL130819202336721' definida em 'CORRETORA'.
Error Code: -1
Call: UPDATE CORRETORA SET NOME = ? WHERE (ID = ?)
    bind => [2 parameters bound]
Query: UpdateObjectQuery(Corretora[ id=7 ])
javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: A instrução foi interrompida, porque iria gerar um valor duplicado da chave em uma restrição de chave primária ou de unicidade identificada por 'SQL130819202336721' definida em 'CORRETORA'.
Error Code: -1
Call: UPDATE CORRETORA SET NOME = ? WHERE (ID = ?)
    bind => [2 parameters bound]
Query: UpdateObjectQuery(Corretora[ id=7 ])
    at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:157)
    at br.meuspila.util.AbstractCrud.persist(AbstractCrud.java:50)
    at br.meuspila.corretora.CorretoraRN.persist(CorretoraRN.java:30)
    at br.meuspila.javafx.EditarCorretoraController$1.handle(EditarCorretoraController.java:66)
    at br.meuspila.javafx.EditarCorretoraController$1.handle(EditarCorretoraController.java:51)
...

Solution

  • The log is telling you why. The SQLIntegrityConstraintViolationException is wrapped inside an org.eclipse.persistence.exceptions.DatabaseException. You can catch this exception and do something about the SQLIntegrityConstraintViolationException

    Not knowing your code, it's impossible to tell you where to change it, but if you wanted to really catch SQLIntegrityConstraintViolationException, you would have to do so before it got wrapped in the other exception.