hibernate does not add entity to persistencecontext after persist

青春壹個敷衍的年華 提交于 2020-01-11 06:54:25

问题


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


回答1:


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.




回答2:


This is normal behaviour.. if the instance is not in the persistence context, it needs to know if it exists or not (should be overwritten or newly created later).

ID generation: the generated ID is usually returned on call to persist(..), which is quite handy, so your application can use the newly created ID right away, no need to wait for the end of the transaction.

You can check if a given object is in the persistence context by calling: https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Session.html#contains%28java.lang.Object%29



来源:https://stackoverflow.com/questions/13187449/hibernate-does-not-add-entity-to-persistencecontext-after-persist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!