title: How to save a new entity that refers existing entity in Spring JPA?
body: <p>Imagine the following models:</p>
  
  <p>Employee:</p>
  
  <pre><code>@ManyToMany(cascade = CascadeType.ALL)
  @JoinTable(name = "employee_project", joinColumns = @JoinColumn(name = "Emp_Id"), inverseJoinColumns = @JoinColumn(name = "Proj_id"))
  private Set&lt;Project&gt; projects = new HashSet&lt;Project&gt;();
  </code></pre>
  
  <p>Project:</p>
  
  <pre><code>@ManyToMany(mappedBy = "projects")
  private Set&lt;Employee&gt; employees = new HashSet&lt;Employee&gt;();
  </code></pre>
  
  <p>Now if I create a new employee that refers to an existing project and try to persist that employee, I get an error:</p>
  
  <pre><code>detached entity passed to persist: Project
  </code></pre>
  
  <p>I create the employee as follows:</p>
  
  <pre><code>public void createNewEmployee(EmployeeDTO empDTO) {
  
    Employee emp = new Employee();
    // add stuff from DTO, including projects
  
    repository.saveAndFlush(emp);  // FAILS
  }
  </code></pre>
  
  <p>and I update existing ones like this:</p>
  
  <pre><code>public void updateEmployee(EmployeeDTO empDTO) {
  
     Employee emp = repository.findOne(empDTO.getId());
     // set stuff from DTO, including projects
  
     repository.saveAndFlush(emp);  // WORKS!
  }
  </code></pre>