现在的位置: 首页 > 综合 > 正文

条件查询(criteria)

2018年02月04日 ⁄ 综合 ⁄ 共 996字 ⁄ 字号 评论关闭
  1. 分页中有重复记录统计总的条数
  • int total = ((Integer)criteria.setProjection(Projections.countDistinct
    ("id")).uniqueResult()).intValue();

          执行后的语句 select count(distcint id) from  table;

  • 没有重复记录的时候

          int total = ((Integer)criteria.setProjection(Projections.rowCount
()).uniqueResult()).intValue();

          执行后的语句 select count(*) from  table;

 

      2.  查询结果除掉重复的记录

  •  第一种是数据库的distinct

          ProjectionList projectionList = Projections.projectionList();
          projectionList.add(Projections.property("id"));
          projectionList.add(Projections.property("name")); 
          criteria.setProjection(Projections.distinct(projectionList));

          执行的sql语句   SQL: select distinct id, name from table;

 

          criteria.setProjection(Projections.distinct(Projections.property("id")));

          执行的sql语句   SQL: select distinct id from table;

 

  • 第二种是在结果集中通过hibernate去重,对大量数据效率太低,如果是分页查询还是不能用这种的
    ,因为它是查询后的出重。

          criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

 

      3.Criteria的结果集

         Criteria的结果集最常用分两种:对象List、List<Object[]>(投影查询)

 

 

 

抱歉!评论已关闭.