hibernate - Merging detached object deletes children -
my model looks this(in real case there getters , setters):
class foo { set<bar> bars; void attachbars(set<bar> bars){ this.bars = bars; for(bar bar : bars) bar.foo = this; } } class bar { set<baz> bazes; } class baz { }
then execute:
foo foo = e.find(foo.class, "id"); hibernate.initialize(foo.bars); em.detach(foo) foo foo2 = e.find(foo.class, "id"); dosomechanges(foo2); foo2.attachbars(foo.bars);
what see in debugger:
before attachbars(foo.bars);
bar.bazes
fields not accesible due lazyinitializationexception
after attachbars(foo.bars);
ther bar.bazes
fields set null, , after em.merge bazes removed database.
the attachbars
method should never alter reference this.bars. be/is arleady instantiated hibernate, because retrived foo via find()
, i.e. hibernate session. reference collection essential, becuase way can rely on proper dirty checking (newly added, deleted items)
so should (expecting collection instantiated hibernate):
void attachbars(set<bar> bars){ if(this.bars == null){ this.bars = new hashset<bar>(); } for(bar bar : bars){ this.bars.add(bar); bar.foo = this; } }
but in case, not have enough. passed colleciton bars
coming detached object(s). not have populated bazes
collection @ all.
once reatteched loaded object, seem have empty collections. before detache root object, should forcefulness intialization of baz instances well.
even improve solution, suggest iterate old bars collection , load id actual proxies
hibernate
No comments:
Post a Comment