Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why merge() return copy object?

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?

like image 305
Rashi Neema Avatar asked Oct 17 '25 10:10

Rashi Neema


2 Answers

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"

like image 79
yashjain12yj Avatar answered Oct 21 '25 14:10

yashjain12yj


In addition to answer added by @yashjain12yj

There are many cases to consider.

  • if the entity is already in the persistence context (session), no action is taken, except for cascades
  • if the entity is detached, a copy (object’) is returned, which is attached (managed)
  • if the entity is transient (new instance), it is saved and a persistent (and managed) copy is returned
  • if the entity is detached, but an object with the same identifier exists in the current entity manager, then the state of the detached object is copied into the current persistent entity, and it (the current) is returned

More detail here

like image 31
MyTwoCents Avatar answered Oct 21 '25 14:10

MyTwoCents



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!