JPA object union returns old values

I have two JPA objects that have bidirectional communication between them.

@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 values โ€‹โ€‹of the fields of the detachable A , which also relates to some Bs and vice versa and combine it back

 public String save(A a) { A returnedA = em.merge(a); } 

returnedA now has values โ€‹โ€‹A before updating them. I suppose that

  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 link in B (which still has the old values) is responsible for overwriting the new ones?

Does anyone have a hint on how to prevent this?

Any idea is much appreciated!

Thanks in advance.

+4
source share
1 answer

Dirk, I had a similar problem, and the solution (I may not have used the API correctly) was intense. Eclipselink maintains an object cache, and if they are not updated (merged / saved), the database reflects the change, but cascading objects are not updated (especially parents).

(I declared A as an entry connecting several B) Objects:

 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 workaround 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 physically cascades the chain fusion from above. This is annoying, but it solves the problem. Alternatively, you can handle this by checking to see if it disconnects and is updated / replaced, but I found this to be less desirable and annoying.

If anyone has a better answer regarding the right setup, I would be glad to hear it. I have now used this approach for my relational entities, and this is definitely annoying.

Good luck with this, I would like to hear a better solution.

+1
source

All Articles