如何初始化Spring Data JPA的规范?

ana*_*ius 10 java dynamicquery 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);
}
Run Code Online (Sandbox Code Playgroud)

有可能没有指定过滤器,所以我会列出所有没有过滤的东西.那么考虑到这一点,我应该如何初始化spec?现在,上面的代码不起作用,因为它总是返回相同的结果:表的所有寄存器,没有过滤已经做过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 + "%");
    }
}
Run Code Online (Sandbox Code Playgroud)

Jen*_*der 17

Specification.where(null)工作得很好.它被注释,@Nullable并且实现处理null值应该.

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

spec = spec.and( ... );
Run Code Online (Sandbox Code Playgroud)

  • @IlyaSerebryannikov请不要在评论中提出新问题,而要在问题中提问。 (2认同)