首页 > 代码库 > Hibernate之HQL检索(查询)方式
Hibernate之HQL检索(查询)方式
HQL(Hibernate Query Language)是面向对象的查询语言,与SQL非常相似。在Hibernate中,HQL是使用最广泛的检索方式。
具有下面经常使用功能:
(1)在查询语句中,能够设定各种条件
(2)支持检出对象的部分属性,就是SQL语句中不用*,而是查询我们想查询的对象
(3)支持连接查询
(4)支持分页查询
(5)支持子查询
(6)支持动态绑定參数
(7)支持分组查询,能够用having,group by
(8)提供分组函数(内置聚集函数,sum(),count(),avg(),max(),min(),g)
(9)能够调用自己定义SQL函数
Session的find()方法和Query接口都支持HQL检索方式,特别注意,在Hibernate3就取消了find()方法,find()方法不具备动态绑定參数的功能,
检索与查询是一个意思,在面向对象中检索说得多,在sql中查询说得多。依据习惯去理解即可。
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.创建Query对象 Query query = session.createQuery("from Customer where name=:v_name");//别习惯性的加上select //2.动态绑定參数 query.setString("v_name", "test"); //3.运行SQL返回查询结果 List list = query.list(); //4.输出结果 for (int i=0;i<list.size();i++) { Customer customer = (Customer) list.get(i); System.out.println(customer.getName()); } //5.事务提交 tr.commit(); //6.关闭session session.close(); } }运行结果:
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=?实例分析Query接口支持的HQL查询方式的运行步骤:test
(1)创建一个Query对象。对象里面包括查询SQL。SQL中包括命名參数v_name.
(2)动态绑定參数。依据Query接口提供的參数命名方法,设置HQL的參数。比方,query.setString("v_name", "test");
(3)运行查询语句。返回list集合,集合中存放符合条件的持久化对象。
比如。当调用query.list()时,运行sql,返回customer持久化对象的集合。
(4)支持链式变成风格。就是将可连接代码连接在一起,做到简洁,明了。比如:
将上面代码查询部分整合例如以下:
List list = session.createQuery("from Customer c where name=:v_name") .setString("v_name", "test") .list();运行查询效果一样。
Hibernate之HQL检索(查询)方式