5

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?

Ken Vernaillen
  • 859
  • 1
  • 7
  • 37
  • Suggest to go through this link in SO [SO Link][1] [1]: http://stackoverflow.com/questions/2167730/checks-for-constraint-violation-before-persisting-an-entity – aksappy Nov 14 '13 at 08:58

2 Answers2

0

To catch unique constraint you should catch this exception ConstraintViolationException

mvb13
  • 1,514
  • 3
  • 18
  • 33
-1

The RollbackException is thrown at a higher level because @Transactional is set in that higher lever, so you can't catch it on that level. You need to catch it in the layer of your transaction.

A better way is to do a check if the object already exists on the database layer. A check-function. That check function is a get by the unique constraints. This is better because you don't need to catch exceptions.

You already need that get-function of the object, because you later want to merge that object. You don't want to merge a detached instance.

Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117
Ken Vernaillen
  • 859
  • 1
  • 7
  • 37
  • 6
    This doesn't work in the face of concurrent access to the database. Between the time you check and the time yo do something else, another session may have changed the database state. – WW. May 24 '18 at 00:51