JPA OneToMany双向仅删除父级

时间:2020-09-12 16:37:15

标签: jpa

我有2个具有OneToMany双向实体,我只想删除父级。

部门

@Entity
public class Department {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;

@OneToMany(mappedBy = "department", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Employee> employees = new ArrayList<>();

员工

@Entity
public class Employee {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;

@ManyToOne
private Department department;

我已经尝试过了,但是没有用。它仍然会删除父母和孩子。

Optional<Department> depart = departmentRepository.findById(id);
if (depart.isPresent()) {
    Department department = depart.get();
    List<Employee> emp = department.getEmployees();

    emp.forEach(x -> {
        x.setDepartment(null);
    });

    departmentRepository.deleteById(id);
}

0 个答案:

没有答案
相关问题