java - annotation mapping bidirectional OneToMany/ManyToOne not fetching? -
i'm struggling understand appreciated...
i have following mapping:
@entity @table(name = "parent") public class parententity { ... @id @column(name = "parent_id") private long id; ... @onetomany(mappedby = "parent", fetch = fetchtype.eager) private list<childentity> children; ... } @entity @table(name = "child") public class childentity { ... @id @column(name = "child_id") private long id; ... @manytoone(fetch = fetchtype.eager) @notfound(action = notfoundaction.ignore) @joincolumn(name = "parent_id") private parententity parent; ... }
in db have:
parent ------ parent_id: 1 child ------ child_id: 1, parent_id: 1
however
((parent) session.get(parent.class, 1)).getchildren()
returns null.
can see have missing?
thanks, p.
edit
it seems more-so session state in collection not populated in context of same session, collection populated in next session...
consider following:
void setuprender() { debug("existing not added", (parententity) session.get(parententity.class, 13l)); parententity parent = new parententity(); session.save(parent); childentity child = new childentity(); child.setparent(parent); session.save(child); debug("new 1 before commit", parent); sessionmanager.commit(); debug("new 1 after commit", parent); debug("new 1 after re-fetch", (parententity) session.load(parententity.class, parent.getid())); } private void debug(string prefix, parententity parent) { log.debug(prefix + ": parent id: " + parent.getid() + ", children " + (parent.getchildren() == null ? "null" : "size:" + parent.getchildren().size())); }
results in following output:
debug - existing not added: parent id: 13, children size:1 debug - new 1 before commit: parent id: 23, children null debug - new 1 after commit: parent id: 23, children null debug - new 1 after re-fetch: parent id: 23, children null
so if it's due session state, , commit isn't enough trigger re-fetch, have mapping fetch collection?
thanks again!
yes, commit doesn't trigger refresh of session cache.
the typical approach here use session-per-request pattern, close session after commit, , open session following transactions (though it's not option if use open session in view pattern).
another practice may solve problem modify both sides of bidirectional relationship simultaneously:
public class parententity { ... public void addchild(childentity c) { children.add(c); c.setparent(this); } }
this way can keep objects in session cache in consistent state.
finally, if need refresh object inside session can call session.refresh()
on it.
Comments
Post a Comment