我遇到了以下问题...我有三个实体:
@Entity
class Contract {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
private Employee employee;
}
@Entity
class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
private Department department;
}
@Entity
class Department {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
}
以及使用 Specification 获取合约信息的方法:
Page<Contract> getContracts(Integer employeeId, Pageable pageable) {
return contractRepository.findAll(createSpecification(employeeId), pageable);
}
Specification<Contract> createSpecification(Integer employeeId) {
return Specification.where(equalEmployeeId(employeeId));
}
Specification<Contract> equalEmployeeId(Integer employeeId) {
return (root, criteriaQuery, criteriaBuilder) -> {
if (Objects.nonNull(employeeId)) {
Join<Contract, Employee> joinParent = root.join("employee");
return criteriaBuilder.equal(joinParent.get("id"), employeeId);
} else {
return criteriaBuilder.isTrue(criteriaBuilder.literal(true));
}
};
}
现在,我的应用程序可以按 Department
名称对 Contract
实体进行排序,因此出现了带有 sort 的
参数设置为 Pageable
对象employee.department.name
。当 Employee
对象将 department
参数设置为 null 时,问题就出现了……例如,如果所有 Employee
对象都有 department
参数设置为 null,则返回空集合。我该怎么做才能更改此行为以返回所有 Contract
实体,而不管 Employee's
department
是否为空?
我已经尝试了不同的方法:将 fetch join 添加到规范中,将 spring.jpa.properties.hibernate.order_by.default_null_ordering
设置为 last
,但没有任何帮助。
提前感谢您的帮助!
PS:请不要建议我删除规范等 - 我提供的代码是为了便于阅读而简化的。实际上,有更多的属性,使用 Specifications 进行过滤是最方便的方法。
最佳答案
如果 Department
为 null,则根据您要返回所有 Contract
实体的内容。
Specification<Contract> equalEmployeeId(Integer employeeId) {
return (root, criteriaQuery, criteriaBuilder) -> {
Join<Contract, Employee> joinParent = root.join("employee");
if (Objects.nonNull(employeeId)) {
return criteriaBuilder.equal(joinParent.get("id"), employeeId);
} else {
return criteriaBuilder.isTrue(joinParent.get("department").isNull());
}
};
}
关于java - 对其他实体的可空属性进行 Spring 可分页排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67597955/