EntityManager.merge()
可以插入新对象并更新现有对象。
为什么要使用persist()
(只能创建新对象)?
无论哪种方式都会将实体添加到 PersistenceContext 中,不同之处在于您随后对该实体执行的操作。
Persist 获取一个实体实例,将其添加到上下文中并使该实例受到管理(即,将跟踪该实体的未来更新)。
合并返回与状态合并的托管实例。它确实返回 PersistenceContext 中存在的内容或创建实体的新实例。在任何情况下,它都会从提供的实体复制状态,并返回托管副本。您传入的实例将不会被管理(您所做的任何更改都不会成为事务的一部分 - 除非您再次调用合并)。尽管您可以使用返回的实例(托管实例)。
也许代码示例会有所帮助。
MyEntity e = new MyEntity();
// scenario 1
// tran starts
em.persist(e);
e.setSomeField(someValue);
// tran ends, and the row for someField is updated in the database
// scenario 2
// tran starts
e = new MyEntity();
em.merge(e);
e.setSomeField(anotherValue);
// tran ends but the row for someField is not updated in the database
// (you made the changes *after* merging)
// scenario 3
// tran starts
e = new MyEntity();
MyEntity e2 = em.merge(e);
e2.setSomeField(anotherValue);
// tran ends and the row for someField is updated
// (the changes were made to e2, not e)
场景 1 和 3 大致相同,但在某些情况下您需要使用场景 2。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)