DetachedCriteria 使用手册

来源:互联网 发布:dnf网络冲突怎么办 编辑:程序博客网 时间:2024/05/07 05:51

一、基本使用

1、说明:Restrictions 是产生查询条件的工具类

2、定义:可以直接用class创建:DetachedCriteria dc = DetachedCriteria.forClass(Person.class);

3、条件查询

     (1)多条件的and查询规则:

         dc.add(Restrictions.eq("uuid",userid));

         dc.add(Restrictions.eq("name",name));

多次添加,默认实现and多条件查询

    (2)多条件的or查询

         dc.add(Restrictions.or(Restrictions.eq("name",name),Restrictions.isNull("name"))); 

// isNull表示常规字段是否为空,isEmpty用来表示一个集合字段是否为空。

4、查询排序

      dc.addOrder(Order.asc("uuid"));   如果有多个排序字段,可以添加多次,最终结果按添加次序进行排序处理。

二、子查询

//主查询: DetachedCriteria dc = DetachedCriteria.forclass(Person.class);   //全部人员表

//子查询:DetachedCriteria subDc = DetachedCriteria.forclass(Student.class);  //学生表

subDc.add(Restrictions.eq("sex",'male'));  

subDc.setProjection(Property.forName(studentId)); //指定查询列 select studentId from ....

dc.add(Porperty.forName("unid").in(sub)) //主查询与子查询关联:where unid in (select studentId from ....)

上面的查询,相当于以下的sql查询:

           select * from Person p where p.unid in (select studentId from Student s where s.sex='male'); 

Property的其它条件判断,参考api: http://docs.jboss.org/hibernate/core/3.3/api/org/hibernate/criterion/Property.html

三、Restrictions 表达式

HQL运算符QBC运算符含义=Restrictions.eq()等于equal<>Restrictions.ne()
不等于 not equal>Restrictions.gt()
大于 >=Restrictions.ge()
大于等于<Restrictions.lt()
小于<=Restrictions.le()
小于等于is nullRestrictions.isNull()
等于空值is not nullRestrictions.isNotNull()
非空值likeRestrictions.like()
字符串模式匹配andRestrictions.add()
逻辑与andRestrictions.conjunction()
逻辑与
orRestrictions.or()
逻辑或
orRestrictions.disjunction()
逻辑或
not Restrictions.not()
逻辑非
in(列表)Restrictions.in()
等于列表中的某一值not in(列表)Restrictions.not(Restrictions.in())
不等于列表中的某一值between x and yRestrictions.between()
闭区间x-y中的任意值not between x and y                                   Restrictions.not(Restrictions.between())       小于x或者大于Y