我有两个实体,我使用双向关联。
公司分支:
@Entity
@Table(name = "COMPANY_BRANCH")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class CompanyBranch {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "companyBranch", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<Department> departments = new HashSet<>();
public void addDepartment(Department department) {
this.departments.add(department);
department.setCompanyBranch(this);
}
public void removeDepartment(Department department) {
department.setCompanyBranch(null);
departments.remove(department);
}
部门名称:
@Entity
@Table(name = "DEPARTMENT")
@Getter
@Setter
public class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "COMPANY_BRANCH_ID")
private CompanyBranch companyBranch;
}
我知道使用双向关联是一个很好的实践,因为它可以在代码级别上关联实体(如果我一切都正确的话)。所以我有个问题如何保存部门实体权限?现在我把它保存成这样:
public Department createDepartment(Department department) {
Department departmentFromDB = findDepartmentByNameOrPhone(department.getDepartmentName(),
department.getPhoneNumber());
if (departmentFromDB != null) {
throw new ResourceAlreadyExistsException("Error message");
}
return departmentRepository.saveAndFlush(department);
}
但是我没有从CompanyBranch实体类中使用addDepartment,这可以吗?或者我应该找到一个CompanyBranch并调用它的方法来获取代码级的关联,然后保存更新后的company branch?在代码中,我认为它看起来像这样:
控制器中的代码:
Department department = departmentMapper.toEntity(departmentDTO);
CompanyBranch companyBranch = companyBranchService.getCompanyBranchById(companyBranchId);
departmentService.createDepartment(department, companyBranch);
部门服务中的代码
public void createDepartment(Department department, CompanyBranch companyBranch) {
Department departmentFromDB = findDepartmentByNameOrPhone(department.getDepartmentName(),
department.getPhoneNumber());
if (departmentFromDB != null) {
throw new ResourceAlreadyExistsException("Отдел с таким названием или номером телефона уже существует");
}
companyBranchService.addDepartment(companyBranch, department);
}
CompanyBranch
服务中的addDepartment
方法:
public void addDepartment(CompanyBranch companyBranch, Department department) {
companyBranch.addDepartment(department);
companyBranchRepository.saveAndFlush(companyBranch);
}
通过这种方式,我将维护类之间的双向关联,但Hibernate需要生成更多的查询(例如,我需要额外的查询来获取Company分支)。这是一个好的做法吗?
1条答案
按热度按时间3vpjnl9f1#
如果您的目的只是插入一个新的
Department
到DB,那么您所做的已经足够了。原因是:1.在创建了一个新的
Department
来执行某些逻辑操作之后,您永远不需要从CompanyBranch
获取departments
。CompanyBranch.departments
字段中的值来确定为插入部门SQL生成哪些FK值,因为您现在将其配置为mappedBy
正因为如此,为什么需要费心维护
CompanyBranch.departments
字段以获得正确的状态,因为它们的值不会影响应用程序?