Java – merge JPA entities to return old values
I have two JPA entities that have a two - way relationship
@Entity public class A { @ManyToOne(cascade={CascadeType.PERSIST,CascadeType.MERGE}) B b; // ... }
and
@Entity public class B { @OneToMany(mappedBy="b",cascade={CascadeType.PERSIST,CascadeType.MERGE}) Set<A> as = new HashSet<A>(); // ... }
Now I update some field values of a separated a, which are also related to some B, and vice versa, and then merge it
public String save(A a) { A returnedA = em.merge(a); }
Before updating them, returneda now has the value A. I think
FINEST: Merge clone with references A@a7caa3be FINEST: Register the existing object B@cacf2dfb FINEST: Register the existing object A@a7caa3be FINEST: Register the existing object A@3f2584b8
Indicates that the as referenced in B (still has the old value) is responsible for overwriting the new?
Did anyone suggest how to prevent this from happening?
Thank you very much for any ideas!
Thank you in advance
Solution
Dirk, I encountered a similar problem. The solution (I may not use the API correctly) is intensive Eclipse link maintains a cache of objects. If they are not updated (merged / persisted), the database usually reflects the changes, but cascading objects do not update (especially parents)
(I have declared a a record of joining more than one b) entity:
public class A { @OneToMany(cascade = CascadeType.ALL) Collection b; } public class B { @ManyToOne(cascade = {CascadeType.MERGE,CascadeType.REFRESH}) //I don't want to cascade a persist operation as that might make another A object) A a; }
In the above case, the solution is:
public void saveB(B b) //"Child relationship" { A a = b.getA();//do null checks as needed and get a reference to the parent a.getBs().add(b); //I've had the collection be null //Persistence here entityInstance.merge(a); // or persist this will cascade and use b } public void saveA(A a) { //Persistence entityInstance.merge(a) // or persist }
What you do here is connect the chain from the top down Maintenance is annoying, but it does solve the problem Or you can handle it by checking whether it is detached and refreshed / replaced, but I find it not so satisfactory and exciting
If someone has a better answer to the correct setting, I will be glad to hear it Now I've adopted this approach for my relational entities, which must be annoying for maintenance
Good luck. I'd love to hear a better solution