Search code examples
hibernatejpaentitymanagerpersist

hibernate does not add entity to persistencecontext after persist


I have a managedbean that has a list of entity objects of current page. after I create a new object and persist it to db using persist() in a transaction; in another transaction when I call merge(because the entity is in detached state due to previous transaction commit); entitymanager cannot find the object in persistence context and throw a select query to database. Am I missing something or is that normal behavior?

Update: The above problem exists when I use mysql database and autogenerated Id column. It does not exist when I use Oracle where I use sequence for Ids; but still; persistence context should know about the generated id; also is there any way to peek into persistence context to see what entities exits; I am using hibernate btw


Solution

  • It is normal behevior. A persistence context, by default, has the same lifetime of the transaction. And it's completely normal: once the transaction is committed, other transactions might modify the entity, and Hibernate must reload the entity from the database to make sure it doesn't return stale values.