下面是小弟结合网络和实践学习的一些个人见解,如有错误的地方还望指出。一起努力,共同进步!
Criteria Query 标准查询,说白了就是将标准SQL语句封装成了对象查询,包括标准语句中的where条件,order by条件等都可以通过指定对象拼接生成。
Criteria应用实例1:
Criteria criteria = session.createCriteria(Student.class);//获取criteria对象
criteria.add(Restrictions.eq("stuName", "zhangsan"));//添加等于条件
List rets = criteria.list();
Student student = (Student)ret.get(0);
上面的代码相当与语句from Student where stuName = ' zhangsan'; //这里要注意的是,指定的条件必须是Student对象的属性,且大小写敏感。
开发的思路和步骤就是,用session创建一个实体类的Criteria对象,通过add方法将条件加入到Criteria对象中,执行语句获取结果。
下面列举一下常用到的SQL查询条件在Criteria对象中的对应方法。
方 法 | 说 明 |
Restrictions.eq(prop,value) | equal,= where prop= value |
Restrictions.allEq(map) | 参数为Map对象,使用key/value进行多个等于的对比,相当于多个Restrictions.eq()的效果 where (key1 = value1 and key2 = value2 ) |
Restrictions.gt(prop,value) | greater-than, > where arg0 > value; |
Restrictions.lt(prop,value) | less-than, < |
Restrictions.le(prop,value) Restrictions.ge(prop,value) | less-equal, <= greater-equal, >= |
Restrictions.between(prop,low,high) | 对应SQL的between子句 where prop between low and high |
Restrictions.like(prop,value) | 对应SQL的like子句 where prop like value |
Restrictions.in(prop,Collection/array) | 对应SQL的in子句 (值可以是Collection,也可以是array) prop in (arrayVal0,arrayVal1...) |
Restrictions.and(Criterion1,Criterion2) | and关系,Criteria默认多个add间就是用的and链接,所以这个方法一般不用,只是为了or方法对应 Restrictions.and(Restriction.eq(prop1,value1),Restrictions.eq(prop2,value2)) 相当于where (prop1=value1 and prop2 = value2); |
Restrictions.or(Criterion1,Criterion2) | or关系 Restrictions.or(Restriction.eq(prop1,value1),Restrictions.eq(prop2,value2)) 相当于where (prop1=value1 orprop2 = value2); |
Restrictions.isNull(prop) | 判断属性是否为空,为空返回true,否则返回false where prop is null |
Restrictions.isNotNull(prop) | 与Restrictions.isNull()相反 where prop is not null |
| |
| |
MatchMode.EXACT | 字符串精确匹配,相当于“like 'value'” |
MatchMode.ANYWHERE | 字符串在中间位置,相当于“like '%value%'” |
MatchMode.START | 字符串在最前面的位置,相当于“like 'value%'” |
MatchMode.END | 字符串在最后面的位置,相当于“like '%value'” |
排序在Criteria对象中的使用。
criteria.addOrder(Order.asc("prop")) 按prop升序排列, 多个字段排序用多个addOrder方法
criteria.addOrder(Order.desc("prop")) 按prop降序排列
Criteria进阶查询,对查询结果的操作
统计:criteria.addProjection(Projections....()); 具体参考API的Projections类,支持avg,count,distinct,max,min,sum等函数
分组:criteria.addProjection(Projections.groupProperty("prop"))//对结果group by