Hibernate hql 查詢指定欄位並擷取結果集

來源:互聯網
上載者:User

在hibernate中,用hql語句查詢實體類,採用list方法的返回結果為一個List,該List中封裝的對象分為以下三種情況:
1.查詢全部欄位的情況下,如"from 實體類",list中封裝的對象為實體類本身,各屬性都將得到填充。
2.只查詢一個欄位,預設情況下,list中封裝的是Object對象。
3.查詢兩個或兩個以上的欄位,預設情況下,list中封裝的是Object[],長度與所查詢的欄位數一致。

對於後兩種情況,用標籤遍曆時不太方便,因為無法直接轉換成實體類的對象。比較簡單的解決方案是:

の:在hql中使用select new 包名.類名(屬性1,屬性2……) from 實體類,同時在實體類中添加帶參的構造方法,參數的個數和順序與(屬性1,屬性2……) 保持一致,這樣我們得到的list中存放的依然是實體類的對象,所查詢到的屬性得到了填充,使用起來更為方便。

  の:hql查詢多表部分欄位,select new 包名.表1實體類名(表1.屬性1,表2.屬性2……) from 表1實體類,表2實體類 where 表1.ID=表2.ID(即相關聯的欄位),同時在要返回的表1實體類中添加表2的屬性和帶參的構造方法,參數的個數和順序與(表1.屬性1,表2.屬性 2……) 保持一致

例如要查詢Problem 中的pid,score,title,totalAccept,totalSubmission,unSee

  1. public class Problem {  
  2.     private int pid;  
  3.     private int score;  
  4.     private int timeLimit;  
  5.     private int memoryLimit;  
  6.     private int totalAccept;  
  7.     private int totalSubmission;  
  8.     private int unSee;  
  9.     private String title;  
  10.     private String description;  
  11.     private String input;  
  12.     private String output;  
  13.       
  14.     public Problem(int pid, int score,String title, int totalAccept, int totalSubmission,  
  15.              int unSee) {  
  16.         super();  
  17.         this.pid = pid;  
  18.         this.score = score;  
  19.         this.totalAccept = totalAccept;  
  20.         this.totalSubmission = totalSubmission;  
  21.         this.unSee = unSee;  
  22.         this.title = title;  
  23.     }  
  24.     //省略getter 和 setter   
  25. }  
查詢語句如下
  1.       Query query=session.createQuery("select new Problem(pid,score,title,totalAccept,totalSubmission,unSee) from Problem order by pid");  
  2.         //query.setFirstResult(firstResult); //分頁函數   
  3.         //query.setMaxResults(maxResutl);   
  4.       
  5.         List<Problem> problems=query.list();//返回的還是Problem對象 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.