JPA : 区分 persist() 和 merge()

区别概述

  • 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 的修改此时会被更新到数据库

附图辅助理解以上概念 : JPA实体状态转换

在这里插入图片描述

来源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值