JPA CriteriaBuilder将标准合并为分离标准

时间:2016-07-15 15:47:43

标签: java hibernate jpa criteria

我需要将此查询复制到 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视为参数。

由于

1 个答案:

答案 0 :(得分:7)

所以这就是我所做的,似乎工作正常:

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