java - 如何正确地从另一个实体中删除一个实体?
问题描述
我使用弹簧数据。有两个实体。我想解雇一名员工。如果我解雇一名员工: 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;
}
解决方案
下面的评论:
@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;
}
推荐阅读
- c# - 使用 XAML 和 C#,我如何制作一个添加 2 个数字的应用程序?
- html - 如何在html CSS中沿侧面文本对齐表格
- lucene - Alfresco:如何搜索特定的文件类型?
- ruby - 如何从数组中随机选择红宝石
- c++ - 停止 C++ 中的特定线程
- excel - 使用条件偏移工作表中的单元格
- python - Scrapy - 如何使用 AWS Lambda 函数运行蜘蛛?
- angular6 - 用于 tr 元素的 Angular 6 / TSLint 组件选择器
- sublimetext3 - 如何修复这个 Sublime SFTP 解析错误?
- c# - “System.Net.Http”中都存在“MediaTypeHeaderValue”类型