JPA EntityManager:为什么在merge()上使用persist()? [英] JPA EntityManager: Why use persist() over merge()?

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

问题描述

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 creates a new instance of your entity, copies the state from the supplied entity, and makes the new copy managed. 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).

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

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:为什么在merge()上使用persist()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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