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?
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.