2016-07-15 76 views
1

我需要這個查詢複製到JPA CriteriaBuilder代碼: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

所以這裏就是我所做的,似乎這是工作的罰款:

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

男人,你幫了我很多......用這種方法,我們可以混合使用AND和OR運算。 ..你是怎麼寫回歸聲明的? thanx – Hinotori

+0

@Hinotori我把它轉換成了一個像這樣的'predicates.toArray(new Predicate [predicates.size()]'''這就是你需要放在你的'cq.where('...' ;' –