1. 程式人生 > >Hibernate hql查詢語句 Count:統計函式 Min:求最小值函式 Max:求最大值函式 Sum:求和函式 Avg:求平均數函式

Hibernate hql查詢語句 Count:統計函式 Min:求最小值函式 Max:求最大值函式 Sum:求和函式 Avg:求平均數函式

在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();