如何初始化 Spring 数据 JPA 的规范?

How to initialize Specification of Spring Data JPA?

我有一个使用过滤器进行搜索的方法,所以我使用 Specification 构建动态查询:

public Page<Foo> searchFoo(@NotNull Foo probe, @NotNull Pageable pageable) {

        Specification<Foo> spec = Specification.where(null);  // is this ok?

        if(probe.getName() != null) {
            spec.and(FooSpecs.containsName(probe.getName()));
        }
        if(probe.getState() != null) {
            spec.and(FooSpecs.hasState(probe.getState()));
        }
        //and so on...

        return fooRepo.findAll(spec, pageable);
}

可能没有指定过滤器,所以我会列出所有内容而不进行过滤。考虑到这一点,我应该如何初始化 spec ?现在,上面的代码不起作用,因为它总是 returns 我得到相同的结果:table 的所有寄存器,尽管进行了 and 操作,但没有应用过滤。

FooSpecs:

public class PrescriptionSpecs {

    public static Specification<Prescription> containsCode(String code) {
        return (root, criteriaQuery, criteriaBuilder) ->
            criteriaBuilder.like(root.get(Prescription_.code), "%" + code + "%");
    }

    // some methods matching objects...
    public static Specification<Prescription> hasContractor(Contractor contractor) {
        return (root, criteriaQuery, criteriaBuilder) ->
            criteriaBuilder.equal(root.get(Prescription_.contractor), contractor);
    }
    //... also some methods that access nested objects, not sure about this
    public static Specification<Prescription> containsUserCode(String userCode) {
        return (root, criteriaQuery, criteriaBuilder) ->
            criteriaBuilder.like(root.get(Prescription_.user).get(User_.code), "%" + userCode + "%");
    }
}

Specification.where(null) 工作得很好。 它用 @Nullable 注释,并且实现会按应有的方式处理 null 值。

问题是您正在使用 and 方法,就好像它会修改 Specification,但它会创建一个新方法。所以你应该使用

spec = spec.and( ... );