I have a question about JPA-2.0 relationships (provider - Hibernate) and their corresponding Java management. Suppose I have a Department and an Entity of an employee:
@Entity public class Department { ... @OneToMany(mappedBy = "department") private Set<Employee> employees = new HashSet<Employee>(); ... } @Entity public class Employee { ... @ManyToOne(targetEntity = Department.class) @JoinColumn private Department department; ... }
Now I know that I need to manage Java relationships myself, as in the following unit test:
@Transactional @Test public void testBoth() { Department d = new Department(); Employee e = new Employee(); e.setDepartment(d); d.getEmployees().add(e); em.persist(d); em.persist(e); assertNotNull(em.find(Employee.class, e.getId()).getDepartment()); assertNotNull(em.find(Department.class, d.getId()).getEmployees()); }
If I leave either e.setDepartment(d) or d.getEmployees().add(e) , the statement fails. So far, so good. What if I do a database transaction between?
@Test public void testBoth() { EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Department d = new Department(); Employee e = new Employee(); e.setDepartment(d); d.getEmployees().add(e); em.persist(d); em.persist(e); em.getTransaction().commit(); em.close(); em = emf.createEntityManager(); em.getTransaction().begin(); assertNotNull(em.find(Employee.class, e.getId()).getDepartment()); assertNotNull(em.find(Department.class, d.getId()).getEmployees()); em.getTransaction().commit(); em.close(); }
Do I still need to manage both sides of the relationship? No, as it turned out, I do not need. With this modification
e.setDepartment(d);
statements are still doing well. However, if I just set the other side:
allegations fail. What for? Is this because Employee is the party that owns this relationship? Can I change this behavior by annotating in different ways? Or is it always the “one” side of “OneToMany” that determines when the foreign key field in the database is populated?
source share