Hibernate Criteria查询
Sessions=HibernateSessionFactory.getSession();
Criteriac=s.createCriteria(PetInfo.class);
查询所有数据:
Criteriac=s.createCriteria(Student.class);
Listlist=c.list();
精确查询:
c.add(Restrictions.eq("id",newInteger(22)));
模糊查询:
c.add(Restrictions.like("name","%2%"));
条件查询:
c.add(Restrictions.ge("id",newInteger(9)));
范围查询:
c.add(Restrictions.between("id",newInteger(5),newInteger(8)));
逻辑语句:
and:
c.add(Restrictions.ge("id",newInteger(6)));
c.add(Restrictions.le("age",newInteger(16)));
or:
c.add(Restrictions.or(Restrictions.ge("id",newInteger(6)),Restrictions.le("age",newInteger(16))));
not:
c.add(Restrictions.not(Restrictions.ge("id",newInteger(6))));
//分页
c.setFirstResult(3);//从第几行开始取数据
c.setMaxResults(3);//总共取多少行数据
Listlist=c.list();
排序:
c.addOrder(Order.desc("id"));
分组:
c.setProjection(Projections.groupProperty("age"));
查询的结果只有一个值时:
Objectobj=c.uniqueResult();
统计函数的使用:
avg()rowCount()count()max()min()countDistinct()
c.setProjection(Projections.avg("age"));
在SQL语句中的多条件分组与统计功能,
可以利用ProjectionList类来实现:
Criteriac=session.createCriteria(User.class);
ProjectionListprolist=Projections.projectionList();
prolist.add(Projections.groupProperty("age"));
prolist.add(Projections.rowCount());
c.setProjection(prolist);
通过以上代码,实现了对不同年龄人员数量的分组统计,
当进行检索时,Hibernate会生成类似如下的SQL语句:
Selectage,count(*)fromusergroupbyage;
在Hibernate3中DetachedCriteria类的使用:
构造常用的查询条件,需要的时候与session关联
(与PreparedStatement类似)
DetachedCriteriadc=DetachedCriteria.forClass(User.class);
dc.add(Expression.eq("name","zhaoxin"));
dc.add(Expression.eq("sex","1"));
Criteriac=dc.getExecutableCriteria(session);
Iteratorit=c.list().iterator();
注意:
DetachedCriteria的生存周期与session实例无关,
当需要进行检索时,通过getExecutableCriteria(session)方法,
与当前的Session实例关联并获得运行期的Criteria实例,
完成检索。
DetachedCriteria类实现子查询:
DetachedCriteriadc=DetachedCriteria.forClass(User.class);
dc.setProjection(Projections.avg("age"));
Criteriac=session.createCriteria(User.class);
c.add(Subqueries.propertyGt("age",dc));
Listlist=c.list();
当执行检索时Hibernate会生成类似如下的SQL语句:
Select*fromuserwhereage>
(selectavg(age)fromusergroupbyage);