hibernatetransactionsejb-3.0persistence-manager

How to Persist and Refresh in the same Transaction


i have multiple users. To prevent concurrency, i write something like that:

@EJB
PersistenceManagerRemote persistenceManager;

persistenceManager.lock(decidableEntity, LockModeType.READ);
persistenceManager.refresh(decidableEntity);

this worked for me. However, if i persist something and then i call this code in the same transaction then i got en error.

 javax.persistence.PersistenceException: org.hibernate.HibernateException: this instance does not yet exist as a row in the database

When i persist an entity, database context is not effected until the transaction finishes. So when i refresh, it tries to find the entity on database, so error arises. Do you have a solution? I cannot divide into two transaction. I should also consider concurrency. What can i do?


Solution

  • You need to call em.flush() to write all the pending changes to the database. persist() only makes a transient entity attached to the persistence context. Hibernate only flushes when necessary, in order to avoid them if they're not, and to be able to send then into a batch.