小编典典

JPA CriteriaBuilder将合并条件合并为析取条件

hibernate

我需要将此查询复制到 JPA CriteriaBuilder 代码中:

....
where
     article.client_id = 1 
     and article.price > 0
     and (
           article.code like '%this is statement%' 
           or article.oem_code like '%this is statement%'
           or ( 
               article.description like '%this%'
               and article.description like '%is%'
               and article.description like '%statement%'
           )    
     )

这是我的代码:

...

Root<Article> article = cq.from(Article.class);

List<Predicate> predicates = new ArrayList<Predicate>();

predicates.add(cb.equal(article.get(Article_.clientId), filter.getClientId()));

predicates.add(cb.greaterThan(article.get(Article_.price), BigDecimal.ZERO));

String searchQuery = filter.getSearchQuery();

Predicate disjunction = cb.disjunction();

disjunction.getExpressions().add(cb.like(article.get(Article_.code), "%" + searchQuery + "%"));
disjunction.getExpressions().add(cb.like(article.get(Article_.oem_code), "%" + searchQuery + "%"));

List<Predicate> andPredicate = new ArrayList<Predicate>();

for (String str : searchQuery.split(" ")) {
   andPredicate.add(cb.like(article.get(Article_.description), "%" + str + "%"));    
}

现在,如何将其添加andPredicate到析取谓词中?在getExpressions().add(...)不采取Predicate为PARAM。

谢谢


阅读 609

收藏
2020-06-20

共1个答案

小编典典

所以这就是我所做的,并且看起来工作正常:

...  
Predicate pr1 = cb.like(article.get(Article_.code), "%" + searchQuery + "%");
Predicate pr2 = cb.like(article.get(Article_.oem_code), "%" + searchQuery + "%");
Predicate pr3 = cb.conjunction();

for (String str : busquedaSplit) {
    Predicate newPredicate = cb.like(article.get(Article_.description), "%" + str + "%");
    pr3 = cb.and(pr3, newPredicate);
}

disjunction = cb.or(pr1, pr2, pr3);

predicates.add(disjunction);
2020-06-20