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

hibernate 分组查询

2014年09月28日 ⁄ 综合 ⁄ 共 1435字 ⁄ 字号 评论关闭

投影查询

使用聚集函数

在HQL中可以调用

Count:统计函数

Min:求最小值函数

Max:求最大值函数

Sum:求和函数

Avg:求平均数函数

 Count:统计函数

Session session = HibernateSessionFactory.getSession();

Transaction tx = session.beginTransaction();

Integer count = (Integer)session.createQuery("select count(*) from Hx")

.uniqueResult();

System.out.print(count);

tx.commit();

session.close();

Avg:求平均数函数

Session session = HibernateSessionFactory.getSession();

Transaction tx = session.beginTransaction();

Float count = (Float)session.createQuery("select avg(c.id) from Hx c")

 .uniqueResult();

System.out.print(count);

tx.commit();

session.close();

Sum:求和函数

Session session = HibernateSessionFactory.getSession();

Transaction tx = session.beginTransaction();

Integer count = (Integer)session.createQuery("select sum(c.id) from Hx c")

 .uniqueResult();

System.out.print(count);

tx.commit();

session.close();

Min:求最小值函数 Max:求最大值函数

Session session = HibernateSessionFactory.getSession();

Transaction tx = session.beginTransaction();

Object[] count = (Object[])session.createQuery("select min(c.age),max(c.age) from Hx c")

.uniqueResult();

String min = (String)count[0];

String max = (String)count[1];

System.out.print("min="+min+"|max="+max);

tx.commit();

session.close();

分组查询

Session session = HibernateSessionFactory.getSession();

Transaction tx = session.beginTransaction();

Iterator it = session.createQuery("select c.name,count(c) from Hx c group by c.name")

.iterate();

while(it.hasNext())

{

Object[] oc = (Object[])it.next();

String count = (Integer)oc[1]; 

System.out.println(name+":"+count);

}

tx.commit();

session.close();

抱歉!评论已关闭.