简体   繁体   中英

Many to many bidirectional mapping in JPA

I have the following JPA entities.
A profile have many users and a user have many profiles:

@Entity
public class Profile implements Serializable {

    @Id
    private Long id;

    @ManyToMany(cascade = CascadeType.ALL)
    private List<User> users;

    ...
}

@Entity
public class User implements Serializable {

    @Id
    private Long id;

    @ManyToMany(mappedBy = "users")
    private List<Profile> profiles;

    ...
}

On my application, when a user is merged , the profiles are updated on database.
However, when a profile is merged , the users are not updated.

Is possible to map my entities in order to make both sides merge their lists?
I am using JPA 2.1 and Hibernate.

Your Profile entity is ownind side or relationship. It's up to it, to manage relationship, so in order to update User you'll have to update Profile too or make manual SQL calls.

Java Specification for JPA 2.1 says that:

• For many-to-many bidirectional relationships either side may be the owning side

So if you'd like to make both entities editable from both side, remove mappedBy element and assigne necessacy cascade. But I'm not sure it works in Hibernate (didn't try actually), see this docs on mapping, there's no information about m:m without owning side: http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html/ch07.html#collections-bidirectional

Otherwise, you may need to iterate through collection in Profile entity and then change them. For example:

for( User user : profile.getUsers() ) {
    user.setSomething(.....);
}

session.merge(profile);

Changing List to Set might be needed in order to avoid Hibernate's delete and reinsert, described here: http://assarconsulting.blogspot.fr/2009/08/why-hibernate-does-delete-all-then-re.html

Also, don't forget about equals() and hashCode() methods override

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM