Hi,
I’m using Hibernate 4.2.21 and I use OPTIMISTIC FORCE INCREMENT to update version of parent entities in 1-to-many relations if the children get updated. This works fine unless the parent is removed in the same transaction.
Actually this can be reduced to a very simple example:
EntityManager em = ...
MyVersionedEntity entity = ...
em.lock (entity, LockModeType.OPTIMISTIC_FORCE_INCREMENT)
em.remove (entity)
em.getTransaction ().commit()
always gives the following exception:
Caused by: org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.syncrotess.gen.model.jpa.MyVersionedEntity#4621066252771655745]
at org.hibernate.persister.entity.AbstractEntityPersister.forceVersionIncrement(AbstractEntityPersister.java:1834)
at org.hibernate.action.internal.EntityIncrementVersionProcess.doBeforeTransactionCompletion(EntityIncrementVersionProcess.java:53)
at org.hibernate.engine.spi.ActionQueue$BeforeTransactionCompletionProcessQueue.beforeTransactionCompletion(ActionQueue.java:748)
at org.hibernate.engine.spi.ActionQueue.beforeTransactionCompletion(ActionQueue.java:338)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:490)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:105)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:75)
The underlying issue is that the EntityIncrementVersionProcess trie to update the version though the entity is deleted. It works if I switch to PESSIMISTIC_FORCE_INCREMENT but that is hard to achieve in my concrete scenario, because at the point where I set the lock I cannot know if the entity is being removed later on and upgrading the OPTIMISTIC_FORCE_INCREMENT to a PESSIMISTIC_FORCE_INCREMENT does not work, i.e. Hibernate still tries to update the version on commit.