下面给出从Department到的一对多关系Employee。
Department
Employee
部门(家长):
@OneToMany(mappedBy = "department", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List<Employee> employeeList = new ArrayList<Employee>(0);
员工(孩子):
@JoinColumn(name = "department_id", referencedColumnName = "department_id") @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH}) private Department department;
合并如下所示的托管实体(子实体)(在EJB中使用CMT),
Employee employee = entityManager.find(Employee.class, 1L); employee.setDepartment(department); // department is supplied by a client. employee.setEmployeeName("xyz"); entityManager.merge(employee);
不会更新数据库表中的相应员工行。仅当CascadeType.MERGE从中的子@ManyToOne关系中删除时,才会发生这种情况Employee。
CascadeType.MERGE
@ManyToOne
为什么表中的行没有更新?CascadeType.MERGE关于此示例的唯一目的是什么?
我当前正在使用具有JPA 2.1的EclipseLink 2.6.0。
级联应该始终从父级传播到子级,而不是相反。
在您的情况下,您需要从子级移除级联:
@JoinColumn(name = "department_id", referencedColumnName = "department_id") @ManyToOne(fetch = FetchType.LAZY) private Department department;
并确保设置了关联的两面:
Employee employee = entityManager.find(Employee.class, 1L); employee.setDepartment(department); employee.setEmployeeName("xyz"); department.getEmployeeList().add(employee); entityManager.merge(department);