How do you “OR” criteria together when using a criteria query with hibernate?

前端 未结 8 893
终归单人心
终归单人心 2020-12-04 07:44

I\'m trying to do a basic \"OR\" on three fields using a hibernate criteria query.

Example

class Whatever{
 string name;
 string address;
 string pho         


        
相关标签:
8条回答
  • 2020-12-04 08:35
    //Expression :  (c1 AND c2) OR (c3)      
    
    
     Criteria criteria = session.createCriteria(Employee.class);
    
      Criterion c1 = Restrictions.like("name", "%e%");
      Criterion c2 = Restrictions.ge("salary", 10000.00);
      Criterion c3 = Restrictions.like("name", "%YYY%");
      Criterion c4 = Restrictions.or(Restrictions.and(c1, c2), c3);
      criteria.add(c4);
    
      //Same thing can be done for (c1 OR c2) AND c3, or any complex expression.
    
    0 讨论(0)
  • 2020-12-04 08:39

    If someone is using CriteriaQuery instead of Criteria, you can put all your expressions in a Predicate list and put a OR by predicates size like this:

    List<Predicate> predicates = new ArrayList<>();
    if (...) {
      predicates.add(...);
    }
    
    criteriaQuery.where(cb.or(predicates.toArray(new Predicate[predicates.size()])));
    
    0 讨论(0)
提交回复
热议问题