我使用Spring Data.有两个实体。我想解雇一名员工。如果我解雇一个员工。 1. 我将在实体Employee中删除一个职位(它将是空的)2。而在实体Position中,我将从一组雇员中删除该雇员。
我检查了 "fire "方法正确地从Position_Employees_JT表中删除,并且职位和雇员继续存在于数据库中。
但它是正确的方法或它更好地写一个查询(HQL或JPQL)? 如果我想写一个更复杂的方法,什么语言更好地使用?
我去掉了getset和另一个不必要的代码。
@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;
}
下面的评论。
@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;
}
你一定是在Employee和Position之间有一个父子关系,我建议你只取到 雇员 从db中获取。它将获取各自的 位置 也是。
@Transactional
public Employee fireEmployee(Long id) {
Optional<Employee> employee = employeeRepository.findById(id);
employee.get().remove();
return null;
}