Hibernate - how to catch "integrity constraint violation: unique constraint or index violation"

Ken Vernaillen picture Ken Vernaillen · Nov 14, 2013 · Viewed 19k times · Source

In my table I have a unique constraint. In hibernate, when I add an item that violates that constraint, I want to catch it, so It will update instead of create an item.

When I set no try-catch block around

    updated = query.executeUpdate();

it gets following error

    Caused by: org.hsqldb.HsqlException: integrity constraint violation: unique constraint or index violation: WEEKROOSTERITEMUNI

When I set the following try-catch block

    try {
        updated = query.executeUpdate();

     }    
   catch(PersistenceException e){                                                         
        LOG.debug("this is PersistenceException exception throw");      
    } 

it gets the following error

    Caused by: javax.persistence.RollbackException: Transaction marked as rollbackOnly

When I catch "ConstraintViolationException" I just keep getting the constraint exception, it doesn't catch anything.

    Caused by: org.hsqldb.HsqlException: integrity constraint violation: unique constraint or index violation: WEEKROOSTERITEMUNI

How can I catch this?

Answer

mvb13 picture mvb13 · Nov 14, 2013

To catch unique constraint you should catch this exception ConstraintViolationException