[英]How to initialize Specification of Spring Data JPA?
I have a method that does a search with filters, so I'm using Specification to build a dynamic query: 我有一个使用过滤器进行搜索的方法,所以我使用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);
}
There is the possibility that there are no filters specified, so I would list everything without filtering. 有可能没有指定过滤器,所以我会列出所有没有过滤的东西。 So having that in mind, how I should initialize
spec
? 那么考虑到这一点,我应该如何初始化
spec
? Right now, the code above doesn't work as it always returns me the same result: all the registers of the table, no filtering have been aplied althought and
operations have been made. 现在,上面的代码不起作用,因为它总是返回相同的结果:表的所有寄存器,没有过滤,
and
已经进行了操作。
FooSpecs: 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)
works just fine. Specification.where(null)
工作得很好。 It is annotated with @Nullable
and the implementation handles null
values as it should. 它用
@Nullable
注释,实现处理null
值。
The problem is that you are using the and
method as if it would modify the Specification
, but it creates a new one. 问题是您正在使用
and
方法,就好像它会修改Specification
,但它会创建一个新的。 So you should use 所以你应该使用
spec = spec.and( ... );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.