Hibernate hql 查询指定字段并获取结果集
Hibernate hql 查詢指定字段并獲取結(jié)果集
在hibernate中,用hql語句查詢實(shí)體類,采用list方法的返回結(jié)果為一個List,該List中封裝的對象分為以下三種情況:
- 1.查詢?nèi)孔侄?/strong>的情況下,如”from 實(shí)體類”,list中封裝的對象為實(shí)體類本身,各屬性都將得到填充。
- 2.只查詢一個字段,默認(rèn)情況下,list中封裝的是Object對象。
- 3.查詢兩個或兩個以上的字段,默認(rèn)情況下,list中封裝的是Object[],長度與所查詢的字段數(shù)一致。
對于后兩種情況,用標(biāo)簽遍歷時不太方便,因?yàn)闊o法直接轉(zhuǎn)換成實(shí)體類的對象。比較簡單的解決方法是:
- の:在hql中使用select new 包名.類名(屬性1,屬性2……) from 實(shí)體類,同時在實(shí)體類中添加帶參的構(gòu)造方法,參數(shù)的個數(shù)和順序與(屬性1,屬性2……) 保持一致,這樣我們得到的list中存放的依然是實(shí)體類的對象,所查詢到的屬性得到了填充,使用起來更為方便。
の:hql查詢多表部分字段,select new 包名.表1實(shí)體類名(表1.屬性1,表2.屬性2……) from 表1實(shí)體類,表2實(shí)體類 where 表1.ID=表2.ID(即相關(guān)聯(lián)的字段),同時在要返回的表1實(shí)體類中添加表2的屬性和帶參的構(gòu)造方法,參數(shù)的個數(shù)和順序與(表1.屬性1,表2.屬性 2……) 保持一致
注意:一般可以不加包名,比如: 1.有包名時 select new com.java.pojo.Problem(pid,score,title,totalAccept,totalSubmission) from Problem 2.可以簡略為不加包名 select new Problem(pid,score,title,totalAccept,totalSubmission) from Problem但是如果使用不加包名的語句時,一直報異常時,說明表名與內(nèi)部存在沖突,此時包名不能省略。
例如要查詢Problem 中的pid,score,title,totalAccept,totalSubmission,unSee
偽代碼
public class Problem { private int pid; private int score; private int timeLimit; private int memoryLimit; private int totalAccept; private int totalSubmission; private int unSee; private String title; private String description; private String input; private String output; public Problem(int pid, int score,String title, int totalAccept, int totalSubmission, int unSee) { super(); this.pid = pid; this.score = score; this.totalAccept = totalAccept; this.totalSubmission = totalSubmission; this.unSee = unSee; this.title = title; } //省略getter 和 setter }查詢語句如下
Query query=session.createQuery("select new Problem(pid,score,title,totalAccept,totalSubmission,unSee) from Problem order by pid"); //query.setFirstResult(firstResult); //分頁函數(shù) //query.setMaxResults(maxResutl); List<Problem> problems=query.list();//返回的還是Problem對象關(guān)于hibernate的問題:
我現(xiàn)在有條
hql=”select s.id,s.name,t.id,t.name from User s,Useraddress t where t.id=s.id”
這條sql里面的User和Useraddress是兩個實(shí)體類,現(xiàn)在組合查詢分別取出來兩個實(shí)體類里面的兩個字段,然后我想再建立一個實(shí)體類Result,里面定義這四個結(jié)果集里面的字段,能不能執(zhí)行完這條hql,正好把這個結(jié)果集對應(yīng)到實(shí)體類Result里面呢,Result這個實(shí)體類,沒寫映射文件Result.hbm.xml.
希望能幫下忙
2種做法
方法一:創(chuàng)建實(shí)體類
創(chuàng)建一個class temp ,有屬性sid,name,tid,sname,tname
創(chuàng)建一個構(gòu)造函數(shù)
public temp(sid,name,tid,sname,tname) {..... }hql中
List<temp>select new temp(s.id,s.name,t.id,t.name) from User s,Useraddress t where t.id=s.id
方法二:List
記錄的每一行是object[] 遍歷
object[0] ==s.id
object[1] ==s.name
object[2] ==t.id
object[3] ==t.name
總結(jié)
以上是生活随笔為你收集整理的Hibernate hql 查询指定字段并获取结果集的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深入浅出谈接口(interface)和类
- 下一篇: Eclipse启动项目时,删除works