HQL語法大全[ 收藏 ]

<script type="text/javascript"> document.body.oncopy = function() { if (window.clipboardData) { setTimeout(function() { var text = clipboardData.getData("text"); if (text && text.length>300) { text = text + "/r/n/n本文來自CSDN博客,轉載請標明出處:" + location.href; clipboardData.setData("text", text); } }, 100); } } </script> <script type="text/javascript">function StorePage(){d=document;t=d.selection?(d.selection.type!='None'?d.selection.createRange().text:''):(d.getSelection?d.getSelection():'');void(keyit=window.open('http://www.365key.com/storeit.aspx?t='+escape(d.title)+'&u='+escape(d.location.href)+'&c='+escape(t),'keyit','scrollbars=no,width=475,height=575,left=75,top=20,status=no,resizable=yes'));keyit.focus();}</script>

HQL:Hibernate Query Language
HQL是完全面向對象的查詢語言,因此可以支持繼承和多態等特徵。
HQL查詢依賴於Query類,每個Query實例對應一個查詢對象,使用HQL查詢按
如下步驟進行:
(1)獲取Hibernate Session對象;
(2)編寫HQL語句;
(3)以HQL語句作爲參數,調用Session的createQuery方法創建查詢對象;
(4)如果HQL語句包含參數,調用Query的setXxx方法爲參數賦值;
(5)調用Query對象的list等方法遍歷查詢結果。
查詢示例:
public class HqlQuery
...{
    public static void main(String[] args) throws Exception ...{
        HqlQuery mgr = new HqlQuery();
        //調用查詢方法
        mgr.findPersons();
        //調用第二個查詢方法
        mgr.findPersonByHappenDate();
        HibernateUtil.sessionFactory.close();
    }
    //第一個查詢方法
    private void findPersons() ...{
        //獲得Hibernate Session
        Session sess = HibernateUtil.currentSession();
        //開始事務
        Transaction tx = sess.beginTransaction();
        //以HQL語句創建Query對象
        //執行setString方法爲HQL語句的參數賦值
        //Query調用list方法訪問查詢的全部實例
        List p1 = sess.createQuery("from Person p where o.myEvents.title = :
            eventTitle").setString("eventTitle", "很普通事情").list();
        //遍歷查詢的全部結果
        for (Iterator pit = p1.iterator(); pit.haxNext(); )
        ...{
            Person p = (Person)pit.next();
            System.out.println(p.getName());
        }
        //提交事務
        tx.commit();
        HibernateUtil.closeSession();
    }
    //第二個查詢方法
    private void findPersonByHappenDate() throws Exception ...{
        Session sess = HibernateUtil.currentSession();
        Transaction tx = sess.beginTransaction();
        //解析出Date對象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date start = sdf.parse("2007-11-27");
        System.out.println("系統開始通過日期查找人" + start);
        //通過Session的createQuery方法創建Query對象
        //設置參數
        //返回結果集
        List pl = sess.createQuery(
            "from Person p where p.myEvents.happenDate between :firstDate
            and :endDate")
                        .setDate("firstDate", start)
                        .setDate("endDate", new Date())
                        .list();
        //遍歷結果集
        for (Iterator pit = pl.iterator(); pit.hasNext(); )
        ...{
            Person p = (Person)pit.next();
            System.out.println(p.getName());
        }
        tx.commit();
        HibernateUtil.closeSession();
    }
}

$下面介紹HQL語句的語法
1.from子句
from Person
表明從Person持久化類中選出全部的實例。
推薦:from Person as p

2.select子句
select p.name from Person as p
select p.name.firstName from Person as p
select new list(p.name, p.address) from Person as p
select new ClassTest(p.name, p.address) from Person as p (有前提)
select p.name as personName from Person as p
select new map(p.name as personName) from Person as p (與new map()結合更普遍)

3.聚集函數
avg,count,max,min,sum
select count(*) from Person
select max(p.age) from Person as p
select p.name || "" || p.address from Person as p

4.多態查詢
from Person as p
from java.lang.Object o
from Named as n

5.where子句
from Person where name like "tom%"
from Person as p where p.name like "tom%"
from Cat cat where cat.mate.name like "kit%"
    select * from cat_table as table1 cat_table as table2 where table1.mate =
    table2.id and table1.name like "kit%"
from Foo foo where foo.bar.baz.customer.address.city like "fuzhou%"
from Cat cat, Cat rival where cat.mate = rival.mate
select cat, mate
from Cat cat, Cat mate
where cat.mate = mate
from Cat as cat where cat.id = 123
from Cat as cat where cat.mate.id = 69
from Person as person
where person.id.country = ''AU''
    and person.id.medicareNumber = 123456
from Account as account
where account.owner.id.country = ''AU''
    and account.owner.id.medicareNumber = 123456
from Cat cat where cat.class = DomesticCat
from Account as a where a.person.name.firstName like "dd%" // 正確
from Account as a where a.person.name like "dd%" // 錯誤

6.表達式
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'')
from DomesticCat cat where cat.name is null
from Person as p where p.address is not null
<property name="hibernate.query.substitutions">true 1, false 0</property>
from Cat cat where cat.alive = true
from Cat cat where cat.kittens.size > 0
from Cat cat where size(cat.kittens) > 0
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
//操作集合元素
select mother from Cat as mother, Cat as kit
where kit in elements(foo.kittens)
//p的name屬性等於集合中某個元素的name屬性
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)
//items是有序集合屬性,items[0]代表第一個元素
from Order order where order.items[0].id = 1234
//holidays是map集合屬性,holidays[national day]是代表其中第一個元素
select person from Person person, Calendar calendar
where calendar.holidays[''national day''] = person.birthDay
    and person.nationality.calendar = calendar
//下面同時使用list集合和map集合屬性
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

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

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
    )

7.order by子句
from Person as p
order by p.name, p.age
from Person as p
order by p.name asc, p.age desc

8.group by子句
select cat.color, sum(cat.weight), count(cat)
from Cat cat
group by cat.color
//select後出現的id處出現在group by之後,而name屬性則出現在聚集函數中
select foo.id, avg(name), max(name)
from Foo foo join foo.names name
group by foo.id

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)

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

9.子查詢
from Cat as fatcat
where fatcat.weight > (select avg(cat.weight) from DomesticCat cat)

from Cat as cat
where not (cat.name, cat.color) in (
    select cat.name, cat.color from DomesticCat cat
)

10.fetch關鍵字
from Person as p join p.scores

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

11.命名查詢
<!--定義命名查詢-->
<query name="myNamedQuery">
    <!--此處確定命名查詢的HQL語句-->
    from Person as p where p.age > ?
</query>

調用命名查詢的示例代碼如下:
private void findByNamedQuery() throws Exception ...{
    Session session = HibernateUtil.currentSession();
    Transaction tx = session.beginTransaction();
    System.out.println("執行命名查詢");
    //調用命名查詢
    List pl = sess.getNamedQuery("myNamedQuery")
                                    //爲參數賦值
                                    .setInteger(0, 20)
                                    //返回全部結果
                                    .list();
    //遍歷結果集
    for (Integer pit = pl.iterator(); pit.hasNext(); )
    ...{
        Person p = (Person)pit.next();
        System.out.println(p.getName());
    }
    tx.commit();
    HibernateUtil.closeSession();
}

 

來源:http://blog.csdn.net/yangdan777/archive/2009/05/30/4225994.aspx


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章