文章出處

一、基本使用

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));

//子查詢:指定查詢的列(也就是select usernuid from ....)

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

//主查詢和子查詢關聯(也就是where unid 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() 大于greater than

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

equal

< Restrictions.lt() 小于less than

<= 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 y Restrictions.between() 閉區間 xy中的任意值

not between x and y

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

三、Restrictions關聯查詢

如果每個美女都有自己的客戶資源(不要想歪了!),那么需要查詢擁有客戶Gates的美女怎么辦?

使用Criteria可以有兩種方法:

1:
DetachedCriteria beautyCriteria = DetachedCriteria.forClass(Beauty.class).createCriteria("customers");
beautyCriteria.add(Restrictions.eq("name", "Gates")):

2:
DetachedCriteria beautyCriteria = DetachedCriteria.forClass(Beauty.class).createAlias("customers", "c");
beautyCriteria.add(Restrictions.eq("c.name", "Gates")):

接著有了新的要求,年紀太大的美女不要,還是查找擁有客戶Gates的,條件如下:
DetachedCriteria beautyCriteria = DetachedCriteria.forClass(Beauty.class, "b").;
DetachedCriteria customerCriteria = beautyCriteria.createAlias("customers", c");
beautyCriteria.add(Restrictions.le("b.age", new Long(20))):
customerCriteria.add(Restrictions.eq("c.name", "Gates")):

 

相關: 

Hibernate - DetachedCriteria 的完整用法


文章列表


不含病毒。www.avast.com
全站熱搜
創作者介紹
創作者 大師兄 的頭像
大師兄

IT工程師數位筆記本

大師兄 發表在 痞客邦 留言(0) 人氣()