如何初始化弹簧数据JPA规范?

2022-09-01 14:32:33

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

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);
}

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

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 + "%");
    }
}

答案 1

Specification.where(null)工作刚刚好。它带有注释,并且实现按预期处理值。@Nullablenull

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

spec = spec.and( ... );

答案 2

推荐