mingyb3
mingyb3
2016-05-03 12:47

Hibernate中hql如何使用聚合函数sum和group by组合查询!

背景:有一张记录各个班级的成绩表;
目的:需要使用hql查询出各个班级对应的总分;

表对应的类:
public class One_Class implements Serializable {

private String address;
private String subject;
private String classes;
private int score;

//get和set方法省略;
//构造方法:
    public One_Class(String classes,int score) {
    this.classes=classes;
    this.score=score;
}

}

//测试方法:
    @Test
public void query() {
    Transaction tx = null;
    Session session = null;
    session = HibernateUtils.getSession();
    tx = session.beginTransaction();
    try {
    //我的想法是通过构造方法 将查询的值传入;但是不行;还请高手指导,分组+sum如何实现?谢谢!
        String hql = "select new One_Class(classes,sum(score)) from One_Class group by classes";
        System.out.println(hql);

        Query query = session.createQuery(hql);
        List<Object[]> list = query.list();
        System.out.println(list.get(0));

        int row = list.size();
        System.out.println(row);
        tx.commit();
    } catch (HibernateException he) {
        he.printStackTrace();
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        HibernateUtils.closeSession(session);
    }
}
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

0条回答