title: Transaction aborted when trying to persist user
body: <p>I am trying to save an user. The user entity and group entity has a bi-directional many-to-many relationship. However the groups are already saved in the database (only two though: administrator and user). </p>
  
  <p>Here I just "fake" the group which already exists because I thought that would work. I can't add the <code>cascade = CascadeType.PERSIST</code> to the user because then it would save the group again, causing duplicate data. How would I fix this?</p>
  
  <p>From the EJB</p>
  
  <pre><code>public void persistAsUser(User user) {
      Group group = new Group(2L, "user");
      user.addGroup(group);
  
      userRepository.persist(user);
  }
  </code></pre>
  
  <blockquote>
    <p>javax.ejb.EJBException: Transaction aborted</p>
    
    <p>Caused by: java.lang.IllegalStateException: During synchronization a
    new object was found through a relationship that was not marked
    cascade PERSIST:</p>
  </blockquote>
  
  <hr>
  
  <p>Here are the entities:</p>
  
  <pre><code>    @Entity
      @Table(name = "app_user")
      public class User implements Serializable {
  
          public static final String ALL = "User.all";
  
          @Id
          @GeneratedValue(strategy = GenerationType.IDENTITY)
          private Long id;
          private String firstName;
          private String lastName;
          private Integer age;
          private String username;
          private String email;
          private String password;
  
          @ManyToMany(mappedBy = "users")
          private List&lt;Group&gt; groups;
  
          ....
  
  public void addGroup(Group group) {
  
      if (!getGroups().contains(group)) {
          getGroups().add(group);
      }
  
      if (!group.getUsers().contains(this)) {
          group.getUsers().add(this);
      }
  }
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>@Entity
      public class Group implements Serializable {
  
          @Id
          @GeneratedValue(strategy = GenerationType.IDENTITY)
          private Long id;
          private String groupName;
  
          @ManyToMany
          @JoinTable(joinColumns = {@JoinColumn(name="group_id")}, inverseJoinColumns = {@JoinColumn(name="user_id")})
          private List&lt;User&gt; users;
  
         ....
  
  }
  </code></pre>