title: Spring data jpa detached entity
body: <p>I started to work on a Spring Boot application using Spring Data JPA to setup a ManyToMany relationship between users and roles.</p>
  
  <p>This relationship is defined as following in the User class:</p>
  
  <pre><code>@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
  @JoinTable(name="user_role", joinColumns = {@JoinColumn(name="user_id")}, inverseJoinColumns = {@JoinColumn(name="role_id")})
  private Set&lt;UserRole&gt; roles;
  </code></pre>
  
  <p>I create roles using:</p>
  
  <pre><code>@Transactional
  private void generateSeedRoles() {
      UserRole adminRole = new UserRole(RoleEnum.ADMIN.toString());
      userRoleRepository.save(adminRole);
  
      UserRole userRole = new UserRole(RoleEnum.USER.toString());
      userRoleRepository.save(userRole);
  }
  </code></pre>
  
  <p>Assigning roles to users afterwards fails:</p>
  
  <pre><code>@Transactional
  private void generateSeedUsers() {
      UserRole adminRole = userRoleRepository.findUserRoleByRoleName("ADMIN");
  
      User user = User.createUser("user1", "user1@user.com", "pass");
      user.setRoles(new HashSet&lt;UserRole&gt;(Arrays.asList(adminRole)));
  
      userRepository.save(user);
  }
  </code></pre>
  
  <p>The following exception is thrown (formatted for readability):</p>
  
  <pre><code>org.springframework.dao.InvalidDataAccessApiUsageException: 
  detached entity passed to persist: co.feeb.models.UserRole; 
  nested exception is org.hibernate.PersistentObjectException: 
  detached entity passed to persist: co.feeb.models.UserRole
  </code></pre>
  
  <p>However, if the user is saved before the relationship is created, it works fine:</p>
  
  <pre><code>@Transactional
  private void generateSeedUsers() {
      UserRole adminRole = userRoleRepository.findUserRoleByRoleName("ADMIN");
  
      User user = User.createUser("user1", "user1@user.com", "pass");
      //Save user
      userRepository.save(user);
  
      //Build relationship and update user
      user.setRoles(new HashSet&lt;UserRole&gt;(Arrays.asList(adminRole)));
      userRepository.save(user);
  }
  </code></pre>
  
  <p>Having to save/update the user twice seems somewhat unreasonable to me. Is there any way to assign the received role to the <strong>new user</strong> without saving the user first?</p>