首页 > 代码库 > Hibernate Criteria
Hibernate Criteria
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 |
1.常用的查询限制方法
在例程9-1中,Restrictions.eq()方法表示equal,即等于的情况。Restrictions类提供了查询限制机制。它提供了许多方法,以实现查询限制。这些方法及其他一些criteria常用查询限制方法列于表9-1中。
表9-1 Criteria Query常用的查询限制方法
方 法
说 明
Restrictions.eq()
equal,=
Restrictions.allEq()
参数为Map对象,使用key/value进行多个等于的对比,相当于多个Restrictions.eq()的效果
Restrictions.gt()
greater-than, >
Restrictions.lt()
less-than, <
Restrictions.le()
less-equal, <=
Restrictions.between()
对应SQL的between子句
Restrictions.like()
对应SQL的like子句
Restrictions.in()
对应SQL的in子句
Restrictions.and()
and关系
Restrictions.or()
or关系
Restrictions.isNull()
判断属性是否为空,为空返回true,否则返回false
Restrictions.isNotNull()
与Restrictions.isNull()相反
Order.asc()
根据传入的字段进行升序排序
Order.desc()
根据传入的字段进行降序排序
MatchMode.EXACT
字符串精确匹配,相当于“like ‘value‘”
MatchMode.ANYWHERE
字符串在中间位置,相当于“like ‘%value%‘”
MatchMode.START
字符串在最前面的位置,相当于“like ‘value%‘”
MatchMode.END
字符串在最后面的位置,相当于“like ‘%value‘”
例1:查询学生名字以t开头的所有Student对象。
Criteria cr = session.createCriteria(Student.class);
cr.add(Restrictions.like(“name”, “t%”))
List list = cr.list();
Student stu = (Student)list.get(0);
或者使用另一种方式:
Criteria cr = session.createCriteria(Student.class);
cr.add(Restrictions.like(“name”, “t”, MatchMode.START))
List list = cr.list();
Student stu = (Student)list.get(0);
例2:查询学生姓名在Bill, Jack和Tom之间的所有Student对象。
String[] names = {“Bill”, “Jack”, “Tom”}
Criteria cr = session.createCriteria(Student.class);
cr.add(Restrictions.in(“name”, names))
List list = cr.list();
Student stu = (Student)list.get(0);
例3:查询学生的年龄age等于22或age为空(null)的所有Student对象。
Criteria cr = session.createCriteria(Student.class);
cr.add(Restrictions.eq(“age”, new Integer(22));
cr.add(Restrictions.isNull(“age”));
List list = cr.list();
Student stu = (Student)list.get(0);
例4:查询学生姓名以字母F开头的所有Student对象,并按姓名升序排序。
Criteria cr = session.createCriteria(Student.class);
cr.add(Restrictions.like(“name”, “F%”);
cr.addOrder(Order.asc(“name”));
List list = cr.list();
Student stu = (Student)list.get(0);
调用Order.asc的方法应是Criteria的addOrder()方法。