OneToMany Update not working in child class
I have OnetoMany relationship between Person and Role class. A Person can have multiple roles. When I create a new person, roles (existing records) should get updated with the person ids. I am using @OneToMany mapping with CascadeType All, but the Role class is not getting updated with Pe开发者_运维问答rson id. If a new role is created and set as a relationship while creating the Person, it works fine. But when you create a new Person and try to set it to existing Role it doesn't get updated.
This must be done manually for bidirectional links. The hibernate tutorial provides a good example: http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html_single/#tutorial-associations-usingbidir
In your case: On the OneToMany side, make your setPersons(...) method protected, and define a public addPerson(Person p) method like this:
public void addPerson(Person p) {
this.getPersons().add(p);
p.setRole(this);
}
By the way, if a person can have multiple roles, and a role can be assigned to multiple persons, then most probably what you actually want is a ManyToMany relationship. So 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 is necessary, because in contrast to EJB 2.x Container Managed Relationships (CMR), this isn't handled automatically. Hibernate uses a POJO approach. The disadvantage of CMR is, that it requires a container to create the objects, whereas you can create POJO objects everywhere. And if you create them, they're just Plain Old Java Objects, no tricks.
Here's a nice blog article, which discusses this further: http://blog.xebia.com/2009/03/16/jpa-implementation-patterns-bidirectional-assocations/
精彩评论