Hibernate之HQL
1 什么是hql
HQL是Hibernate Query Language的缩写
2 hql和sql区别/异同
HQL | SQL |
---|---|
类名/属性 | 表名/列名 |
区分大小写,关键字不区分大小写 | 不区分大小写 |
别名 | 别名 |
?,从下标0开始计算位置(hibernate5之后不支持) | ?,从顺序1开始计算位置 |
:命名参数 | 不支持:命名参数 |
面向对象的查询语言 | 面向结构查询语言 |
注1:QuerySyntaxException:book is not mapped
3 hql的基本知识
1、针对查询结果集的处理
返回对象
字符串
数组
map select new map(属性)
返回是构造对象
2、命名参数
3、链表查询
4、聚合函数
count
5、分页
setFirst
setMaxResult
4 查询全部and连接查询
注2:<!-- 3. 在hibernate.cfg.xml添加实体映射文件 -->
<mapping resource="com/chz/entity/book.hbm.xml" />
<mapping resource="com/chz/entity/category.hbm.xml"/>
<mapping resource="com/chz/entity/TreeNode.hbm.xml"/>
<mapping resource="com/chz/entity/Order.hbm.xml" />
<mapping resource="com/chz/entity/OrderItem.hbm.xml"/>
创建hql测试方法类
package com.chz.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.chz.dao.BookDao;
import com.chz.entity.Book;
import com.chz.util.PageBean;
import com.chz.util.SessionFactoryUtils;
public class HqlTest {
private Session session;
private Transaction transaction;
private BookDao bookdao=new BookDao();
@Before
public void before() {
session = SessionFactoryUtils.openSession();
transaction = session.beginTransaction();
}
@After
public void after() {
transaction.commit();
session.close();
}
/**
* 返回对象(多个)
*/
@Test
public void testList1() {
Query query = session.createQuery("from Book");
List<Book> list = query.list();
for (Book b : list) {
System.out.println(b);
}
}
/**
* 返回单个列段,用字符串就可以接受
*/
@Test
public void testList2() {
Query query = session.createQuery("select b.bookName as ss from Book b");
List<String> list = query.list();
for (String b : list) {
System.out.println(b);
}
}
/**
* 查两个列段及以上,默认返回的是Object【】
*/
@Test
public void testList3() {
Query query = session.createQuery("select b.bookId,b.bookName as ss from Book b");
List<Object[]> list = query.list();
for (Object[] b : list) {
System.out.println(Arrays.toString(b));
}
}
/**
* 注意map是函数,所以不区分大小写,返回的是map集合
*/
@Test
public void testList4() {
Query query = session.createQuery("select new mAp(b.bookId,b.bookName) from Book b");
List<Map> list = query.list();
for (Map b : list) {
System.out.println(b);
}
}
/**
* 查两个列段及以上,也可返回对象,前提是有对应的构造函数
*/
@Test
public void testList5() {
Query query = session.createQuery("select new Book(b.bookId,b.bookName) from Book b");
List<Book> list = query.list();
for (Book b : list) {
System.out.println(b);
}
}
/**
* HQL语句支持占位符
*/
@Test
public void testList6() {
// Query query = session.createQuery("from Book where bookId = :bookId");
// query.setParameter("bookId", 1);
// Book b = (Book) query.getSingleResult();
// System.out.println(b);
Query query = session.createQuery("from Book where bookId in (:bookIds)");
// query.setParameterList("bookIds", new Integer[] {1,2,4});
List<Integer> params = new ArrayList<Integer>();
params.add(1);
params.add(2);
params.add(4);
query.setParameterList("bookIds", params);
List<Book> list = query.list();
for (Book b : list) {
System.out.println(b);
}
}
/**
* HQL支持连接查询
*/
@Test
public void testList7() {
Query query = session.createQuery("select o.order_no,oi.quantity from Order o,OrderItem oi where o= oi.order");
List<Object[]> list = query.list();
for (Object[] b : list) {
System.out.println(Arrays.toString(b));
}
}
/**
* HQL支持聚合函数
*/
@Test
public void testList8() {
Query query = session.createQuery("select count(*) from Book");
Long singleResult = (Long) query.getSingleResult();
System.out.println(singleResult);
}
/**
* HQL分页
*/
@Test
public void testList9() {
Query query = session.createQuery("from Book");
query.setFirstResult(2);
query.setMaxResults(3);
List<Book> list = query.list();
for (Book b : list) {
System.out.println(b);
}
}
@Test
public void testList10() {
Book book=new Book();
PageBean pageBean=new PageBean();
pageBean.setPage(2);
// book.setBookName("%杀神%");
List<Book> list=this.bookdao.list(book, pageBean);
for (Book b : list) {
System.out.println(b);
}
}
@Test
public void testList11() {
Book book=new Book();
PageBean pageBean=new PageBean();
// pageBean.setPage(2);
book.setBookName("%杀神%");
List<Book> list=this.bookdao.listPlus(book, pageBean);
for (Book b : list) {
System.out.println(b);
}
}
}
5 处理返回的结果集
4.1 单个对象
select没有逗号
4.2 Object[]
b.bookId, b.bookName
4.3 Map
new Map(b.bookId as bid, b.bookName as bname)
4.4 new 构造方法(attr1,attr2)
new Book(b.bookId, b.price)
单个列段
6 hql中使用占位符
5.1 ?占位符
从下标0开始计算位置
hibernate5之后不再支持?占位符
5.2 :命名参数
示例:
创建 BaseDao.java类
package com.chz.dao;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.query.Query;
import com.chz.util.PageBean;
public class BaseDao {
/**
*
* @param query 里面包含了带有命名参数的hql语句,需要等待赋值
*
* @param paramMap
*/
public void setParam(Query query,Map<String,Object> paramMap) {
if(paramMap!=null && paramMap.size()>0) {
Set<Entry<String,Object>> entrySet=paramMap.entrySet();
for (Entry<String, Object> entry : entrySet) {
String key=entry.getKey();
Object value=entry.getValue();
if(value instanceof Object[]) {
// value可能是数组
query.setParameterList("bookIds",(Object[])value);
}else if(value instanceof Collection) {
// value可能是集合
query.setParameterList("bookIds", (Collection)value);
}else {
query.setParameter(key, value);
}
}
}
}
/**
* 拼装符合条件的总记录数
* @param hql
*/
public String getCountHql(String hql) {
int fromIndex=hql.toUpperCase().indexOf("FROM");
return "select count(*)"+hql.substring(fromIndex);
}
/**
*
* @param hql
* @param pageBean
* @param paMap
* @param session
* @return
*/
public List executeQuery(String hql,PageBean pageBean,Map<String,Object> paMap,Session session) {
Query query=null;
List list=null;
if(pageBean!=null && pageBean.isPagination()) {
// 1,首先要查询出符合条件的总记录数
String countHql=getCountHql(hql);
Query CountQuery=session.createQuery(countHql);
this.setParam(CountQuery, paMap);
pageBean.setTotal(CountQuery.getSingleResult().toString());
// 2,返回符合条件的记录
query=session.createQuery(hql);
this.setParam(query, paMap);
query.setFirstResult(pageBean.getStartIndex());
query.setMaxResults(pageBean.getRows());
list=query.list();
}else {
query=session.createQuery(hql);
this.setParam(query, paMap);
list =query.list();
}
return list;
}
}
7 创建BookDao.java方法类
package com.chz.dao;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import com.chz.entity.Book;
import com.chz.entity.Category;
import com.chz.util.PageBean;
import com.chz.util.SessionFactoryUtils;
import com.chz.util.StringUtils;
public class BookDao extends BaseDao{
public Integer addBook(Book book) {
Session session = SessionFactoryUtils.openSession();
Transaction transaction = session.beginTransaction();
Integer bid = (Integer) session.save(book);
transaction.commit();
session.close();
return bid;
}
public Integer addCategory(Category category) {
Session session = SessionFactoryUtils.openSession();
Transaction transaction = session.beginTransaction();
Integer cid = (Integer) session.save(category);
transaction.commit();
session.close();
return cid;
}
public Category getCategory(Category category) {
Session session = SessionFactoryUtils.openSession();
Transaction transaction = session.beginTransaction();
Category c = session.get(Category.class, category.getCategoryId());
transaction.commit();
session.close();
return c;
}
public Book getBook(Book book) {
Session session = SessionFactoryUtils.openSession();
Transaction transaction = session.beginTransaction();
Book b = session.get(Book.class, book.getBookId());
if (b != null && new Integer(1).equals(book.getInitCategories())) {
Hibernate.initialize(b.getCategories());
}
transaction.commit();
session.close();
return b;
}
public void delBook(Book book) {
Session session = SessionFactoryUtils.openSession();
Transaction transaction = session.beginTransaction();
session.delete(book);
transaction.commit();
session.close();
}
public void delCategory(Category category) {
Session session = SessionFactoryUtils.openSession();
Transaction transaction = session.beginTransaction();
Category c = session.get(Category.class, category.getCategoryId());
if(c!=null) {
for (Book b : c.getBooks()) {
// 通过在被控方通过主控方来解除关联关系,最后被控方再做删除
b.getCategories().remove(c);
}
}
session.delete(c);
transaction.commit();
session.close();
}
/**
* 书籍的分页查询
* 1,动态的拼接hql语句
* 2,需要给拼接的hql语句的命名参数赋值(可以)
* @param book
* @param pageBean
* @return
*/
public List<Book> list(Book book,PageBean pageBean){
Session session=SessionFactoryUtils.openSession();
// Transaction transaction=session.beginTransaction();
String hql=" from Book where 1=1";
String bname=book.getBookName();
if(StringUtils.isNotBlank(bname)) {
hql+="and bookName like :bookName";
}
Query query=session.createQuery(hql);
if(StringUtils.isNotBlank(bname)) {
query.setParameter("bookName", bname);
}
if(pageBean!=null && pageBean.isPagination()) {
query.setFirstResult(pageBean.getStartIndex());
query.setMaxResults(pageBean.getRows());
}
List list=query.list();
// transaction.commit();
session.close();
return list;
}
/**
* 基于hql的baseDao的plus版本
* @param book
* @param pageBean
* @return
*/
public List<Book> listPlus(Book book,PageBean pageBean){
Session session=SessionFactoryUtils.openSession();
String hql=" from Book where 1=1";
String bname=book.getBookName();
Map<String,Object> map=new HashMap<String, Object>();
if(StringUtils.isNotBlank(bname)) {
hql+="and bookName like :bookName";
map.put("bookName",bname);
}
Query query=session.createQuery(hql);
List list=super.executeQuery(hql, pageBean, map, session);
// session.close();
return list;
}
}
8 创建测试方法HqlTest.java类
package com.chz.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.chz.dao.BookDao;
import com.chz.entity.Book;
import com.chz.util.PageBean;
import com.chz.util.SessionFactoryUtils;
public class HqlTest {
private Session session;
private Transaction transaction;
private BookDao bookdao=new BookDao();
@Before
public void before() {
session = SessionFactoryUtils.openSession();
transaction = session.beginTransaction();
}
@After
public void after() {
transaction.commit();
session.close();
}
/**
* 返回对象(多个)
*/
@Test
public void testList1() {
Query query = session.createQuery("from Book");
List<Book> list = query.list();
for (Book b : list) {
System.out.println(b);
}
}
/**
* 返回单个列段,用字符串就可以接受
*/
@Test
public void testList2() {
Query query = session.createQuery("select b.bookName as ss from Book b");
List<String> list = query.list();
for (String b : list) {
System.out.println(b);
}
}
/**
* 查两个列段及以上,默认返回的是Object【】
*/
@Test
public void testList3() {
Query query = session.createQuery("select b.bookId,b.bookName as ss from Book b");
List<Object[]> list = query.list();
for (Object[] b : list) {
System.out.println(Arrays.toString(b));
}
}
/**
* 注意map是函数,所以不区分大小写,返回的是map集合
*/
@Test
public void testList4() {
Query query = session.createQuery("select new mAp(b.bookId,b.bookName) from Book b");
List<Map> list = query.list();
for (Map b : list) {
System.out.println(b);
}
}
/**
* 查两个列段及以上,也可返回对象,前提是有对应的构造函数
*/
@Test
public void testList5() {
Query query = session.createQuery("select new Book(b.bookId,b.bookName) from Book b");
List<Book> list = query.list();
for (Book b : list) {
System.out.println(b);
}
}
/**
* HQL语句支持占位符
*/
@Test
public void testList6() {
// Query query = session.createQuery("from Book where bookId = :bookId");
// query.setParameter("bookId", 1);
// Book b = (Book) query.getSingleResult();
// System.out.println(b);
Query query = session.createQuery("from Book where bookId in (:bookIds)");
// query.setParameterList("bookIds", new Integer[] {1,2,4});
List<Integer> params = new ArrayList<Integer>();
params.add(1);
params.add(2);
params.add(4);
query.setParameterList("bookIds", params);
List<Book> list = query.list();
for (Book b : list) {
System.out.println(b);
}
}
/**
* HQL支持连接查询
*/
@Test
public void testList7() {
Query query = session.createQuery("select o.order_no,oi.quantity from Order o,OrderItem oi where o= oi.order");
List<Object[]> list = query.list();
for (Object[] b : list) {
System.out.println(Arrays.toString(b));
}
}
/**
* HQL支持聚合函数
*/
@Test
public void testList8() {
Query query = session.createQuery("select count(*) from Book");
Long singleResult = (Long) query.getSingleResult();
System.out.println(singleResult);
}
/**
* HQL分页
*/
@Test
public void testList9() {
Query query = session.createQuery("from Book");
query.setFirstResult(2);
query.setMaxResults(3);
List<Book> list = query.list();
for (Book b : list) {
System.out.println(b);
}
}
@Test
public void testList10() {
Book book=new Book();
PageBean pageBean=new PageBean();
pageBean.setPage(2);
// book.setBookName("%杀神%");
List<Book> list=this.bookdao.list(book, pageBean);
for (Book b : list) {
System.out.println(b);
}
}
@Test
public void testList11() {
Book book=new Book();
PageBean pageBean=new PageBean();
// pageBean.setPage(2);
book.setBookName("%杀神%");
List<Book> list=this.bookdao.listPlus(book, pageBean);
for (Book b : list) {
System.out.println(b);
}
}
}
9 测试结果
testList1测试结果
Hibernate:
select
book0_.book_id as book_id1_0_,
book0_.book_name as book_nam2_0_,
book0_.price as price3_0_
from
t_hibernate_book book0_
Book [bookId=1, bookName=西游记, price=50.0]
Book [bookId=2, bookName=红楼梦, price=50.0]
Book [bookId=7, bookName=杀神2, price=34.0]
Book [bookId=8, bookName=圣墟, price=66.0]
Book [bookId=9, bookName=圣墟2, price=66.0]
Book [bookId=12, bookName=不死不灭, price=45.0]
Book [bookId=13, bookName=我是至尊, price=66.0]
Book [bookId=15, bookName=灵域, price=88.0]
Book [bookId=16, bookName=灵域2, price=88.0]
Book [bookId=17, bookName=b, price=10.0]
Book [bookId=18, bookName=c, price=10.0]
Book [bookId=19, bookName=b, price=10.0]
Book [bookId=20, bookName=b, price=10.0]
Book [bookId=21, bookName=c, price=10.0]
Book [bookId=22, bookName=斗气化马, price=10.0]
Book [bookId=23, bookName=斗宗强者恐怖如斯, price=10.0]
Book [bookId=24, bookName=T226自传, price=10.0]
Book [bookId=25, bookName=T226c, price=10.0]
Book [bookId=26, bookName=b, price=10.0]
Book [bookId=27, bookName=c, price=10.0]
注:返回对象(多个)
testList2测试结果
Hibernate:
select
book0_.book_name as col_0_0_
from
t_hibernate_book book0_
西游记
红楼梦
杀神2
圣墟
圣墟2
不死不灭
我是至尊
灵域
灵域2
b
c
b
b
c
斗气化马
斗宗强者恐怖如斯
T226自传
T226c
b
c
注:返回单个列段,用字符串就可以接受
testList3测试结果
Hibernate:
select
book0_.book_id as col_0_0_,
book0_.book_name as col_1_0_
from
t_hibernate_book book0_
[1, 西游记]
[2, 红楼梦]
[7, 杀神2]
[8, 圣墟]
[9, 圣墟2]
[12, 不死不灭]
[13, 我是至尊]
[15, 灵域]
[16, 灵域2]
[17, b]
[18, c]
[19, b]
[20, b]
[21, c]
[22, 斗气化马]
[23, 斗宗强者恐怖如斯]
[24, T226自传]
[25, T226c]
[26, b]
[27, c]
====
注:查两个列段及以上,默认返回的是Object【】
testList4测试结果
Hibernate:
select
book0_.book_id as col_0_0_,
book0_.book_name as col_1_0_
from
t_hibernate_book book0_
{0=1, 1=西游记}
{0=2, 1=红楼梦}
{0=7, 1=杀神2}
{0=8, 1=圣墟}
{0=9, 1=圣墟2}
{0=12, 1=不死不灭}
{0=13, 1=我是至尊}
{0=15, 1=灵域}
{0=16, 1=灵域2}
{0=17, 1=b}
{0=18, 1=c}
{0=19, 1=b}
{0=20, 1=b}
{0=21, 1=c}
{0=22, 1=斗气化马}
{0=23, 1=斗宗强者恐怖如斯}
{0=24, 1=T226自传}
{0=25, 1=T226c}
{0=26, 1=b}
{0=27, 1=c}
注:注意map是函数,所以不区分大小写,返回的是map集合
testList5测试结果
两个参数的构造函数
Hibernate:
select
book0_.book_id as col_0_0_,
book0_.book_name as col_1_0_
from
t_hibernate_book book0_
Book [bookId=1, bookName=西游记, price=null]
Book [bookId=2, bookName=红楼梦, price=null]
Book [bookId=7, bookName=杀神2, price=null]
Book [bookId=8, bookName=圣墟, price=null]
Book [bookId=9, bookName=圣墟2, price=null]
Book [bookId=12, bookName=不死不灭, price=null]
Book [bookId=13, bookName=我是至尊, price=null]
Book [bookId=15, bookName=灵域, price=null]
Book [bookId=16, bookName=灵域2, price=null]
Book [bookId=17, bookName=b, price=null]
Book [bookId=18, bookName=c, price=null]
Book [bookId=19, bookName=b, price=null]
Book [bookId=20, bookName=b, price=null]
Book [bookId=21, bookName=c, price=null]
Book [bookId=22, bookName=斗气化马, price=null]
Book [bookId=23, bookName=斗宗强者恐怖如斯, price=null]
Book [bookId=24, bookName=T226自传, price=null]
Book [bookId=25, bookName=T226c, price=null]
Book [bookId=26, bookName=b, price=null]
Book [bookId=27, bookName=c, price=null]
注:查两个列段及以上,也可返回对象,前提是有对应的构造函数
三个参数的构造函数
Hibernate:
select
book0_.book_id as col_0_0_,
book0_.book_name as col_1_0_,
book0_.price as col_2_0_
from
t_hibernate_book book0_
Book [bookId=1, bookName=西游记, price=50.0]
Book [bookId=2, bookName=红楼梦, price=50.0]
Book [bookId=7, bookName=杀神2, price=34.0]
Book [bookId=8, bookName=圣墟, price=66.0]
Book [bookId=9, bookName=圣墟2, price=66.0]
Book [bookId=12, bookName=不死不灭, price=45.0]
Book [bookId=13, bookName=我是至尊, price=66.0]
Book [bookId=15, bookName=灵域, price=88.0]
Book [bookId=16, bookName=灵域2, price=88.0]
Book [bookId=17, bookName=b, price=10.0]
Book [bookId=18, bookName=c, price=10.0]
Book [bookId=19, bookName=b, price=10.0]
Book [bookId=20, bookName=b, price=10.0]
Book [bookId=21, bookName=c, price=10.0]
Book [bookId=22, bookName=斗气化马, price=10.0]
Book [bookId=23, bookName=斗宗强者恐怖如斯, price=10.0]
Book [bookId=24, bookName=T226自传, price=10.0]
Book [bookId=25, bookName=T226c, price=10.0]
Book [bookId=26, bookName=b, price=10.0]
Book [bookId=27, bookName=c, price=10.0]
testList6测试结果
Hibernate:
select
book0_.book_id as book_id1_0_,
book0_.book_name as book_nam2_0_,
book0_.price as price3_0_
from
t_hibernate_book book0_
where
book0_.book_id in (
? , ? , ?
)
Book [bookId=1, bookName=西游记, price=50.0]
Book [bookId=2, bookName=红楼梦, price=50.0]
注:HQL语句支持占位符
testList7测试结果
HQL支持连接查询
Hibernate:
select
order0_.order_no as col_0_0_,
orderitem1_.quantity as col_1_0_
from
t_hibernate_order order0_ cross
join
t_hibernate_order_item orderitem1_
where
order0_.order_id=orderitem1_.oid
[P7, 11]
[P7, 11]
[P7, 11]
[P7, 11]
[P7, 11]
[P7, 11]
[P7, 78]
[P7, 56]
[P101, 20]
[P101, 21]
[P101, 22]
[P101, 23]
[P101, 24]
[P101, 25]
[P20, 20]
[P20, 21]
[P20, 22]
[P20, 23]
[P20, 24]
[P20, 25]
[T226, 20]
[T226, 21]
[T226, 22
testList8测试结果
== HQL支持聚合函数==
Hibernate:
select
count(*) as col_0_0_
from
t_hibernate_book book0_
20
testList9测试结果
HQL分页
Hibernate:
select
book0_.book_id as book_id1_0_,
book0_.book_name as book_nam2_0_,
book0_.price as price3_0_
from
t_hibernate_book book0_ limit ?,
?
Book [bookId=7, bookName=杀神2, price=34.0]
Book [bookId=8, bookName=圣墟, price=66.0]
Book [bookId=9, bookName=圣墟2, price=66.0]
testList10测试结果
HQL模糊查询,分页查询
Hibernate:
select
book0_.book_id as book_id1_0_,
book0_.book_name as book_nam2_0_,
book0_.price as price3_0_
from
t_hibernate_book book0_
where
1=1 limit ?, ?
Book [bookId=8, bookName=圣墟, price=66.0]
Book [bookId=9, bookName=圣墟2, price=66.0]
Book [bookId=12, bookName=不死不灭, price=45.0]
testList11测试结果
Hibernate:
select
count(*) as col_0_0_
from
t_hibernate_book book0_
where
1=1
and (
book0_.book_name like ?
)
Hibernate:
select
book0_.book_id as book_id1_0_,
book0_.book_name as book_nam2_0_,
book0_.price as price3_0_
from
t_hibernate_book book0_
where
1=1
and (
book0_.book_name like ?
) limit ?
Book [bookId=7, bookName=杀神2, price=34.0]
注: 基于hql的继承baseDao的模糊查询