java - 对其他实体的可空属性进行 Spring 可分页排序

标签 java spring spring-boot jpa pageable

我遇到了以下问题...我有三个实体:

@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/

相关文章:

java - 递归方法的 Big-O 和 Big-Omega

java - Spring boot - Controller 捕获所有 URL

java - Spring Boot 在 Debug模式下阻止 H2 控制台

java - RETURN_GENERATED_KEYS 和指定生成的列名的区别

java - 如何配置gradle来解决依赖关系

java - MouseListener 在 JLabel 中不起作用

java - Spring Boot API 自定义错误响应契约

java - 如何在 Hibernate 中删除多对多关系中的实体

java - 在 spring boot 2.4.0 版本中包含配置文件

elasticsearch - springboot ElasticSearch中的n-gram实现