Hibernate QBC
介绍:
QBC(Query By Criteria)通过 API 来检索对象
主要由 Criteria 接口、Criterion 接口和 Exception 类组成,支持在运行时动态生成查询语句。
声明
事先定义:Department Employee 两个实体类
示例
查询
ListempList = session.createCriteria(Employee.class).list();
分页
ListempList = session.createCriteria(Employee.class).setFirestResult(0).setMaxResults(4).list();
Like 查询,忽略大小写
ListempList = session.createCriteria(Employee.class).add(Restrictions.like("ename","a",MatchMode.ANYWHERE).ignoreCase()).list();
between 查询
listempList = session.createCriteria(Employee.class).add(Restrictions.between("hiredate",begindate,enddate)).list();
in 查询
listempList = session.createCriteria(Employee.class).add(Restrictions.in("id",new Integer[]{12,123})).list();
> 或 >=
listempList = session.createCriteria(Employee.class).add(Restrictions.ge("id",123)).list();
多条件查询
listempList = session.createCriteria(Employee.class).add(Restrictions.ge("id",123)).add(Restrictions.between("hiredate",begindate,enddate)).add(Restrictions.like("ename","a", MatchMode.ANYWHERE).ignoreCase()).list();
排序
listempList = session.createCriteria(Employee.class).addOrder(Order.desc("salary")).list();
统计
listempList = session.createCriteria(Employee.class).setProjection(Projections.rowCount()).add(Restrictions.eq("dept.id",20)).list();
count 统计
listempList = session.createCriteria(Employee.class).setProjection(Projection.projectionList().add(Projetions.property("dept.id")).add(Projections.rowCount()).add(Projections.avg("salary")).add(Projections.max("salary")).add(Projections.min("salary")).add(Projections.sum("salary")).add(Projections.groupProperty("dept.id"))).list();
非空查询
listempList = session.createCriteria(Employee.class).add(Restrictions.isNotNull("comm")).list();