1
votes

In one of my concurrent insert operation in the same table I'm getting the ConstraintViolationException.

javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: 
could not insert:

Can Hibernate Optimistic Lock can help me in this regard? As far I know that Optimistic locking work in update/delete operation on same record in the database.

Does it work for insert query as well?

I have created a version column in the target table (entity). But still getting the same exception(no optimisticLockException or StaleObjectStateException).

1

1 Answers

4
votes

Optimistic locking is used to prevent overwriting existing data with stale data. Since you can't overwrite one insert with another, there is no point in performing an optimistic lock check as the database already throws its own exceptions - a ConstraintViolation exception. A PersistenceException is all you can get from flush or commit if the insert fails. You may be able to configure your JPA provider to throw an EntityExistsException when calling persist if it was already inserted, unless you are getting this on persist already in which case you might be hitting https://hibernate.atlassian.net/browse/HHH-4131