JPA EntityManager:为什么使用persist() 而不是merge()? [英] JPA EntityManager: Why use persist() over merge()?

查看:33
本文介绍了JPA EntityManager:为什么使用persist() 而不是merge()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

EntityManager.merge() 可以插入新对象并更新现有对象.

EntityManager.merge() can insert new objects and update existing ones.

为什么要使用 persist()(它只能创建新对象)?

Why would one want to use persist() (which can only create new objects)?

推荐答案

无论哪种方式都会将实体添加到 PersistenceContext,区别在于您之后如何处理实体.

Either way will add an entity to a PersistenceContext, the difference is in what you do with the entity afterwards.

Persist 获取一个实体实例,将其添加到上下文并管理该实例(即,将跟踪对实体的未来更新).

Persist takes an entity instance, adds it to the context and makes that instance managed (ie future updates to the entity will be tracked).

Merge 返回状态合并到的托管实例.它确实返回 PersistenceContext 中存在的内容或创建实体的新实例.在任何情况下,它都会从提供的实体复制状态,并返回托管副本.您传入的实例将不会被管理(您所做的任何更改都不会成为事务的一部分 - 除非您再次调用合并).虽然您可以使用返回的实例(托管实例).

Merge returns the managed instance that the state was merged to. It does return something what exists in PersistenceContext or creates a new instance of your entity. In any case, it will copy the state from the supplied entity, and return managed copy. The instance you pass in will not be managed (any changes you make will not be part of the transaction - unless you call merge again). Though you can use the returned instance (managed one).

也许代码示例会有所帮助.

Maybe a code example will help.

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.

Scenario 1 and 3 are roughly equivalent, but there are some situations where you'd want to use Scenario 2.

这篇关于JPA EntityManager:为什么使用persist() 而不是merge()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