Hibernate:Disjunction&Conjunction构造复杂的查询条件

 

Disjunction和Conjunction是逻辑或和逻辑与,如下:

 

用来组合一组逻辑或【or】条件的方法

  1. 1.Restrictions.disjunction();  

用来组合一组逻辑与【and】条件的方法

  1. 2.Restrictions.conjunction();  


 

实例一:构造复杂的SQL查询条件

  1. private void CheckBsc_lj(Criteria queryCriteria)   
  2.  {  
  3.   Disjunction disjunction = Restrictions.disjunction();  
  4.   Criterion cirterion = Restrictions.sqlRestriction("SIMULPORTCAPACITY<SIMULPORTCAPACITYOCUPIED".toLowerCase());  
  5.   disjunction.add(cirterion);  
  6.   cirterion = Restrictions.sqlRestriction("ADSLPORTCAPACITY<ADSLPORTCAPACITYOCCUPIED".toLowerCase());  
  7.   disjunction.add(cirterion);  
  8.   cirterion = Restrictions.sqlRestriction("LANPORTCAPACITY<LANPORTCAPACITYOCCUPIED".toLowerCase());  
  9.   disjunction.add(cirterion);  
  10.     
  11.   // ONU端口,至少要录入一种端口  
  12.   Conjunction conjunction = Restrictions.conjunction();  
  13.   cirterion = Restrictions.eq("lanportcapacity"0);  
  14.   conjunction.add(cirterion);  
  15.   cirterion = Restrictions.eq("simulportcapacity"0);  
  16.   conjunction.add(cirterion);  
  17.   cirterion = Restrictions.eq("adslportcapacity"0);  
  18.   conjunction.add(cirterion);  
  19.   
  20.   disjunction.add(conjunction);  
  21.   queryCriteria.add(disjunction);  
  22.  }  
  23.   
  24. 构造出的条件如下:  
  25. select *  
  26.   from aaaa this_  
  27.  where (simulportcapacity < simulportcapacityocupied or  
  28.        adslportcapacity < adslportcapacityoccupied or  
  29.        lanportcapacity < lanportcapacityoccupied or  
  30.        (this_.LANPORTCAPACITY = ? and this_.SIMULPORTCAPACITY = ? and  
  31.        this_.ADSLPORTCAPACITY = ?))   

实例二:构造模糊查询

 

  1. Disjunction dis=Restrictions.disjunction();     
  2. dis.add(Restrictions.like("chanpin""冰箱", MatchMode.ANYWHERE));     
  3. dis.add(Restrictions.like("chanpin""洗衣机", MatchMode.ANYWHERE));     
  4. dis.add(Restrictions.like("chanpin""热水器", MatchMode.ANYWHERE));     
  5. dis.add(Restrictions.like("chanpin""空调", MatchMode.ANYWHERE));     
  6. detachedCriteria.add(dis);