HQL (十) 统计查询

统计查询(重要)
参见:StatQueryTest.java

package com.wlh.hibernate;

import java.util.Iterator;
import java.util.List;

import org.hibernate.Session;

import junit.framework.TestCase;

public class StateQueryTest extends TestCase{
	
	/**
	 * 统计所有的学生	 */
	public void testQuery1() {
		Session session = null;
		try {
			session = HibernateUtils.getSession();
			session.beginTransaction();
		  /*List students=(List) session.createQuery("[b]select count(*) from Student [/b] ");
		    Long count=(Long) students.get(0);*/
			
			Long count=(Long) session.createQuery("select count(*) from Student ").uniqueResult();
			System.out.println("count="+count);
			session.getTransaction().commit();
		}catch(Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}finally {
			HibernateUtils.closeSession(session);
		}
	}	
	
	/**
	 * 统计各个班级的学生各是多少	 */
	public void testQuery2() {
		Session session = null;
		try {
			session = HibernateUtils.getSession();
			session.beginTransaction();
			
			List list=session.createQuery("select c.name,count(*) from Student s join s.classes c group by c.id order by c.id ").list();
			
			for(Iterator iter=list.iterator();iter.hasNext();){
				Object [] o=(Object[]) iter.next();
				System.out.println("o.name="+o[0]+",o.count="+o[1]);
			}
			session.getTransaction().commit();
		}catch(Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}finally {
			HibernateUtils.closeSession(session);
		}
	}	
}

你可能感兴趣的:(java,C++,c,Hibernate,C#)