I am new to JPA, read about merge method which is present in EntityManager, that return a copy object when we try to merge a detached object. Why does it returns a copy object?
I tried to detach a managed object and found that the hashcode of the detached object and the object returned by the merge method is different.
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");
}
The output is "Hash Code not Equal". Which means both the object are different but why?
The merge() returns the copy object, please find the below explanation
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.
The above explanation is copied from "Pro JPA 2 in Java EE 8: An In-Depth Guide to Java Persistence APIs"
In addition to answer added by @yashjain12yj
There are many cases to consider.
More detail here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With