首页 > 解决方案 > 如何正确地从另一个实体中删除一个实体?

问题描述

我使用弹簧数据。有两个实体。我想解雇一名员工。如果我解雇一名员工: 1. 我将删除实体 Employee 中的一个职位(它将为空) 2. 在实体职位中,我将从一组员工中删除该员工。

我检查了“fire”方法是否从 Position_Employees_JT 表中正确删除,并且位置和员工继续存在于数据库中。

但它是正确的方法还是编写查询(HQL 或 JPQL)更好?如果我想写一个更复杂的方法怎么办,用什么语言更好?

我删除了 get/set 和另一个不必要的代码。

@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long employeeId;

    private String firstName;

    @ManyToOne(cascade = ALL, fetch = LAZY)
    @JoinColumn(name = "fk_position")
    private Position position;

    public void removePosition(){
        this.position = null;
    }
}

@Entity
public class Position {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "POSITION_ID", updatable = false)
    private Long id;

    private PositionName name;

    @JoinTable(name = "Position_Employees_JT",
            joinColumns = @JoinColumn(name = "ID_POSITION", referencedColumnName = "POSITION_ID"),
            inverseJoinColumns = @JoinColumn(name = "ID_EMPLOYEE", referencedColumnName = "EMPLOYEE_ID"))
    @OneToMany
    private Set<Employee> employeeSet = new HashSet<>();

    public void addEmployee(Employee employee){
        employeeSet.add(employee);
    }

    public void removeEmployee(Employee employee){
        employeeSet.remove(employee);
    }
}

“火”法:

@Transactional
public Employee fireEmployee(Long id) {
    Optional<Employee> employee = employeeRepository.findById(id);
    Optional<Position> position = positionRepository.findById(employee.get().getPosition().getId()); 
    position.get().removeEmployee(employee.get());
    employee.get().removePosition();
    return null;
}

标签: javaspringspring-data-jpaspring-data

解决方案


下面的评论:

@Transactional
public Employee fireEmployee(Long id) {
    Optional<Employee> employee = employeeRepository.findById(id);
    Optional<Position> position = positionRepository.findById(employee.get().getPosition().getId()); 
    position.get().removeEmployee(employee.get()); //this only affects the set in the memory, will not affect the database record
    employee.get().remove(); //this will actually delete record from the database
    return null;
}

推荐阅读