A client application supplies a stale entity which is to be merged by Hibernate. Taking a very simple example.
public Entity update(Entity entity) {
return entityManager.contains(entity) ? entity : entityManager.merge(entity);
}
Entity
is a detached, stale entity supplied by a web application, for example. The method is executed in an active JTA transaction (or resource local).
Optimistic locking has been enabled by introducing a @Version
field in the entity given.
When an entity to be merged had already been deleted, javax.persistence.OptimisticLockException
is expected to be thrown which does not happen. Hibernate performs INSERT
instead which is completely unexpected. Inserting a stale entity instead of throwing the javax.persistence.OptimisticLockException
is something going against locking.
"Insert or update" is a story apart which should be suspended by throwing the javax.persistence.OptimisticLockException
, if a stale or deleted (nonexistent) entity is passed to merge()
, if optimistic locking is implemented.
EclipseLink throws the javax.persistence.OptimisticLockException
as expected in case a stale or deleted / nonexistent entity is passed to merge()
.
Is there a way to make Hibernate throw the javax.persistence.OptimisticLockException
, when a stale or nonexistent entity is passed to merge()
?
I expect there should be some configurable property in persistence.xml
to apply it globally application-wide or annotations to apply it to a specific entity.
I am currently using Hibernate 5.0.5 final.
Updated to Hibernate 5.0.6 final.