如何在hibernate投影结果上应用命令

时间:2012-03-16 09:06:16

标签: java hibernate list

我使用了以下休眠标准。

Criteria criteria = session.createCriteria(Student.class);
        ProjectionList projectionList = Projections.projectionList();
       projectionList.add(Projections.groupProperty("studentId"));
       projectionList.add(Projections.count("studentId"));
        criteria.setProjection(projectionList);
      return criteria.list();

这将返回一个对象列表,对象有两个字段,studentId和count(studentId)。我想按count(studentId)降序对此列表进行排序。我怎么做这个休眠?

目前我正在

{[1, 5], [2, 7], [3,4]} 

我想明白这个

{[2, 7], [1, 5], [3,4]}

溶液: 这解决了这个问题:)

  Criteria criteria = session.createCriteria(Student.class);
            ProjectionList projectionList = Projections.projectionList();
           projectionList.add(Projections.groupProperty("studentId"));
           projectionList.add( Projections.alias(Projections.count("studentId"),"count"));
            criteria.setProjection(projectionList);
           criteria.addOrder(Order.desc(("count")));
            return criteria.list();

1 个答案:

答案 0 :(得分:4)

由于没有接受答案 - 我格式化并简化了您自己的解决方案:

Criteria criteria = session.createCriteria(Student.class);
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.groupProperty("studentId"));
projectionList.add(Projections.count("studentId"), "count");
criteria.setProjection(projectionList);
criteria.addOrder(Order.desc(("count")));
return criteria.list();