java - 合并与查找以更新实体 JPA

标签 java jakarta-ee jpa persistence

摘自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/

相关文章:

mysql - MySQL 解释计划、多字段索引和 OR 子句的问题

Tomcat 上的 Spring/JPA/Vaadin - 非持久实体

java - 带有可视化图表的 JPA 数据库建模器

java - IntelliJ IDEA 13 Scala Plugin & Eclipse Kepler 编译报错

java - 在存储在 HashMap 中的 ArrayList 中搜索值

java - 从代码中监控内存使用情况

multithreading - EntityManager 线程安全和 Java EE

mysql - hibernate 设置属性以触发数据库更新

java - red5 是否读取 tomcat-users.xml

java - 在哪些情况下我们可以使用 public static void main(String... args) 而不是 public static void main(String[] args)