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 Person 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.
-
Some sample code may be helpful. – axtavt Feb 10 '11 at 09:03
-
It seems quite similar to [this problem](http://stackoverflow.com/questions/2441598/detached-entity-passed-to-persist-error-with-jpa-ejb-code/4905238#4905238). – zawhtut Feb 11 '11 at 13:22
1 Answers
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/

- 37,264
- 20
- 99
- 131
-
To whoever downvoted: This is from the official documentation. Do you have a better solution? (Note: Hibernate doesn't perform *black magic* on your objects, which would be necessary to automate bidirectional links.) – Chris Lercher Feb 10 '11 at 22:50