区别概述
-
persist
- Insert a new register to the database
- Attach the object to the entity manager.
-
merge
- Find an attached object with the same id and update it.
- If exists update and return the already attached object.
- If doesn’t exist insert the new register to the database.
-
persist() efficiency:
- It could be more efficient for inserting a new register to a database than merge().
- It doesn’t duplicates the original object.
-
persist() semantics:
- It makes sure that you are inserting and not updating by mistake.
例子说明
例子1
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
// 事务结束, 字段 e.someField 的改动会更新到数据库
// 原因 : 经过 persist, e 已经是一个 managed 实体对象,处于被修改跟踪的状态
例子2
// 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)
// 事务结束, 字段 e.someField 的修改不会被更新到数据库,
// 原因解释 : 合并过程中有两个对象,合并来源对象,合并目标对象 ,整个合并过程中,参数对象 e
// 作为合并来源对象(而不是合并目标对象),一直都不会设置到`managed`对象,因此合并结束后的对
// e.someFiled 的修改也不会被更新到数据库。
// 注意 : merge 方法返回的对象才是合并目标对象
例子3
// 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)
// 事务结束,作为合并(`merge`)目标对象,e2处于`managed`状态,对其属性 e.someField 的修改此时会被更新到数据库