Hibernate之HQL检索(查询)方式
HQL(Hibernate Query Language)是面向?qū)ο蟮牟樵冋Z言,與SQL非常相似。在Hibernate中,HQL是使用最廣泛的檢索方式。
具有下面經(jīng)常使用功能:
(1)在查詢語句中,能夠設(shè)定各種條件
(2)支持檢出對象的部分屬性,就是SQL語句中不用*,而是查詢我們想查詢的對象
(3)支持連接查詢
(4)支持分頁查詢
(5)支持子查詢
(6)支持動態(tài)綁定參數(shù)
(7)支持分組查詢,能夠用having,group by
(8)提供分組函數(shù)(內(nèi)置聚集函數(shù),sum(),count(),avg(),max(),min(),g)
(9)能夠調(diào)用自己定義SQL函數(shù)
Session的find()方法和Query接口都支持HQL檢索方式,特別注意,在Hibernate3就取消了find()方法,find()方法不具備動態(tài)綁定參數(shù)的功能,
檢索與查詢是一個意思,在面向?qū)ο笾袡z索說得多,在sql中查詢說得多。依據(jù)習慣去理解即可。
Query接口是真正的HQL查詢方式的接口,懂它就夠。
讓我們先看個實例:
package com.lanhuigu.hibernate.test;import java.util.List;import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration;import com.lanhuigu.hibernate.entity.Customer;public class TestHibernateJianSuo {public static void main(String[] args){Configuration cfg = new Configuration().configure();SessionFactory sessionFactory = cfg.buildSessionFactory();Session session = sessionFactory.openSession();Transaction tr = session.beginTransaction();//1.創(chuàng)建Query對象Query query = session.createQuery("from Customer where name=:v_name");//別習慣性的加上select//2.動態(tài)綁定參數(shù)query.setString("v_name", "test");//3.運行SQL返回查詢結(jié)果List list = query.list();//4.輸出結(jié)果for (int i=0;i<list.size();i++) {Customer customer = (Customer) list.get(i);System.out.println(customer.getName());}//5.事務(wù)提交tr.commit();//6.關(guān)閉sessionsession.close();} } 運行結(jié)果: Hibernate: select customer0_.ID as ID1_0_, customer0_.NAME as NAME2_0_, customer0_.EMAIL as EMAIL3_0_, customer0_.PASSWORD as PASSWORD4_0_, customer0_.PHONE as PHONE5_0_, customer0_.ADDRESS as ADDRESS6_0_, customer0_.SEX as SEX7_0_, customer0_.IS_MARRIED as IS8_0_, customer0_.DESCRIPTION as DESCRIPT9_0_, customer0_.IMAGE as IMAGE10_0_, customer0_.BIRTHDAY as BIRTHDA11_0_, customer0_.REGISTERED_TIME as REGISTE12_0_, customer0_.HOME_PROVINCE as HOME13_0_, customer0_.HOME_CITY as HOME14_0_, customer0_.HOME_STREET as HOME15_0_, customer0_.HOME_ZIPCODE as HOME16_0_, customer0_.COMP_PROVINCE as COMP17_0_, customer0_.COMP_CITY as COMP18_0_, customer0_.COMP_STREET as COMP19_0_, customer0_.COMP_ZIPCODE as COMP20_0_ from CUSTOMERS customer0_ where customer0_.NAME=?test
實例分析Query接口支持的HQL查詢方式的運行步驟:(1)創(chuàng)建一個Query對象。對象里面包括查詢SQL。SQL中包括命名參數(shù)v_name.
(2)動態(tài)綁定參數(shù)。依據(jù)Query接口提供的參數(shù)命名方法,設(shè)置HQL的參數(shù)。比方,query.setString("v_name", "test");
(3)運行查詢語句。返回list集合,集合中存放符合條件的持久化對象。
比如。當調(diào)用query.list()時,運行sql,返回customer持久化對象的集合。
(4)支持鏈式變成風格。就是將可連接代碼連接在一起,做到簡潔,明了。比如:
?????? 將上面代碼查詢部分整合例如以下:
List list = session.createQuery("from Customer c where name=:v_name").setString("v_name", "test").list();運行查詢效果一樣。總結(jié)
以上是生活随笔為你收集整理的Hibernate之HQL检索(查询)方式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Cython进阶--用Cython封装C
- 下一篇: 6.1 解释计划