hibernate(5)之hql

1. 什么是hql

HQL是Hibernate Query Language的缩写

2. hql和sql区别/异同

hql sql
类名/属性 表名/列名
区分大小写,关键字不区分大小写 不区分大小写
别名 别名
?,从下标0开始计算位置(hibernate5之后不支持,安全性考虑) ?,从顺序1开始计算位置
:命名参数 不支持:命名参数
面向对象的查询语言 面向结构查询语言

3. hql的基本功能演示和通用分页:

package com.swx.five.test;

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.swx.four.entity.Book;
import com.swx.two.util.SessionFactoryUtils;


public class HqlTest {
	private Session session;
	private Transaction transaction;
	
	@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 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 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 list = query.list();
		for (Object[] b : list) {
			System.out.println(Arrays.toString(b));
		}
	}
	/**
	 * 查询结果
	 * [1, 西游记]
[2, 红楼梦]
[7, 杀神2]
[8, 圣墟]
[9, 圣墟2]
[12, 不死不灭]
[13, 我是至尊]
	 */
	
	
	
	/**
	 * 注意map是函数,所以不区分大小写,返回的是map集合
	 */
	@Test
	public void testList4() {
		Query query = session.createQuery("select new mAp(b.bookId,b.bookName) from Book b");
		List list = query.list();
		for (Map b : list) {
			System.out.println(b);
		}
	}
	/**
	 * 查询结果
	 * {0=1, 1=西游记}
{0=2, 1=红楼梦}
{0=7, 1=杀神2}
{0=8, 1=圣墟}
{0=9, 1=圣墟2}
{0=12, 1=不死不灭}
{0=13, 1=我是至尊}
	 */
	
	/**
	 * 查两个列段及以上,也可返回对象,前提是有对应的构造函数(在实体类中写构造函数)
	 */
	@Test
	public void testList5() {
		Query query = session.createQuery("select new Book(b.bookId,b.bookName) from Book b");
		List list = query.list();
		for (Book b : list) {
			System.out.println(b);
		}
	}
	/**
	 * 查询结果
	 * 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]
	 */
	
	/**
	 * 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 params = new ArrayList();
//		params.add(1);
//		params.add(2);
//		params.add(4);
//		query.setParameterList("bookIds", params);
		List list = query.list();
		for (Book b : list) {
			System.out.println(b);
		}
	}
	/**
	 * 查询结果:
	 * Book [bookId=1, bookName=西游记, price=50.0]
		Book [bookId=2, bookName=红楼梦, price=50.0]
	 * 
	 */
	
	/**
	 * HQL支持连接查询
	 */
	@Test
	public void testList7() {                                         //o.orderId = oi.order.orderId → o = oi.order
		Query query = session.createQuery("select o.orderNo,oi.quantity from Order o,OrderItem oi where o = oi.order");
		List list = query.list();
		for (Object[] b : list) {
			System.out.println(Arrays.toString(b));
		}
	}
	
	/**
	 * HQL支持聚合函数 sum、avg、count
	 */
	@Test
	public void testList8() {
		Query query = session.createQuery("select count(*) from Book");
		Long singleResult = (Long) query.getSingleResult();
		System.out.println(singleResult);//21
	}
	
	/**
	 * HQL分页
	 */
	@Test
	public void testList9() {
		Query query = session.createQuery("from Book");
		query.setFirstResult(0);//设置起始下标 
		query.setMaxResults(3);//设置查询数量
		List list = query.list();
		for (Book b : list) {
			System.out.println(b);
		}
	}
		/**
	 * Book [bookId=1, bookName=西游记, price=50.0]
Book [bookId=2, bookName=红楼梦, price=50.0]
Book [bookId=7, bookName=杀神2, price=34.0]

	 */
}

hql通用分页1.0

bookdao:

	/**
	 * hql通用分页写法1.0
	 * 步骤:
	 *    1、动态拼接hql语句
	 *    2、需要给拼接的hql语句的命名参数赋值(可以简化)
	 *    3、分页(可以简化)
	 */
	public List list(Book book,PageBean pageBean){
		Session session = SessionFactoryUtils.openSession();
		
		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();
		session.close();
		return list;
	}

测试:

/**
	 * 测试hql通用分页 1.0
	 */
	@Test
	public void testList10() {
		Book book = new Book();
		PageBean pageBean = new PageBean();
//		pageBean.setRows(10);//设置每页显示数据行数
		book.setBookName("%圣墟%");//带条件查询
		List list = this.bookDao.list(book, pageBean);
		for (Book b : list) {
			System.out.println(b);
		}
	}

