Search code examples
javajpamany-to-manyeclipselink

How make both sides of many-to-many relation ships owner?


I have a class Group and a class User
where Group and User are many-to-many relation ship
If i change the groups of a user and save a user i want to update the groups
and vice versa where if i changed a user of a group and save the group i want the user to be updated
Do i have to set the mappedBy in both classes
Note : I am using eclipseLink


Solution

  • For a many-to-many relationship, you will need to update the relationship data on both sides in order to stay consistent.

    Unfortunately there is no shortcut.

    What you can do is to create a single method on either of the entities or a third class to encapsulate the consistent update.

    Beware of infinite loops - do not implement the propagation to the other entity in both entity classes.

    Roughly like this:

    public class User
    ...
    public void addGroup(Group g){
       groups.add(g);
       g.addUser(this);
    }
    

    or

    public class Group
    ...
    public void addUser(User u){
       users.add(u);
       u.addGroup(this);
    }
    

    I assume the presence of proper cascade settings on the relationship annotations.