Hibernate Restrictions 简单使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xj80231314/article/details/51692391

 1. 说明

Restrictions 是产生查询条件的工具类。

2. 定义

可以直接用class创建

DetachedCriteria searDc =

DetachedCriteria.forClass(QymlPerson.class);

也可以用hibernate的session创建

session.createCriteria(Student.class)

3. 条件查询

3.1 多条件的and规则

通过searDc.add(Restrictions.eq("unid",userid))实现条件查询。

多次添加的条件,默认的规则是and.

3.2 多条件的or规则

如果实现or的查询,需要按照如下方式进行

searDc.add(Restrictions.or(Restrictions.eq("deptunid","aa"),

Restrictions.isNull("deptunid")));

其中isnull表示一个常规字段是否为空,isEmpty用来表示一个集合字段是否为空。

4. 查询排序

通过searDc.addOrder(Order.asc(propertyName1))可以添加排序,如果有多个排

序字段,可以添加多次;最终的结果将按照添加的次序进行排序处理。

二、子查询

//主查询:人员查询

DetachedCriteria searDc =

DetachedCriteria.forClass(QymlPerson.class);

//子查询:职务人员关系表

DetachedCriteria sub =

DetachedCriteria.forClass(QymlPositionUserLink.class);

sub.add(Restrictions.eq("positionunid",positionunid));

//子查询:指定查询的列(也就是selectusernuid from ....)

sub.setProjection(Property.forName("userunid"));

//主查询和子查询关联(也就是whereunid in (select userunid from...) )

searDc.add(Property.forName("unid").in(sub));

在上面的例子中,用个一个类似于下面SQL的子查询

Select * from Person a where a.unid in (select userunid from PositionUserLink b where

b.positionunid= ..)

Property 还有其他的条件判断,参考api

http://docs.jboss.org/hibernate/core/3.3/api/org/hibernate/criter

ion/Property.html。

三、Restrictions表达式

HQL运算符QBC运算符含义

= Restrictions.eq() 等于equal

<> Restrictions.ne() 不等于 not equal

> Restrictions.gt() 大于greaterthan

>= Restrictions.ge() 大于等于 greater than or

equal

< Restrictions.lt() 小于lessthan

<= Restrictions.le() 小 于 等 于 less than or

equal

is null Restrictions.isnull() 等于空值

is not null Restrictions.isNotNull() 非空值

like Restrictions.like() 字符串模式匹配

and Restrictions.and() 逻辑与

and Restrictions.conjunction() 逻辑与

or Restrictions.or() 逻辑或

or Restrictions.disjunction() 逻辑或

not Restrictions.not() 逻辑非

in(列表)Restrictions.in()等于列表中的某一个值

not in(列表)Restrictions.not(Restrictions.in())不等于列表中任意一个值

between x and yRestrictions.between() 闭区间 xy中的任意值

not between x and y

Restrictions.not(Restrictions..between()) 小于值 X 或者大于值 y

猜你喜欢

转载自blog.csdn.net/xj80231314/article/details/51692391