QBC查询:
Query By Criteria
使用面向对象的方式查询
和HQL单表查询相似,但不包含别名查询和具名查询
1 全表查询
Criteria ce = session.createCriteria(Customer.class);
List<Customer> list = ce.list();
for(Customer customer : list) {
System.out.println(customer);
}
2 条件查询
Criteria ce = session.createCriteria(Order.class);
ce.add(Restrictions.eq("orderno", "111"));
List<Order> list = ce.list();
Criteria ce = session.createCriteria(Order.class);
ce.add(Restrictions.and(
Restrictions.like("orderno", "%111%"),
Restrictions.like("productName", "%手机%")
));
List<Order> list = ce.list();
3 分页查询
Criteria ce = session.createCriteria(Order.class);
//分页
ce.setFirstResult(0);
ce.setMaxResults(5);
List<Order> list = ce.list();
4 查询排序
Criteria ce = session.createCriteria(Order.class);
ce.addOrder(org.hibernate.criterion.Order.desc("id"));
List<Order> list = ce.list();
5 聚合查询
Criteria ce = session.createCriteria(Order.class);
/*ce.setProjection(Projections.rowCount());
Long count = (Long)ce.uniqueResult();*/
ce.setProjection(Projections.max("id"));
Integer count = (Integer)ce.uniqueResult();
System.out.println(count);
6 投影查询
Criteria ce = session.createCriteria(Order.class);
ProjectionList pList = Projections.projectionList();
pList.add(Property.forName("orderno"));
pList.add(Property.forName("productName"));
ce.setProjection(pList);
List<Object[]> list = ce.list();
for(Object[] order : list) {
for(Object column : order) {
System.out.print(column);
System.out.print(" ");
}
System.out.println();
}