JPA/Hibernate using associated object in setters while fields are null -
my code looks this. why name in setchildren()
null
??
public class node { private string id, name, parentname; private set<node> children = new hashset<node>(); private node parent; private set<string> childrennames = new hashset<string>(); @id @generatedvalue public string getid() { return id; } public string getname() {return name;} @manytoone @joincolumn(name="parent_id") public node getparent(){retrun parent;} @onetomany(cascade=cascadetype.all, mappedby="parent", fetch=fetchtype.eager) public set<client> getchildren(){return collections.unmodifiableset(children)} @transient public string getparentname() { return parentname;} @transient public set<string> getchildrennames() {return childrennames;} // problem here ------------ public void setchildren(set<node> children) { this.children = children; for(node child : children) { childrennames.add(child.getname()); //adds null !!!!!! } } // other setters }
am n00b, please this.
this guess suspect node.setchildren() being called before child objects have been populated data backing sql query hibernate. hibernate create objects @id value set; if read documentation lazy proxies should see evidence of that. suspect hibernate has created child node objects hasn't populated them data yet because needs populate parent node first. setter firing in process.
you verify debugging code , adding breakpoint in setchildren() , setname(). don't show setname() method in code above assume omitted it. check stack @ breakpoint sense of hibernate doing @ time setter invoked.
one workaround add logic setchildren() getchildren() this:
@transient public set<string> getchildrennames() { if (children.size() != childrennames.size() { childrennames.removeall(); for(node child : children) { childrennames.add(child.getname()); } } return childrennames; }
this should execute once , time getter invoked data in children should populated. or put logic populates "childrennames" non getter/setter method , invoke manually after query.
Comments
Post a Comment