Merging and retrieving children using Hibernate
I have a model that looks like this:
A -- Many-toMany --> B -- Many-toMany --> C
Both A
and B
have the CascadeType of All
and FetchType of Lazy
.
When I make the following call:
A mergedA = (A) session.merge(a);
The mergedA
has the collection of B
objects resolved. B
however does not have its collection of C
objects resolved.
If I make the following call:
B mergedB = (B) session.merge(b);
The mergedB
has the collection of C
objects resolved.
If both A
and B
have the C开发者_运维百科ascadeType of All
, why does the collections of C
objects not get resolved for the collection of B
s when I call session.merge(a);
?
Its because, it does it for the single step deep in the object graph and C
is at the second step. Thus, it did just for the immediate one.
I think its because cascade has to do with transitive persistence, and nothing to do with lazy vs non lazy.
Transitive persistence as a concept applies to logical operations that you want to 'transit' from parents to children. So its all about "you deleted a parent, and should that cascade down to children?" -- its about the semantics you want in your object relationships.
lazy vs non lazy is a persistence implementation detail. So its all about "do I as a persistence layer load this thing now?" -- its about how to optimize the persistence layer.
As a note, Im wondering if this is a correct application of merge. Merge is for reattaching a detached object to the session when an object with the same id is already in the session. Im a bit surprised that it is loading the children at all.
精彩评论