java - OneToMany Update not working in child class -
i have onetomany relationship between person , role class. person can have multiple roles. when create new person, roles (existing records) should updated person ids. using @onetomany mapping cascadetype all, role class not getting updated person id. if new role created , set relationship while creating person, works fine. when create new person , try set existing role doesn't updated.
this must done manually bidirectional links. hibernate tutorial provides example: http://docs.jboss.org/hibernate/core/3.6/reference/en-us/html_single/#tutorial-associations-usingbidir
in case: on onetomany side, make setpersons(...) method protected, , define public addperson(person p) method this:
public void addperson(person p) { this.getpersons().add(p); p.setrole(this); }
by way, if person can have multiple roles, , role can assigned multiple persons, want manytomany relationship. you'd have:
public void addperson(person p) { this.getpersons().add(p); p.getroles().add(this); }
and in class person:
public void addrole(role r) { this.getroles().add(r); r.getpersons().add(this); }
this necessary, because in contrast ejb 2.x container managed relationships (cmr), isn't handled automatically. hibernate uses pojo approach. disadvantage of cmr is, requires container create objects, whereas can create pojo objects everywhere. , if create them, they're plain old java objects, no tricks.
here's nice blog article, discusses further: http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/
Comments
Post a Comment