Bellow is my problematic code:
Code:
EntityManager em = JPAUtil.createEntityManager();
try {
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
List<Radcheck> rcs = em.createNamedQuery("com.netnfork.entities.radius.Radcheck.getRadchecks", Radcheck.class).
setParameter("username", "set_a_username").getResultList();
for (Radcheck rc : rcs) {
em.lock(rc, LockModeType.OPTIMISTIC);
}
Radcheck ltCheck = getCheck(rcs, "Login-Time"); // here I get a Radcheck entity based on some properties. Note that this entity is locked in the above for.
em.remove(ltCheck);
tx.commit();
} finally {
//rollback if is the case
}
} finally {
em.close();
}
After I execut this, I get the following exception:
javax.persistence.RollbackException: Error while committing the transaction
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:92)
...............................
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
........................................
Caused by: javax.persistence.OptimisticLockException: Newer version [null] of entity [[com.netnfork.entities.radius.Radcheck#66]] found in database at org.hibernate.ejb.AbstractEntityManagerImpl.wrapLockException(AbstractEntityManagerImpl.java:1427)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1324)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:80)
... 23 more
Caused by: org.hibernate.OptimisticLockException: Newer version [null] of entity [[com.netnfork.entities.radius.Radcheck#66]] found in database at
org.hibernate.action.internal.EntityVerifyVersionProcess.doBeforeTransactionCompletion(EntityVerifyVersionProcess.java:54) at org.hibernate.engine.spi.ActionQueue$BeforeTransactionCompletionProcessQueue.beforeTransactionCompletion(ActionQueue.java:662)
at org.hibernate.engine.spi.ActionQueue.beforeTransactionCompletion(ActionQueue.java:307)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:610)
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)
... 23 more
I colored with red what I think is important.
Can I remove an entity with JPA/Hibernate while it is locked in Optimistic mode? Or am I wrong somewhere? Do you have any suggestions to my problem?
Thanks in advance.