1. 程式人生 > >Hibernate Restrictions 簡單使用

Hibernate Restrictions 簡單使用

 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