方法 | 说明 |
Restrictions.eq | = |
Restrictions.allEq | 利用Map来进行多个等于的限制 |
Restrictions.gt | > |
Restrictions.ge | >= |
Restrictions.lt | < |
Restrictions.le | <= |
Restrictions.between | BETWEEN |
Restrictions.like | LIKE |
Restrictions.in | in |
Restrictions.and | and |
Restrictions.or | or |
Restrictions.sqlRestriction | 用SQL限定查询 |
有空再添加上,代码示例。
QBC常用限定方法
Restrictions.eq
Restrictions.allEq
Restrictions.gt
Restrictions.ge
Restrictions.lt
Restrictions.le
Restrictions.between
Restrictions.like
Restrictions.in
Restrictions.and
Restrictions.or
Restrictions.isNull
Restrictions.isNotNull
Restrictions.sqlRestriction
Order.asc
Order.desc
MatchMode.EXACT
MatchMode.ANYWHERE
MatchMode.START
MatchMode.END
例子
查询年龄在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();
--------------------------------------------------------------------
使用QBC实现动态查询
public List findStudents(String name,int age){
Criteria criteria = session.createCriteria(Student.class);
if(name != null){
criteria.add(Restrictions.liek("name",name,MatchMode.ANYWHERE));
}
if(age != 0){
criteria.add(Restrictions.eq("age",new Integer(age)));
}
criteria.addOrder(Order.asc("name"));//根据名字升序排列
return criteria.list();
}
-----------------------------------------------------------------------------------
今天用了写hibernate高级查询时用了Restrictions(当然Expression也是可以以的)这个类.感觉不错.
下面的代码写的不易读.其实核心就是一句
Restrictions.or(Restrictions.like(),Restrictions.or(Restrictions.like,........))
里面的or可以无限加的.还是比较好用
Session session = getHibernateTemplate().getSessionFactory()
.openSession();
Criteria criteria = session.createCriteria(Film.class);
List<Film> list = criteria.add(
Restrictions.or(Restrictions.like("description", key,MatchMode.ANYWHERE),
Restrictions.or(Restrictions.like("name", key,MatchMode.ANYWHERE),
Restrictions.or( Restrictions.like("direct", key,MatchMode.ANYWHERE),
Restrictions.or(Restrictions.like("mainplay",key,MatchMode.ANYWHERE),
Restrictions.like("filearea", key,MatchMode.ANYWHERE)))))).list();
session.close();
return list;