新聞中心
Hibernate配備了一種非常強(qiáng)大的Hibernate查詢語句,這種語言看上去很像SQL。本文主要介紹select子句、聚集函數(shù)、多態(tài)查詢。但是不要被語法結(jié)構(gòu) 上的相似所迷惑,HQL是非常有意識(shí)的被設(shè)計(jì)為完全面向?qū)ο蟮牟樵?,它可以理解如繼承、多態(tài) 和關(guān)聯(lián)之類的概念。

景谷網(wǎng)站制作公司哪家好,找成都創(chuàng)新互聯(lián)!從網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、響應(yīng)式網(wǎng)站等網(wǎng)站項(xiàng)目制作,到程序開發(fā),運(yùn)營維護(hù)。成都創(chuàng)新互聯(lián)于2013年成立到現(xiàn)在10年的時(shí)間,我們擁有了豐富的建站經(jīng)驗(yàn)和運(yùn)維經(jīng)驗(yàn),來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選成都創(chuàng)新互聯(lián)。
1. select子句
select 子句選擇將哪些對(duì)象與屬性返 回到查詢結(jié)果集中. 考慮如下情況:
- select mate
- from Cat as cat
- inner join cat.mate as mate
該語句將選擇mates of other Cats。(其他貓的配偶) 實(shí)際上, 你可以更簡潔的用以下的查詢語句表達(dá)相同的含義:
- select cat.mate from Cat cat
Hibernate查詢語句可以返回值為任何類型的屬性,包括返回類型為某種組件(Component)的屬性:
- select cat.name from DomesticCat cat
- where cat.name like 'fri%'
- select cust.name.firstName from Customer as cust
Hibernate查詢語句可以返回多個(gè)對(duì)象和(或)屬性,存放在 Object[]隊(duì)列中,
- select mother, offspr, mate.name
- from DomesticCat as mother
- inner join mother.mate as mate
- left outer join mother.kittens as offspr
或存放在一個(gè)List對(duì)象中,
- select new list(mother, offspr, mate.name)
- from DomesticCat as mother
- inner join mother.mate as mate
- left outer join mother.kittens as offspr
也可能直接返回一個(gè)實(shí)際的類型安全的Java對(duì)象,
- select new Family(mother, mate, offspr)
- from DomesticCat as mother
- join mother.mate as mate
- left join mother.kittens as offspr
假設(shè)類Family有一個(gè)合適的構(gòu)造函數(shù).
你可以使用關(guān)鍵字as給“被選擇了的表達(dá)式”指派別名:
- select max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n
- from Cat cat
這種做法在與子句select new map一起使用時(shí)最有用:
- select new map( max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n )
- from Cat cat
該Hibernate查詢語句返回了一個(gè)Map的對(duì)象,內(nèi)容是別名與被選擇的值組成的名-值映射。
3. 聚集函數(shù)
HQL查詢甚至可以返回作用于屬性之上的聚集函數(shù)的計(jì)算結(jié)果:
- select avg(cat.weight), sum(cat.weight), max(cat.weight), count(cat)
- from Cat cat
受支持的聚集函數(shù)如下:
- avg(...), sum(...), min(...), max(...)
- count(*)
- count(...), count(distinct ...), count(all...)
你可以在選擇子句中使用數(shù)學(xué)操作符、連接以及經(jīng)過驗(yàn)證的SQL函數(shù):
- select cat.weight + sum(kitten.weight)
- from Cat cat
- join cat.kittens kitten
- group by cat.id, cat.weight
- select firstName||' '||initial||' '||upper(lastName) from Person
關(guān)鍵字distinct與all 也可以使用,它們具有與SQL相同的語義.
- select distinct cat.name from Cat cat
- select count(distinct cat.name), count(cat) from Cat cat
3. 多態(tài)查詢
一個(gè)如下的Hibernate查詢語句:
- from Cat as cat
不僅返回Cat類的實(shí)例, 也同時(shí)返回子類 DomesticCat的實(shí)例. Hibernate 可以在from子句中指定任何 Java 類或接口. 查詢會(huì)返回繼承了該類的所有持久化子類 的實(shí)例或返回聲明了該接口的所有持久化類的實(shí)例。下面的查詢語句返回所有的被持久化的對(duì)象:
- from java.lang.Object o
接口Named 可能被各種各樣的持久化類聲明:
- from Named n, Named m where n.name = m.name
注意:***的兩個(gè)查詢將需要超過一個(gè)的SQL SELECT.這表明order by子句 沒有對(duì)整個(gè)結(jié)果集進(jìn)行正確的排序. (這也說明你不能對(duì)這樣的查詢使用Query.scroll()方法.)
新聞標(biāo)題:簡述Hibernate部分查詢語句
本文路徑:http://www.5511xx.com/article/dheiido.html


咨詢
建站咨詢
