title: Updating ManyToMany relationships in JPA or Hibernate
body: <p>I have two <code>Entity</code> like below...</p>
  
  <pre><code>@Entity
  @Table(name = "USER")
  public class User {
      @Id
      private Long id;
  
      private String name;
  
      @ManyToMany(fetch = FetchType.LAZY, mappedBy = "groupMemberList")
      @Fetch(FetchMode.SELECT)
      private List&lt;Group&gt; groupList = new ArrayList&lt;&gt;();
  
      // Getters - Setters
  }
  
  
  @Entity
  @Table(name = "GROUP")
  public class Group {
      @Id
      private Long id;
  
      private String name;
  
      @ManyToMany(fetch = FetchType.LAZY/*, mappedBy = "groupList"*/)
      @Fetch(FetchMode.SELECT)
      @JoinTable(name = "SEC_GROUP_VS_MEMBER", joinColumns = @JoinColumn(name = "GROUP_ID"),
              inverseJoinColumns = @JoinColumn(name = "MEMBER_ID"))
      private List&lt;User&gt; groupMemberList;
  
      // Getters - Setters
  }
  </code></pre>
  
  <p>I want to update the <code>User</code> sometimes and also <code>Group</code> sometimes with the methods below...</p>
  
  <p><strong>Method#1</strong></p>
  
  <pre><code>public boolean updateGroup(Long groupId, List&lt;Staff&gt; groupMemberList) {
      Group group = hibernateTemplate.get(Group.class, groupId);
  
      group.setGroupMemberList(groupMemberList);
      hibernateTemplate.merge(group); // Group updated with the users
      return true;
  }
  </code></pre>
  
  <p><strong>Method#2</strong></p>
  
  <pre><code>public boolean updateUser(Long userId, List&lt;Group&gt; groupList) {
      User user = hibernateTemplate.get(User.class, userId);
  
      user.setGroupList(groupList);
      hibernateTemplate.merge(user); // User not updated with the groups
      return true;
  }
  </code></pre>
  
  <p>The first method works fine but not the second one. BUT when I move the <code>join table</code> from <code>Group.class</code> to <code>User.class</code> then second method works fine and not the first one.</p>