摘自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
例子: 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);
}
}
然后,说:
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.
例子: 此处附加了 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);
}
因此,看起来对于小的更新和创建操作策略 find()
然后一个一个地设置新值是很方便的。但是!对于数据的大更新(即集合),最好有一个分离的实体及其所有关系(使用 CascadeType.Merge)并进行大的 merge()
。
好的,但是为什么?
最佳答案
因为如果你的 bean 有很多属性,如果你正在处理一个分离的对象,JPA 将在合并过程中一个一个地检查所有属性。
现在,如果您有一个具有 200 个属性的 bean 并且只想更改 1 个字段,那么 JPA 更容易只获取托管版本(在内部,JPA 知道托管实体的一个字段何时“脏”或不),那么它将只处理那个特定的属性。
关于java - 合并与查找以更新实体 JPA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21175450/