When你关闭一个EntityManager,它的所有被管实体变成分开。没有什么不妥。您仍然可以使用分离的实体作为java对象,但更改它们的属性不会影响数据库(除非重新附加它)。同样,一旦一个实体被分离,你不能再遵循在实体仍然连接时尚未初始化的延迟加载的关系。
您可以稍后通过调用其上的merge()
方法将分离的实体重新附加到不同的EntityManager。例如:
// Here myEntity is managed by entityManager1.
SomeEntity myEntity = entityManager1.find(SomeEntity.class, id);
// myEntity becomes detached.
entityManager1.close();
// I can still work with the java object.
myEntity.setSomeProperty("blah");
// Here myEntity becomes managed by entityManager2.
// It basically retrieves the current entity from the DB (based on its ID),
// then apply any change that was made to it while it was detached.
myEntity = entityManager2.merge(myEntity);
// If you commit at this point, the changes made to myEntity while
// it was detached will be persisted to the DB.
防止发生变更时数据库“你背后”,而在实体分离(例如,另一个应用程序修改相应的行),你可以使用一个@Version场的情况。每次修改实体时,其版本都会发生变化。如果您尝试合并分离的实体,并且从数据库中检索的当前版本具有不同的版本,则会抛出OptimisticLockException
。
非常感谢大卫,我感谢你的例子代码和你的快速答案。无论如何,你能帮我解决最后一个问题吗?你从哪里得到你的信息?在经验中还是有关于JPA的非常详细的文章/描述?我已经阅读了甲骨文的Jave EE教程,但它看起来很浅,在JPA中对我来说不是很深...(并且关于这个主题也有点短小) – czupe
无论如何添加了标记并接受它!谢谢! – czupe
我对这本书非常依赖(不幸的是不幸):http://www.amazon.com/Pro-JPA-Mastering-Persistence-Technology/dp/1430219564请参阅第6章中的“分离和合并”一节。 –