我有两个实体,Department和Employees,一个Department可以有多个employee。雇员表有一个外键,DEPT_ID。我想删除一个特定的部门,并将该部门所有员工的外键设置为空。相反,我的代码正在删除子记录(i。(雇员),即使我只是将DEPT_ID设置为null。
@Entity
@Table(name = "MY_DEPARTMENT")
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence1")
@SequenceGenerator(name = "sequence1", sequenceName = "SEQ_DEP")
@Column(name = "DEPARTMENT_ID")
private long departmentId;
@Column(name = "DEPARTMENT_NAME")
private String departmentName;
@Column(name = "DEPARTMENT_LOCATION")
private String departmentLocation;
@OneToMany(mappedBy = "department")
private List<Employee> employees;
}
@Entity
@Table(name = "MY_EMPLOYEE")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequence2")
@SequenceGenerator(name = "sequence2", sequenceName = "SEQ_EMP")
@Column(name = "EMPLOYEE_ID")
private long employeeId;
@Column(name = "EMPLOYEE_NAME")
private String employeeName;
private int salary;
private String email;
@ManyToOne
@JoinColumn(name = "DEPT_ID")
private Department department;
}
Session session = sessionFactory.getCurrentSession();
Department department = session.get(Department.class, 3102l);
List<Employee> list = department.getEmployees();
for (Employee employee : list) {
employee.setDepartment(null);
}
session.delete(department);
注意:我已经启用了show_sql = true,我可以看到UPDATE查询首先为EMPLOYEE表触发,我认为所有员工的DEPT_ID设置为null,然后我可以看到DELETE查询触发,删除Department记录。
我使用Oracle数据库,外键定义为ON DELETE RESTRICT
在删除前将department object中的employees设置为null
Session session = sessionFactory.getCurrentSession();
Department department = session.get(Department.class, 3102l);
List<Employee> list = department.getEmployees();
for (Employee employee : list) {
employee.setDepartment(null);
}
department.setEmployees(null);
session.delete(department);