结果:
Book [bookId=8, bookName=圣墟, price=66.0]
Book [bookId=9, bookName=圣墟2, price=66.0]

hql2.0基于basedao的升级版

basedao:

package com.swx.five.util;

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;


/**
 * 基于hql语句的通用查询工具类
 * 1、需要给拼接的hql语句的命名参数赋值(可以简化)
 *    2、分页(可以简化)
 *    
 *    
 *    基于sql的分页查询做法;
 *    	1、首先要查询出符合条件的总记录数
 *    	2、返回符合条件的记录
 *    	
 *    参数:sql 、 pagebean、 Class对象
 *    sql = select * from 表名 where 查询列 like "%参数%"
 *   1、 countSql = select count(*) from (sql) t;
 *   2、 pageSql = sql + " limit "+start+","+rows
 *   
 *   基于hql的分页查询做法:
 *   hql = from Book where bookName like "%圣墟%"
 *   hql = select * from Book where bookName like "%圣墟%"
 *   截取hql
 *   	1、 countHql = select count(*)  hql
 *   
 * @author 10570
 *
 */
public class BaseDao {
	/**
	 * 
	 * @param query 里面包含了带有命名参数的hql语句,需要等待赋值
	 * 			from Book where 1=1 and bookName like :bookName
	 * @param paramMap
	 * 		= request.getParameterMap();
	 */
	public void setParam(Query query,Map paramMap) {
		if(paramMap != null && paramMap.size()>0) {
			Set> entrySet = paramMap.entrySet();
			for (Entry entry : entrySet) {
				String key = entry.getKey();//拿到命名参数
				Object value = entry.getValue();//拿到对应的值
				
				if(value instanceof Object[]) {//如果是数组的话
					
					query.setParameterList(key, (Object[])value);
					
				}else if(value instanceof Collection) {//如果是集合的话
					
					query.setParameterList(key, (Collection) value);
					
				}else {
					query.setParameter(key, value);
				}
			}
		}
	}
	/**
	 * 拼装符合条件的总记录数
	 * @param hql
	 * @return
	 */
	public String getCountHql(String hql) {
		/**
		 * 		hql = from Book where bookName like "%圣墟%"
		 *      hql = select * from Book where bookName like "%圣墟%"
		 *      将这两种hql语句进行截取
		 */
		int fromIndex = hql.toUpperCase().indexOf("FROM");//全都变成大写然后再进行截取
		
		return "select count(*) "+hql.substring(fromIndex);
	}
	/**
	 * 基于hql的通用查询方法
	 * @param hql
	 * @param pageBean
	 * @param paMap
	 * @param session
	 * @return
	 */
	public List executeQuery(String hql,PageBean pageBean ,Map paMap,Session session) {
		Query query = null;
		List list = null;
		
		if(pageBean !=null && pageBean.isPagination()) {//分页是否为空 && 是否分页
			//1.首先要查询出符合条件的总记录数
			String countHql = getCountHql(hql);
			Query createQuery = session.createQuery(countHql);
			this.setParam(createQuery, paMap);
			pageBean.setTotal(createQuery.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;
		
	}
}

bookdao继承basedao:

	/**
	 * hql通用分页写法2.0
	 * 步骤:
	 *    1、动态拼接hql语句
	 *    2、需要给拼接的hql语句的命名参数赋值(可以简化)
	 *    3、分页(可以简化)
	 */
	public List listPlus(Book book,PageBean pageBean){
		Session session = SessionFactoryUtils.openSession();
		
		String hql = "from Book where 1=1";
		String bname = book.getBookName();
		//map由jsp自动传递过来,不需要手动写
		Map map = new  HashMap();
		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;
	}

测试:

/**
	 * 测试hql通用分页 2.0
	 * 基于basedao的升级版
	 */
	@Test
	public void testList11() {
		Book book = new Book();
		PageBean pageBean = new PageBean();
//		pageBean.setRows(10);//设置每页显示数据行数
		book.setBookName("%希灵%");//带条件查询
		List list = this.bookDao.listPlus(book, pageBean);
		for (Book b : list) {
			System.out.println(b);
		}
	}
}

结果:
Book [bookId=26, bookName=swx希灵帝国, price=10.0]

你可能感兴趣的:(hibernate)