Hibernate中HQL的統計查詢

Java代碼 
  1. import java.util.Iterator;  
  2. import java.util.List;  
  3.   
  4. import junit.framework.TestCase;  
  5.   
  6. import org.hibernate.Query;  
  7. import org.hibernate.SQLQuery;  
  8. import org.hibernate.Session;  
  9.   
  10. import cn.edu.ahau.mgc.hibernate.factory.HibernateSessionFactory;  
  11.   
  12. public class TestCount extends TestCase {  
  13.   
  14.       
  15.     public void test2() {  
  16.         Session session = null;  
  17.         try {  
  18.             session = HibernateSessionFactory.getSession();  
  19.             List<Object[]> results = session.createQuery("select c.id,c.name,count(s) from Student s join s.classes c group by c.id, c.name").list();  
  20.             for (Iterator<Object[]> iterator = results.iterator(); iterator.hasNext();) {  
  21.                 Object[] result = iterator.next();  
  22.                Long countLong=(Long)result[2];//需轉爲long對象  
  23.                Integer count=Integer.parseInt(countLong.toString());  
  24.                 System.out.println("----ID:" + result[0] + ";Name:" + result[1] + "Students Count:" + count);  
  25.             }  
  26.         } catch (Exception e) {  
  27.             e.printStackTrace();  
  28.         } finally {  
  29.             HibernateSessionFactory.closeSession();  
  30.         }  
  31.     }  
  32.       
  33. }  
發佈了18 篇原創文章 · 獲贊 3 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章