hibernate Restrictions 用法 查询

 

import hibernate classes

 

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
DetachedCriteria criteria = DetachedCriteria.forClass(UserPO.class);
// 按照用户名排序 -- 升序
criteria.addOrder(Order.asc("userName"));
if (user != null) {
	// 按条件查询
	if (user.getUserName() != null && !user.getUserName().trim().equals("")) {
		criteria.add(Restrictions.like("userName", user.getUserName().trim(), MatchMode.ANYWHERE));
	}
}

getHibernateTemplate().findByCriteria(criteria ); // 返回LIST

 

Restrictions 的用法:

 

1、Restrictions

方法 说明
Restrictions.eq equal 等于 ==
Restrictions.allEq 参数为Map对象,使用key/value进行多个等于的对比,相当于多个Restrictions.eq的效果
Restrictions.gt great than 大于 >
Restrictions.ge great equal 大于等于 >=
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 判断属性是否为null,为空则返回true
Restrictions.sqlRestriction SQL限定的查询


2、Order

 

 

Order.asc 根据传入的字段进行升序排序
Order.desc                             降序

 

 

3、MatchMode

 

 

MatchMode.EXACT 字符串精确匹配,相当于: like 'value'
MatchMode.ANYWHERE                    字符串在中间匹配 like '%value%'
MatchMode.START 匹配前面 like 'value%'
MatchMode.END like '%value'

 

 

例子:

 

// 查询年龄在20-30岁之间的所有学生对象
List list = session.createCriteria(Student.class)
       .add(Restrictions.between("age",new Integer(20),new Integer(30)).list();
// 查询学生姓名在AAA,BBB,CCC之间的学生对象
String[] names = {"AAA","BBB","CCC"};
List list = session.createCriteria(Student.class)
       .add(Restrictions.in("name",names)).list();
// 查询年龄为空的学生对象
List list = session.createCriteria(Student.class)
       .add(Restrictions.isNull("age")).list();
// 查询年龄等于20或者年龄为空的学生对象
List list = session.createCriteria(Student.class)
       .add(Restrictions.or(Restrictions.eq("age",new Integer(20)),
                 Restrictions.isNull("age")).list();

 

or可以无限加

 

 

 

.

你可能感兴趣的:(Restrictions)