I realize JPA doesn't work as I expected, as I often end up with multiple instance of a single entity in a session.
Here's the study case: A parent has a collection of child mapped with @OneToMany
In a single method:
- get an instance of the Parent P entity
- load the collection of child with P.getChilds(): it contains an instance of C1 and C2
- then find a specific Child with an optimized JPA query having the Parent P has a parameter: Child C = dao.getSpecificChild(P)
Here I would expect C to be one of the two instances already loaded (of C1 or C2). I thought JPA would check t开发者_如何学编程he already existing instance in its current session. But JPA will load a new instance of C (whether it is C1 or C2 doesn't matter here).
So that I end up with two different instances of C.
My question is: is this the expected behavior? If it is, how can I reconcile my entity instances in a session?
cheers
how can I reconcile my entity instances in a session?
If you want to transfer state from entity a to entity b, you can do the following:
entityManager.merge(a);
entityManager.refresh(b);
I too would expect the instance of C returned from the query to be one of the previously returned Cs (assuming its the same txn) since they are enlisted in the transaction already, and that is what DataNucleus certainly does (since it also implements JDO and that is part of the spec), and that's what an L1 cache is for.
精彩评论