Hibernate之HQL

一:Hql语句基础

1. 什么是hql
HQL是Hibernate Query Language的缩写

2. hql和sql区别/异同

   HQL                               SQL
   类名/属性                          表名/列名
   区分大小写,关键字不区分大小写         不区分大小写
   别名                               别名	as a
   ?,从下标0开始计算位置               ?,从顺序1开始计算位置
   :命名参数                           不支持:命名参数
   面向对象的查询语言                   面向结构查询语言

3.聚合函数
sum
avg
max
min
count

案例一:HQL基本功能演示

工具类PageBean.java

package com.xwt.five.uity;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 分页工具类
 *
 */
public class PageBean {

	private int page = 1;// 页码

	private int rows = 6;// 页大小

	private int total = 0;// 总记录数

	private boolean pagination = true;// 是否分页
	// 获取前台向后台提交的所有参数
	private Map<String, String[]> parameterMap;
	// 获取上一次访问后台的url
	private String url;

	/**
	 * 初始化pagebean
	 * 
	 * @param req
	 */
	public void setRequest(HttpServletRequest req) {
		this.setPage(req.getParameter("page"));
		this.setRows(req.getParameter("rows"));
		// 只有jsp页面上填写pagination=false才是不分页
		this.setPagination(!"fasle".equals(req.getParameter("pagination")));
		this.setParameterMap(req.getParameterMap());
		this.setUrl(req.getRequestURL().toString());
	}

	public int getMaxPage() {
		return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1;
	}

	public int nextPage() {
		return this.page < this.getMaxPage() ? this.page + 1 : this.getMaxPage();
	}

	public int previousPage() {
		return this.page > 1 ? this.page - 1 : 1;
	}

