seasun  
          在不斷模仿、思考、總結(jié)中一步一步進(jìn)步!
          公告
          •     我的blog中的部分資源是來自于網(wǎng)絡(luò)上,如果您認(rèn)為侵犯了您的權(quán)利,請及時聯(lián)系我我會盡快刪除!E-MAIL:shiwenfeng@aliyun.com和QQ:281340916,歡迎交流。

          日歷
          <2010年1月>
          272829303112
          3456789
          10111213141516
          17181920212223
          24252627282930
          31123456

          導(dǎo)航

          常用鏈接

          隨筆分類

          good blog author

          積分與排名

          • 積分 - 81762
          • 排名 - 700

          最新評論

          閱讀排行榜

           
          請查看此blog: http://conkeyn.javaeye.com/category/35770

          HQL: Hibernate查詢語言

          Hibernate配備了一種非常強(qiáng)大的查詢語言,這種語言看上去很像SQL。但是不要被語法結(jié)構(gòu)上的相似所迷惑,HQL是非常有意識的被設(shè)計(jì)為完全面向?qū)ο蟮牟樵儯梢岳斫馊缋^承、多態(tài) 和關(guān)聯(lián)之類的概念。

          1.大小寫敏感性問題

          除了Java類與屬性的名稱外,查詢語句對大小寫并不敏感。 所以 SeLeCT sELEct 以及 SELECT 是相同的,但是 org.hibernate.eg.FOO 并不等價于 org.hibernate.eg.Foo 并且 foo.barSet 也不等價于 foo.BARSET

          本手冊中的HQL關(guān)鍵字將使用小寫字母. 很多用戶發(fā)現(xiàn)使用完全大寫的關(guān)鍵字會使查詢語句 的可讀性更強(qiáng), 但我們發(fā)現(xiàn),當(dāng)把查詢語句嵌入到Java語句中的時候使用大寫關(guān)鍵字比較難看。

          2.from子句

          Hibernate中最簡單的查詢語句的形式如下:

          from eg.Cat
          
          

          該子句簡單的返回eg.Cat 類的所有實(shí)例。通常我們不需要使用類的全限定名, 因?yàn)?auto-import (自動引入) 是缺省的情況。所以我們幾乎只使用如下的簡單寫法:

          from Cat
          
          

          大多數(shù)情況下, 你需要指定一個別名 , 原因是你可能需要 在查詢語句的其它部分引用到Cat

          from Cat as cat
          
          

          這個語句把別名cat 指定給類Cat 的實(shí)例, 這樣我們就可以在隨后的查詢中使用此別名了。關(guān)鍵字as 是可選的,我們也可以這樣寫:

          from Cat cat
          
          

          子句中可以同時出現(xiàn)多個類, 其查詢結(jié)果是產(chǎn)生一個笛卡兒積或產(chǎn)生跨表的連接。

          from Formula, Parameter
          
          
          from Formula as form, Parameter as param
          
          

          查詢語句中別名的開頭部分小寫被認(rèn)為是實(shí)踐中的好習(xí)慣, 這樣做與Java變量的命名標(biāo)準(zhǔn)保持了一致 (比如,domesticCat )。

          3.關(guān)聯(lián)(Association)與連接(Join)

          我們也可以為相關(guān)聯(lián)的實(shí)體甚至是對一個集合中的全部元素指定一個別名, 這時要使用關(guān)鍵字join

          from Cat as cat
          inner join cat.mate as mate
          left outer join cat.kittens as kitten
          
          
          from Cat as cat left join cat.mate.kittens as kittens
          
          
          from Formula form full join form.parameter param
          
          

          受支持的連接類型是從ANSI SQL中借鑒來的。

          • inner join (內(nèi)連接)

          • left outer join (左外連接)

          • right outer join (右外連接)

          • full join (全連接,并不常用)

          語句inner join , left outer join 以及 right outer join 可以簡寫。

          from Cat as cat
          join cat.mate as mate
          left join cat.kittens as kitten
          
          

          還有,一個"fetch"連接允許僅僅使用一個選擇語句就將相關(guān)聯(lián)的對象或一組值的集合隨著他們的父對象的初始化而被初始化,這種方法在使用到集合的情況下尤其有用,對于關(guān)聯(lián)和集合來說,它有效的代替了映射文件中的外聯(lián)接與延遲聲明(lazy declarations). 查看 第20.1節(jié) “ 抓取策略(Fetching strategies) ” 以獲得等多的信息。

          from Cat as cat
          inner join fetch cat.mate
          left join fetch cat.kittens
          
          

          一個fetch連接通常不需要被指定別名, 因?yàn)橄嚓P(guān)聯(lián)的對象不應(yīng)當(dāng)被用在 where 子句 (或其它任何子句)中。同時,相關(guān)聯(lián)的對象并不在查詢的結(jié)果中直接返回,但可以通過他們的父對象來訪問到他們。

          注意fetch 構(gòu)造變量在使用了scroll() iterate() 函數(shù)的查詢中是不能使用的。最后注意,使用full join fetch right join fetch 是沒有意義的。

          如果你使用屬性級別的延遲獲取(lazy fetching)(這是通過重新編寫字節(jié)碼實(shí)現(xiàn)的),可以使用 fetch all properties 來強(qiáng)制Hibernate立即取得那些原本需要延遲加載的屬性(在第一個查詢中)。

          from Document fetch all properties order by name
          
          
          from Document doc fetch all properties where lower(doc.name) like '%cats%'
          
          

          4.select子句

          select 子句選擇將哪些對象與屬性返回到查詢結(jié)果集中. 考慮如下情況:

          select mate
          from Cat as cat
          inner join cat.mate as mate
          
          

          該語句將選擇mate s of other Cat s。(其他貓的配偶) 實(shí)際上, 你可以更簡潔的用以下的查詢語句表達(dá)相同的含義:

          select cat.mate from Cat cat
          
          

          查詢語句可以返回值為任何類型的屬性,包括返回類型為某種組件(Component)的屬性:

          select cat.name from DomesticCat cat
          where cat.name like 'fri%'
          
          
          select cust.name.firstName from Customer as cust
          
          

          查詢語句可以返回多個對象和(或)屬性,存放在 Object[] 隊(duì)列中,

          select mother, offspr, mate.name
          from DomesticCat as mother
          inner join mother.mate as mate
          left outer join mother.kittens as offspr
          
          

          或存放在一個List 對象中,

          select new list(mother, offspr, mate.name)
          from DomesticCat as mother
          inner join mother.mate as mate
          left outer join mother.kittens as offspr
          
          

          也可能直接返回一個實(shí)際的類型安全的Java對象,

          select new Family(mother, mate, offspr)
          from DomesticCat as mother
          join mother.mate as mate
          left join mother.kittens as offspr
          
          

          假設(shè)類Family 有一個合適的構(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 一起使用時最有用:

          select new map( max(bodyWeight) as max, min(bodyWeight) as min, count(*) as n )
          from Cat cat
          
          

          該查詢返回了一個Map 的對象,內(nèi)容是別名與被選擇的值組成的名-值映射。

          5.聚集函數(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
          
          

          6.多態(tài)查詢

          一個如下的查詢語句:

          from Cat as cat
          
          

          不僅返回Cat 類的實(shí)例, 也同時返回子類 DomesticCat 的實(shí)例. Hibernate 可以在from 子句中指定任何 Java 類或接口. 查詢會返回繼承了該類的所有持久化子類的實(shí)例或返回聲明了該接口的所有持久化類的實(shí)例。下面的查詢語句返回所有的被持久化的對象:

          from java.lang.Object o
          
          

          接口Named 可能被各種各樣的持久化類聲明:

          from Named n, Named m where n.name = m.name
          
          

          注意,最后的兩個查詢將需要超過一個的SQL SELECT .這表明order by 子句 沒有對整個結(jié)果集進(jìn)行正確的排序. (這也說明你不能對這樣的查詢使用Query.scroll() 方法.)

          7.where子句

          where 子句允許你將返回的實(shí)例列表的范圍縮小. 如果沒有指定別名,你可以使用屬性名來直接引用屬性:

          from Cat where name='Fritz'
          
          

          如果指派了別名,需要使用完整的屬性名:

          from Cat as cat where cat.name='Fritz'
          
          

          返回名為(屬性name等于)'Fritz'的Cat 類的實(shí)例。

          select foo
          from Foo foo, Bar bar
          where foo.startDate = bar.date
          
          

          將返回所有滿足下面條件的Foo 類的實(shí)例:存在如下的bar 的一個實(shí)例,其date 屬性等于 Foo startDate 屬性。 復(fù)合路徑表達(dá)式使得where 子句非常的強(qiáng)大,考慮如下情況:

          from Cat cat where cat.mate.name is not null
          
          

          該查詢將被翻譯成為一個含有表連接(內(nèi)連接)的SQL查詢。如果你打算寫像這樣的查詢語句

          from Foo foo
          where foo.bar.baz.customer.address.city is not null
          
          

          在SQL中,你為達(dá)此目的將需要進(jìn)行一個四表連接的查詢。

          = 運(yùn)算符不僅可以被用來比較屬性的值,也可以用來比較實(shí)例:

          from Cat cat, Cat rival where cat.mate = rival.mate
          
          
          select cat, mate
          from Cat cat, Cat mate
          where cat.mate = mate
          
          

          特殊屬性(小寫)id 可以用來表示一個對象的唯一的標(biāo)識符。(你也可以使用該對象的屬性名。)

          from Cat as cat where cat.id = 123
          from Cat as cat where cat.mate.id = 69
          
          

          第二個查詢是有效的。此時不需要進(jìn)行表連接!

          同樣也可以使用復(fù)合標(biāo)識符。比如Person 類有一個復(fù)合標(biāo)識符,它由country 屬性 與medicareNumber 屬性組成。

          from bank.Person person
          where person.id.country = 'AU'
          and person.id.medicareNumber = 123456
          
          
          from bank.Account account
          where account.owner.id.country = 'AU'
          and account.owner.id.medicareNumber = 123456
          
          

          第二個查詢也不需要進(jìn)行表連接。

          同樣的,特殊屬性class 在進(jìn)行多態(tài)持久化的情況下被用來存取一個實(shí)例的鑒別值(discriminator value)。 一個嵌入到where子句中的Java類的名字將被轉(zhuǎn)換為該類的鑒別值。

          from Cat cat where cat.class = DomesticCat
          
          

          你也可以聲明一個屬性的類型是組件或者復(fù)合用戶類型(以及由組件構(gòu)成的組件等等)。永遠(yuǎn)不要嘗試使用以組件類型來結(jié)尾的路徑表達(dá)式(path-expression_r)(與此相反,你應(yīng)當(dāng)使用組件的一個屬性來結(jié)尾)。 舉例來說,如果store.owner 含有一個包含了組件的實(shí)體address

          store.owner.address.city    // 正確
          store.owner.address         // 錯誤!
          
          

          一個“任意”類型有兩個特殊的屬性id class , 來允許我們按照下面的方式表達(dá)一個連接(AuditLog.item 是一個屬性,該屬性被映射為<any> )。

          from AuditLog log, Payment payment
          where log.item.class = 'Payment' and log.item.id = payment.id
          
          

          注意,在上面的查詢與句中,log.item.class payment.class 將涉及到完全不同的數(shù)據(jù)庫中的列。

          8.表達(dá)式

          where 子句中允許使用的表達(dá)式包括大多數(shù)你可以在SQL使用的表達(dá)式種類:

          • 數(shù)學(xué)運(yùn)算符+, -, *, /

          • 二進(jìn)制比較運(yùn)算符=, >=, <=, <>, !=, like

          • 邏輯運(yùn)算符and, or, not

          • in , not in , between , is null , is not null , is empty , is not empty , member of and not member of

          • "簡單的" case, case ... when ... then ... else ... end ,和 "搜索" case, case when ... then ... else ... end

          • 字符串連接符...||... or concat(...,...)

          • current_date() , current_time() , current_timestamp()

          • second(...) , minute(...) , hour(...) , day(...) , month(...) , year(...) ,

          • EJB-QL 3.0定義的任何函數(shù)或操作:substring(), trim(), lower(), upper(), length(), locate(), abs(), sqrt(), bit_length()

          • coalesce() nullif()

          • cast(... as ...) , 其第二個參數(shù)是某Hibernate類型的名字,以及extract(... from ...) ,只要ANSI cast() extract() 被底層數(shù)據(jù)庫支持

          • 任何數(shù)據(jù)庫支持的SQL標(biāo)量函數(shù),比如sign() , trunc() , rtrim() , sin()

          • JDBC參數(shù)傳入 ?

          • 命名參數(shù):name , :start_date , :x1

          • SQL 直接常量 'foo' , 69 , '1970-01-01 10:00:01.0'

          • Java public static final 類型的常量 eg.Color.TABBY

          關(guān)鍵字in between 可按如下方法使用:

          from DomesticCat cat where cat.name between 'A' and 'B'
          
          
          from DomesticCat cat where cat.name in ( 'Foo', 'Bar', 'Baz' )
          
          

          而且否定的格式也可以如下書寫:

          from DomesticCat cat where cat.name not between 'A' and 'B'
          
          
          from DomesticCat cat where cat.name not in ( 'Foo', 'Bar', 'Baz' )
          
          

          同樣, 子句is null is not null 可以被用來測試空值(null).

          在Hibernate配置文件中聲明HQL“查詢替代(query substitutions)”之后,布爾表達(dá)式(Booleans)可以在其他表達(dá)式中輕松的使用:

          <property name="hibernate.query.substitutions">true 1, false 0</property>
          
          

          系統(tǒng)將該HQL轉(zhuǎn)換為SQL語句時,該設(shè)置表明將用字符 1 0 來 取代關(guān)鍵字true false :

          from Cat cat where cat.alive = true
          
          

          你可以用特殊屬性size , 或是特殊函數(shù)size() 測試一個集合的大小。

          from Cat cat where cat.kittens.size > 0
          
          
          from Cat cat where size(cat.kittens) > 0
          
          

          對于索引了(有序)的集合,你可以使用minindex maxindex 函數(shù)來引用到最小與最大的索引序數(shù)。同理,你可以使用minelement maxelement 函數(shù)來引用到一個基本數(shù)據(jù)類型的集合中最小與最大的元素。

          from Calendar cal where maxelement(cal.holidays) > current date
          
          
          from Order order where maxindex(order.items) > 100
          
          
          from Order order where minelement(order.items) > 10000
          
          

          在傳遞一個集合的索引集或者是元素集(elements indices 函數(shù)) 或者傳遞一個子查詢的結(jié)果的時候,可以使用SQL函數(shù)any, some, all, exists, in

          select mother from Cat as mother, Cat as kit
          where kit in elements(foo.kittens)
          
          
          select p from NameList list, Person p
          where p.name = some elements(list.names)
          
          
          from Cat cat where exists elements(cat.kittens)
          
          
          from Player p where 3 > all elements(p.scores)
          
          
          from Show show where 'fizard' in indices(show.acts)
          
          

          注意,在Hibernate3種,這些結(jié)構(gòu)變量- size , elements , indices , minindex , maxindex , minelement , maxelement - 只能在where子句中使用。

          一個被索引過的(有序的)集合的元素(arrays, lists, maps)可以在其他索引中被引用(只能在where子句中):

          from Order order where order.items[0].id = 1234
          
          
          select person from Person person, Calendar calendar
          where calendar.holidays['national day'] = person.birthDay
          and person.nationality.calendar = calendar
          
          
          select item from Item item, Order order
          where order.items[ order.deliveredItemIndices[0] ] = item and order.id = 11
          
          
          select item from Item item, Order order
          where order.items[ maxindex(order.items) ] = item and order.id = 11
          
          

          [] 中的表達(dá)式甚至可以是一個算數(shù)表達(dá)式。

          select item from Item item, Order order
          where order.items[ size(order.items) - 1 ] = item
          
          

          對于一個一對多的關(guān)聯(lián)(one-to-many association)或是值的集合中的元素, HQL也提供內(nèi)建的index() 函數(shù),

          select item, index(item) from Order order
          join order.items item
          where index(item) < 5
          
          

          如果底層數(shù)據(jù)庫支持標(biāo)量的SQL函數(shù),它們也可以被使用

          from DomesticCat cat where upper(cat.name) like 'FRI%'
          
          

          如果你還不能對所有的這些深信不疑,想想下面的查詢。如果使用SQL,語句長度會增長多少,可讀性會下降多少:

          select cust
          from Product prod,
          Store store
          inner join store.customers cust
          where prod.name = 'widget'
          and store.location.name in ( 'Melbourne', 'Sydney' )
          and prod = all elements(cust.currentOrder.lineItems)
          
          

          提示: 會像如下的語句

          SELECT cust.name, cust.address, cust.phone, cust.id, cust.current_order
          FROM customers cust,
          stores store,
          locations loc,
          store_customers sc,
          product prod
          WHERE prod.name = 'widget'
          AND store.loc_id = loc.id
          AND loc.name IN ( 'Melbourne', 'Sydney' )
          AND sc.store_id = store.id
          AND sc.cust_id = cust.id
          AND prod.id = ALL(
          SELECT item.prod_id
          FROM line_items item, orders o
          WHERE item.order_id = o.id
          AND cust.current_order = o.id
          )
          
          

          9.order by子句

          查詢返回的列表(list)可以按照一個返回的類或組件(components)中的任何屬性(property)進(jìn)行排序:

          from DomesticCat cat
          order by cat.name asc, cat.weight desc, cat.birthdate
          
          

          可選的asc desc 關(guān)鍵字指明了按照升序或降序進(jìn)行排序.

          10.group by子句

          一個返回聚集值(aggregate values)的查詢可以按照一個返回的類或組件(components)中的任何屬性(property)進(jìn)行分組:

          select cat.color, sum(cat.weight), count(cat)
          from Cat cat
          group by cat.color
          
          
          select foo.id, avg(name), max(name)
          from Foo foo join foo.names name
          group by foo.id
          
          

          having 子句在這里也允許使用.

          select cat.color, sum(cat.weight), count(cat)
          from Cat cat
          group by cat.color
          having cat.color in (eg.Color.TABBY, eg.Color.BLACK)
          
          

          如果底層的數(shù)據(jù)庫支持的話(例如不能在MySQL中使用),SQL的一般函數(shù)與聚集函數(shù)也可以出現(xiàn) 在having order by 子句中。

          select cat
          from Cat cat
          join cat.kittens kitten
          group by cat
          having avg(kitten.weight) > 100
          order by count(kitten) asc, sum(kitten.weight) desc
          
          

          注意group by 子句與 order by 子句中都不能包含算術(shù)表達(dá)式(arithmetic expression_rs).

          posted on 2010-01-24 13:55 shiwf 閱讀(2074) 評論(0)  編輯  收藏 所屬分類: 1.03 hibernate

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
           
          Copyright © shiwf Powered by: 博客園 模板提供:滬江博客
          主站蜘蛛池模板: 建德市| 弥渡县| 增城市| 金沙县| 遂平县| 微山县| 台东县| 延安市| 宁津县| 凯里市| 黎城县| 宁远县| 柯坪县| 大宁县| 溧水县| 郓城县| 樟树市| 临邑县| 平原县| 柳河县| 巨野县| 舒兰市| 菏泽市| 上虞市| 平邑县| 同江市| 马边| 华池县| 秦安县| 蒲城县| 托克逊县| 广河县| 平顶山市| 根河市| 佛坪县| 长垣县| 马山县| 高碑店市| 中超| 洪江市| 商洛市|