Java 合并与查找以更新实体 JPA
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21175450/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
merge vs find to update entities JPA
提问by Sergio
From the book Pro EJB3 JPA:
来自Pro EJB3 JPA一书:
The most common strategy to handle this (-update entities-) in Java EE application that uses JPA is to place the results of the changes into detached entity instances and merge the pending changes into a persistence context so that they can be written to the database
在使用 JPA 的 Java EE 应用程序中处理此(-更新实体-)的最常见策略是将更改的结果放入分离的实体实例中,并将挂起的更改合并到持久性上下文中,以便将它们写入数据库
Example: The empparam is a detached entity
例如: 该EMP参数是分离实体
@Stateless
public class EmployeeServiceBean {
@PersistenceContext
EmtityManager em;
public void updateEmployee(Employee emp){
if(em.find(Employee.class, emp.getId()) == null){
throw new IllegalArgumentException("Unknown Employee id")
}
em.merge(emp);
}
}
Then, says:
然后说:
If the amount of information being udated is very small, we can avoid the detached object and merge() operation entirely by locating the managed version and manually copying the changes into it.
如果更新的信息量非常小,我们可以通过定位托管版本并手动将更改复制到其中来完全避免分离对象和 merge() 操作。
Example: Here the empis attached
示例: 此处附加了emp
public void updateEmployee(int id, String newName, long newSalary) {
Employee emp = em.find(Employee.class, id);
if(emp==null){
throw new IllegalArgumentException("Unknown Employee id")
}
emp.setEmpName(newName);
emp.setSalary(newSalary);
}
So, looks like for small updates and create operations the strategy find()
and then set new values one by one is convenient. But!, for big updates of data (i.e collections) is preferred have a detached entity and all it's relations (with CascadeType.Merge) and do a big merge()
.
所以,看起来对于小更新和创建操作的策略find()
然后一一设置新值是方便的。但是!对于数据的大更新(即集合),最好有一个独立的实体和它的所有关系(使用 CascadeType.Merge)并做一个大的merge()
.
OK, but why?
好的,但为什么?
采纳答案by Sergio
Because if your bean has a lot of attributes, JPA will check one by one in the merge process, for all attributes, if you're dealing with a detached object.
因为如果你的bean有很多属性,JPA会在合并过程中一一检查,对于所有的属性,如果你是在处理一个分离的对象。
Now, if you have a bean with 200 atrributes and want to change only 1 field, it′s easier for JPA to just get the managed version (internally, JPA knows when one field of a managed entity is "dirty" or not), then it will only deal with that specific attribute.
现在,如果您有一个具有 200 个属性的 bean 并且只想更改 1 个字段,那么 JPA 更容易获得托管版本(在内部,JPA 知道托管实体的一个字段何时“脏”),那么它只会处理那个特定的属性。