Java JPA / Hibernate: how to avoid multiple instances of an object in a session?

I understand that JPA does not work as I expected, since often I get multiple instances of the same object in a session.

Here's an example study: a parent has a set of children mapped to @OneToMany

In one method:

  • get an instance of the parent P object
  • Download the collection of the child using P.getChilds (): it contains an instance of C1 and C2
  • then find a specific Child with an optimized JPA request for which Parent P has a parameter: Child C = dao.getSpecificChild (P)

Here I would expect C to become one of two already loaded instances (from C1 or C2). I thought JPA would check for an existing instance in the current session. But JPA will load a new instance of C (regardless of whether it has C1 or C2 here).

So, I get two different instances of C.

My question is: is this the expected behavior? If so, how can I reconcile entity instances in a session?

amuses

+3
source share
2 answers

How can I reconcile entity instances in a session?

If you want to pass state from object a to object b, you can do the following:

entityManager.merge(a);
entityManager.refresh(b);
+2
source

, C, , Cs ( , txn), , , , , DataNucleus ( JDO, ), , L1.

0

Source: https://habr.com/ru/post/1786341/


All Articles