gpt4 book ai didi

hibernate - 为什么 merge() 返回复制对象?

转载 作者:行者123 更新时间:2023-12-01 09:42:29 26 4
gpt4 key购买 nike

我是 JPA 的新手,阅读了 EntityManager 中存在的合并方法,当我们尝试合并一个分离的对象时,它返回一个副本对象。为什么会返回一个拷贝对象?

我尝试分离一个托管对象,发现分离的对象和merge方法返回的对象的hashcode不同。

Employee emp = new Employee();
emp.setName("Name");

em.persist(emp);

emp = em.find(Employee.class, emp.getId());
em.detach(emp);

emp.setName("New Name");

int empHashCode = emp.hashCode();

Employee managedEmp = em.merge(emp);
int managedHashCode = managedEmp.hashCode();

if(empHashCode == managedHashCode){
System.out.println("Hash Code Equal");
} else{
System.out.println("Hash Code not Equal");
}

输出是“哈希码不相等”。这意味着两个对象都不同,但为什么?

最佳答案

merge() 返回复制对象,请看下面的解释

Applications may not access an entity directly from multiple threads while it is managed by a persistence context. An application may choose, however, to allow entities to be accessed concurrently when they are detached. If it chooses to do so, the synchronization must be controlled through the methods coded on the entity. Concurrent entity state access is not recommended, however, because the entity model does not lend itself well to concurrent patterns. It would be preferable to simply copy the entity and pass the copied entity to other threads for access and then merge any changes back into a persistence context when they need to be persisted.

以上解释抄自《Java EE 8 中的 Pro JPA 2:Java Persistence APIs 深入指南》

关于hibernate - 为什么 merge() 返回复制对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57975310/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com