QBC(QueryByCriteria)查询方式是Hibernate提供的“更加面向对象”的一种检索方式。QBC在条件查询上比HQL查询更为灵活,而且支持运行时动态生成查询语句。
//查询名字为zhangsan的用户 Criteria criteria = session.createCriteria(User.class); criteria.add(Restrictions.eq("username", "zhangsan")); List<User> users = criteria.list(); for(User user : users){ System.out.println(user.getId() + "--" + user.getUsername()); }
Hibernate中Restrictions的方法 说明
Restrictions.eq =
Restrictions.allEq 利用Map来进行多个等于的限制
Restrictions.gt >
Restrictions.ge >=
Restrictions.lt <
Restrictions.le <=
Restrictions.between BETWEEN
Restrictions.like LIKE
Restrictions.in in
Restrictions.and and
Restrictions.or or
Restrictions.sqlRestriction 用SQL限定查询
查询id大于100,小于200的用户:
Criteria criteria = session.createCriteria(User.class); criteria.add(Restrictions.gt("id", 100)).add(Restrictions.lt("id", 200)); List<User> users = criteria.list(); for(User user : users){ System.out.println(user.getId() + "--" + user.getUsername()); }
通过Example工具类,判断Example.create(example)传进来的example对象里面各个属性是否与数据库中配置。
//查询名字为zhanglinlin的所有的用户 Criteria criteria = session.createCriteria(User.class); User example = new User(); example.setUsername("zhanglinlin"); criteria.add(Example.create(example)); List<User> users = criteria.list(); for(User user : users){ System.out.println(user.getId() + "--" + user.getUsername()); }
Order.asc(StringpropertyName)
升序排序
Order.desc(StringpropertyName)
降序排
Criteria criteria = session.createCriteria(User.class); User example = new User(); example.setUsername("zhanglinlin"); criteria.add(Example.create(example)); //criteria.addOrder(Order.asc("id")); criteria.addOrder(Order.desc("id")); List<User> users = criteria.list(); for(User user : users){ System.out.println(user.getId() + "--" + user.getUsername()); }
Porjections.avg(StringpropertyName)
求某属性的平均值
Projections.count(StringpropertyName)
统计某属性的数量
Projections.countDistinct(StringpropertyName)
统计某属性的不同值的数量
Projections.groupProperty(StringpropertyName)
指定一组属性值
Projections.max(StringpropertyName)
某属性的最大值
Projections.min(StringpropertyName)
某属性的最小值
Projections.projectionList()
创建一个新的projectionList对象
Projections.rowCount()
查询结果集中记录的条数
Projections.sum(StringpropertyName)
返回某属性值的合计
//查询有多少个人的名字为zhanglinlin的 Criteria criteria = session.createCriteria(User.class); User example = new User(); example.setUsername("zhanglinlin"); criteria.add(Example.create(example)); criteria.setProjection(Projections.count("id")); Integer count = (Integer) criteria.uniqueResult(); System.out.println(count);
Criteria criteria = session.createCriteria(User.class); User example = new User(); example.setUsername("zhanglinlin"); criteria.add(Example.create(example)); criteria.setFirstResult(0); //从哪一个记录开始 criteria.setMaxResults(5);//取多少条记录 List<User> users = criteria.list(); for(User user : users){ System.out.println(user.getId() + "--" + user.getUsername()); }