条件查询
//比较运算
cri.add(Restrictions.eq("bookName","sql")); //eq等于 le小于等于 lt小于 ge大于等于 gt大于
//模糊查询
cri.add(Restrictions.like("bookName","%a%"));
//范围运算
Restrictions.in
( )
//逻辑运算
Restrictions.and( )
cri.add(Restrictions.or(Restrictions.eq("bookName","sql"),Expression.eq("price",50)));
criteria.addOrder(Order.desc("price"));
集合运算
Restrictions.isEmpty( )
排序
List<Emp> list = session.createCriteria(Emp.class)
.add(
Restrictions.gt
("salary", 4000D))
.addOrder(Order.asc("salary"))
.addOrder(Order.desc("empNo")).list();
分页:
criteria.setFirstResult(); 设置当前页起始行索引
criteria.setMaxResults(); 设置每页记录条数
List<Emp> list = session.createCriteria(Emp.class)
.add(Restrictions.isNotNull("salary"))
.addOrder(Order.desc("salary"))
.setFirstResult(0)
.setMaxResults(2).list();
查询唯一对象:
Emp emp = (Emp) session.createCriteria(Emp.class)
.add(Restrictions.isNotNull("salary"))
.addOrder(Order.desc("salary"))
.setMaxResults(1)
.uniqueResult();
关联:
方式一:
List<Emp> list = session.createCriteria(Emp.class)
.add(Restrictions.ilike("empName", "a", MatchMode.ANYWHERE))
.createCriteria("dept")
.add(Restrictions.eq("deptName", "财务部").ignoreCase()) .list();
方式二:
List<Emp> list = session.createCriteria(Emp.class, "e")
.createAlias("dept", "d")
.add(Restrictions.ilike("e.empName", "a",MatchMode.ANYWHERE))
.add(Restrictions.eq("d.deptName", "财务部").ignoreCase()).list();
投影:
List<String> list = session.createCriteria(Dept.class).setProjection(Property.forName("deptName")).list();
List<Object[]> list = session.createCriteria(Emp.class)
.setProjection(Projections.projectionList().add(Property.forName("empName")).add(Property.forName("hiredate"))).list();
分组、聚合函数:
List<Object[]> list = session.createCriteria(Emp.class, "e").createAlias("e.dept", "d")
.setProjection(Projections.projectionList().add(Projections.groupProperty("d.deptName"))
.add(Projections.avg("e.salary")).add(Projections.max("e.salary")).add(Projections.min("e.salary"))).list();
for (Object[] obj : list) {
System.out.println(obj[0] + ","+obj[1]+ ","+obj[2]+ ","+obj[3]);
}
DetachedCriteria查询:
DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Emp.class, "e").createAlias("e.dept", "d")
.add(Restrictions.eq("d.deptName", "财务部").ignoreCase()).add(Restrictions.ilike("e.empName", "a",MatchMode.ANYWHERE));
List<Emp> list = detachedCriteria.getExecutableCriteria(session).list();
3. 注解
Hibernate 提供了注解进行对象--关系映射,它可以代替大量的hbm.xml 文件,使得Hibernate 程序的文件的数量大大精简。使用注解,可以直接映射信息定义在持久化类中,而无需编写对应的*.hbm.xml文件。