How do I store the same table row in the database for two entities that contain the same object? The following illustrates my invalid attempt.
@Entity
public class Employee 
  {
  @ManyToOne(cascade=CascadeType.ALL)
  private Department department;
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;
  private String name;
  ...
  <Getters and setters for all members here>
  ...
  }
@Entity
public class Department 
  {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;
  private String name;
  @OneToMany(mappedBy="department")
  private Collection<Employee> employees;
  ...
  <Getters and setters for all members here>
  ...
  }
In the Servlet I try the following:
Department department=new Department();
department.setName("HR");
Employee employee1=new Employee();
employee1.setName("Bob");
employee1.setDepartment(department);
Employee employee2=new Employee();
employee2.setName("Anna");
employee2.setDepartment(department);
...
em.persist(employee1);
em.persist(employee2);
When I do this I get an error when employee2 is persisted that the primary key for department is already in the database as it tries to add the same department for a second time.
How do I achieve both employees pointing to the same row in the database.
Do I have to work from the inverse side by adding the employees to the department to achieve this?
I feel like I am missing something fundamental here.
 
     
    