[英]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
? 現在,上面的代碼不起作用,因為它總是返回相同的結果:表的所有寄存器,沒有過濾, 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( ... );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.