	public PageBean() {
		super();
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public void setPage(String page) {
		this.page = StringUtils.isBlank(page) ? this.page : Integer.valueOf(page);
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public void setRows(String rows) {
		this.rows = StringUtils.isBlank(rows) ? this.rows : Integer.valueOf(rows);
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}

	public boolean isPagination() {
		return pagination;
	}

	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}

	public Map<String, String[]> getParameterMap() {
		return parameterMap;
	}

	public void setParameterMap(Map<String, String[]> parameterMap) {
		this.parameterMap = parameterMap;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	/**
	 * 获得起始记录的下标
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
				+ ", parameterMap=" + parameterMap + ", url=" + url + "]";
	}
}

StringUtils.java

package com.xwt.five.uity;

public class StringUtils {
	// 私有的构造方法,保护此类不能在外部实例化
	private StringUtils() {
	}

	/**
	 * 如果字符串等于null或去空格后等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isBlank(String s) {
		boolean b = false;
		if (null == s || s.trim().equals("")) {
			b = true;
		}
		return b;
	}
	
	/**
	 * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isNotBlank(String s) {
		return !isBlank(s);
	}
}

测试类HqlTest.java

package com.xwt.five.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.xwt.four.entity.Book;
import com.xwt.two.uity.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<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相当preparStatement
		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.orderNo,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(1);
		query.setMaxResults(6);
		List<Book> list = query.list();
		for (Book b : list) {
			System.out.println(b);
		}
	}
}

案例二:按名字分页查询对应书籍信息(初级版)

Dao方法BookDao.java

package com.xwt.five.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import com.xwt.five.uity.PageBean;
import com.xwt.five.uity.StringUtils;
import com.xwt.four.entity.Book;
import com.xwt.two.uity.SessionFactoryUtils;

public class BookDao {
	/**
	 * 查询带分页
	 * @param book
	 * @param pageBean
	 * @return
	 */
	public List<Book> list(Book book,PageBean pageBean){
		Session session=SessionFactoryUtils.openSession();
		/**
		 * 拼接hql语句
		 */
		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<Book> list = query.list();
		session.close();
		return list;
	}
}

测试类HqlTests.java

package com.xwt.five.test;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Test;

import com.xwt.five.dao.BookDao;
import com.xwt.five.uity.PageBean;
import com.xwt.four.entity.Book;

public class HqlTests {
	private BookDao bookDao=new BookDao();
	/**
	 * 查询和分页
	 */
	@Test
	public void testHql1() {
		Book book=new Book();
		PageBean pageBean=new PageBean();
		//pageBean.setPage(1);
		book.setBookName("%斗%");
		List<Book> list=this.bookDao.list(book, pageBean);
		for(Book b:list) {
			System.out.println(b);
		}
	}
}

在这里插入图片描述

升级版

BaseDao.java

package com.xwt.five.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.xwt.five.uity.PageBean;

/**
 * 基于hql语句的通用查询工具类
 *        1、需要给拼接的hql语句的命名参数赋值
 *        2、 分页
 *    
 *  基于hql分页的查询
 *        1、首先要查询出符合条件的总记录数
 *        2、返回符合条件的记录
 * @author wt
 *
 */
public class BaseDao {
	/**
	 * @param query  里面包含了带有命名参数的hq语句  需要等待赋值
	 * @param paMap
	 */
	public void setParam(Query query,Map<String, Object> paMap) {
		if(paMap!=null && paMap.size()>0) {
			Set<Entry<String, Object>> entrySet=paMap.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
	 * @return
	 */
	public String getCountHql(String hql) {
		int fromIndex=hql.toUpperCase().indexOf("FROM");
		return "select count(*) "+hql.substring(fromIndex);
	}

	/**
	 * 基于hql的通用查询方法
	 * @param hql
	 * @param pageBean
	 * @param pMap
	 * @param session
	 * @return
	 */
	public List executeQuery(String hql,PageBean pageBean,Map<String, Object> pMap,Session session) {
		List list=null;
		Query query=null;
		if(pMap!=null && pageBean.isPagination()) {
			//首先要查询出符合条件的总记录数
			String countHql=getCountHql(hql);
			Query countQuery=session.createQuery(countHql);
			this.setParam(countQuery, pMap);
			pageBean.setTotal(countQuery.getSingleResult().toString());
			
			//返回符合条件的记录
			query=session.createQuery(hql);
			this.setParam(countQuery, pMap);
			query.setFirstResult(pageBean.getStartIndex());
			query.setMaxResults(pageBean.getRows());
			list=query.list();
		}else {
			query=session.createQuery(hql);
			this.setParam(query, pMap);
			list=query.list();
		}
		return list;
	}	
}

BookDao.java继承BaseDao.java

package com.xwt.five.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.query.Query;

import com.xwt.five.uity.PageBean;
import com.xwt.five.uity.StringUtils;
import com.xwt.four.entity.Book;
import com.xwt.two.uity.SessionFactoryUtils;

public class BookDao extends BaseDao {
	/**
	 * 基于hql的basedao的升级版
	 * @param book
	 * @param pageBean
	 * @return
	 */
	public List<Book> listPlus(Book book,PageBean pageBean){
		Session session=SessionFactoryUtils.openSession();
		/**
		 * 拼接hql语句
		 */
		String hql="from Book where 1=1";
		String bname=book.getBookName();
		//jsp自动传递过来的  不需要手写
		Map<String, Object> map=new HashMap<>();
		if(StringUtils.isNotBlank(bname)) {
			hql+=" and bookName like :bookName";
		}
		Query query=session.createQuery(hql);
		List  list = super.executeQuery(hql, pageBean, map, session);
		session.close();
		return list;
	}
}

测试

	@Test
	public void testHql2() {
		Book book=new Book();
		PageBean pageBean=new PageBean();
		pageBean.setPage(1);
		//book.setBookName("%斗%");
		List<Book> list=this.bookDao.list(book, pageBean);
		for(Book b:list) {
			System.out.println(b);
		}
	}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值