hibernate的hql

HQL(Hibernate Query Language)是面向对象的查询语言,与SQL有所不同。它不区分类名和属性的大小写,但关键字不区分大小写。HQL支持别名和命名参数,并提供了多种处理返回结果集的方式,包括List、单个对象、Object[]和Map。通过使用占位符和命名参数,可以进行连接查询和聚合函数操作,如sum、avg等。此外,HQL还支持分页查询,结合辅助类可以实现更高效的检索。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

hql

什么是hql

HQL是Hibernate Query Language的缩写,查全部

hql和sql区别/异同

HQL

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

注1:QuerySyntaxException:book is not mapped。

处理返回的结果集

  1. 查询返回List
    案例代码:
String hql = "from Book";
		List list = session.createQuery(hql).list();
		list.forEach(b->{
			System.out.println(b);
		});

结果图:在这里插入图片描述

  1. 单个对象
    案例代码:
String hql = "from Book b where b.bookId=1";
		List list = session.createQuery(hql).list();
		list.forEach(b->{
			System.out.println(b);
		});

结果图:在这里插入图片描述
3. Object[]
案例代码:

String hql = "select bookId,bookName,price from Book";
		Query query = session.createQuery(hql);
		List<Object[]> list = query.list();
		list.forEach(b->{
			System.out.println(Arrays.toString(b));
		});
//		for (Object[] o : list) {
//			System.out.println(Arrays.toString(o));
//		}

结果图:在这里插入图片描述

  1. Map
    案例代码:
String hql = "select new Map(b.bookId as bookId,b.bookName as bookName,b.price as price) from Book b";
		Query query = session.createQuery(hql);
		List<Map> list = query.list();
		list.forEach(b->{
			System.out.println(b);
		});

结果图:在这里插入图片描述

  1. 构造方法
    案例代码:
String hql = "select new Book(b.bookId as bookId,b.bookName as bookName,b.price as price) from Book b";
		Query query = session.createQuery(hql);
		List list = query.list();
		list.forEach(b->{
			System.out.println(b);
		});

结果图:在这里插入图片描述

hql中使用占位符

  1. ?占位符
    从下标0开始计算位置
    hibernate5之后不再支持?占位符

  2. :命名参数
    案例代码:

String hql = "from Book b where b.price >:min and b.price <=:max";
		Query query = session.createQuery(hql);
		query.setParameter("min", 20f);
		query.setParameter("max", 120f);
		List list = query.list();
		list.forEach(b->{
			System.out.println(b);
		});

结果图:在这里插入图片描述

  1. 连接查询
    案例代码:
String sql = "select * from t_book_hb b\r\n" + 
				"inner join t_book_category_hb bc\r\n" + 
				"on b.book_id=bc.bid\r\n" + 
				"inner join t_category_hb c\r\n" + 
				"on bc.cid=c.category_id";
		NativeQuery nativeQuery = session.createNativeQuery(sql);
		List<Object[]> list = nativeQuery.list();
		list.forEach(b->{
			System.out.println(Arrays.toString(b));
		});

结果图:在这里插入图片描述

  1. 聚合函数(sum,avg,max, min,count)
    案例代码:
String hql = "select sum(price),avg(price),"
				+ "count(price),max(price),"
				+ "min(price) from Book";
		Query query = session.createQuery(hql);
		List<Object[]> list = query.list();
		list.forEach(b->{
			System.out.println(Arrays.toString(b));
		});

结果图:在这里插入图片描述

  1. hql分页
    int page = 2;// 页码:page
    int row = 10;// 每页行数:rows
    query.setFirstResult((page - 1) * row);// 设置起始记录下标
    query.setMaxResults(row);// 设置返回的最大结果集

案例代码:

String sql = "select * from t_book_hb";
		NativeQuery nativeQuery = session.createNativeQuery(sql);
		List<Object[]> list = nativeQuery.list();
		list.forEach(b->{
			System.out.println(Arrays.toString(b));
		});

结果图:在这里插入图片描述

辅助类

PageBean

package com.tang4.util;

import java.io.Serializable;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class PageBean implements Serializable {

	private static final long serialVersionUID = 2422581023658455731L;

	//页码
	private int page=1;
	//每页显示记录数
	private int rows=3;
	//总记录数
	private int total=0;
	//是否分页
	private boolean isPagination=true;
	//上一次的请求路径
	private String url;
	//获取所有的请求参数
	private Map<String,String[]> map;
	
	public PageBean() {
		super();
	}
	
	//设置请求参数
	public void setRequest(HttpServletRequest req) {
		//获取请求参数
		String page=req.getParameter("page");//页码
		String rows=req.getParameter("rows");//显示条数
		String pagination=req.getParameter("pagination");//是否分页
		//重载page/rows/pagination的set方法,并进行判空处理
		this.setPage(page);
		this.setRows(rows);
		this.setPagination(pagination);
		//获取上一次的请求路径,并保存到url
		this.url=req.getContextPath()+req.getServletPath();
		//获取上一次的所有请求参数集
		this.map=req.getParameterMap();
	}
	public String getUrl() {
		return url;
	}

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

	public Map<String, String[]> getMap() {
		return map;
	}

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

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	public void setPage(String page) {
		if(null!=page&&!"".equals(page.trim()))
			this.page = Integer.parseInt(page);
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}
	
	public void setRows(String rows) {
		if(null!=rows&&!"".equals(rows.trim()))
			this.rows = Integer.parseInt(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 isPagination;
	}
	
	public void setPagination(boolean isPagination) {
		this.isPagination = isPagination;
	}
	
	public void setPagination(String isPagination) {
		if(null!=isPagination&&!"".equals(isPagination.trim()))
			this.isPagination = Boolean.parseBoolean(isPagination);
	}
	
	/**
	 * 获取分页起始标记位置
	 * @return
	 */
	public int getStartIndex() {
		//(当前页码-1)*显示记录数
		return (this.getPage()-1)*this.rows;
	}
	
	/**
	 * 末页
	 * @return
	 */
	public int getMaxPage() {
		int totalpage=this.total/this.rows;
		if(this.total%this.rows!=0)
			totalpage++;
		return totalpage;
	}
	
	/**
	 * 下一页
	 * @return
	 */
	public int getNextPage() {
		int nextPage=this.page+1;
		if(this.page>=this.getMaxPage())
			nextPage=this.getMaxPage();
		return nextPage;
	}
	
	/**
	 * 上一页
	 * @return
	 */
	public int getPreivousPage() {
		int previousPage=this.page-1;
		if(previousPage<1)
			previousPage=1;
		return previousPage;
	}

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

BaseDao

package com.tang4.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;


public class BaseDao {
	
	public Session getSession() {
		return SessionFactoryUtils.openSession();
	}
	
	/**
	 * 设置Query的查询参数
	 * @param params
	 * @param query
	 * @return
	 */
	public void setParamters(Map<String,Object> params,Query query) {
		if(null==params||0==params.size())
			return;
		
		Set<Entry<String, Object>> set = params.entrySet();
		String name=null;
		Object value=null;
		for (Entry<String, Object> entry : set) {
			name=entry.getKey();
			value=entry.getValue();
			//判断参数是否是Collection,一般用于List/Set集合参数时使用
			if(value instanceof Collection)
				query.setParameterList(name, (Collection)value);
			//判断参数是否是Object[]
			else if(value instanceof Object[]) 
				query.setParameterList(name, (Object[])value);
			else 
				query.setParameter(name, value);
		}
	}
	
	/**
	 * 将普通hql语句转换成查询总记录数的hql语句
	 * @param hql
	 * @return
	 */
	public String countSql(String hql) {
		//from Book
		//select * from Book
		int start=hql.toUpperCase().indexOf("FROM");
		return "select count(1) "+hql.substring(start);
	}
	
	/**
	 * 查询(支持分页)
	 * @param hql       普通hql语句
	 * @param params    请求参数
	 * @param pageBean  分页对象
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public List executeQuery(String hql,Map<String,Object> params,PageBean pageBean) {
		Session session=getSession();
		Query query=null;
		//1.根据满足条件查询总记录数
		if(null!=pageBean&&pageBean.isPagination()) {
			//select count(1) from Book where 
			String countHql=this.countSql(hql);
			query = session.createQuery(countHql);
			this.setParamters(params, query);
			List list=query.list();
			pageBean.setTotal(Integer.parseInt(list.get(0).toString()));
		}
		query=session.createQuery(hql);
		//2.根据满足条件查询分页记录
		if(null!=pageBean&&pageBean.isPagination()) {
			query.setFirstResult(pageBean.getStartIndex());
			query.setMaxResults(pageBean.getRows());
		}
		this.setParamters(params, query);
		return query.list();
	}
}

把Book实体类修改一下
Book

package com.tang4.entity;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

public class Book implements Serializable{
	
	private Integer bookId;
	private String bookName;
	private Float price;
	Set<Category> categorys = new HashSet<Category>();
	
	public Set<Category> getCategorys() {
		return categorys;
	}
	public void setCategorys(Set<Category> categorys) {
		this.categorys = categorys;
	}
	public Integer getBookId() {
		return bookId;
	}
	public void setBookId(Integer bookId) {
		this.bookId = bookId;
	}
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public Float getPrice() {
		return price;
	}
	public void setPrice(Float price) {
		this.price = price;
	}
	@Override
	public String toString() {
		return "Book [bookId=" + bookId + ", bookName=" + bookName + ", price=" + price + "]";
	}
	public Book(Integer bookId, String bookName, Float price) {
		super();
		this.bookId = bookId;
		this.bookName = bookName;
		this.price = price;
	}
	public Book() {
		
	}	  

}

完整的代码

Test

package com.tang4.dao;

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.junit.After;
import org.junit.Before;

import com.tang.util.SessionFactoryUtils;
import com.tang4.entity.Book;

public class Test {
	
	Session session = null;
	Transaction ts = null;

	@Before
	public void setUp() throws Exception {
		session = SessionFactoryUtils.openSession();
		 ts = session.beginTransaction();
	}

	@After
	public void tearDown() throws Exception {
		ts.commit();
		SessionFactoryUtils.closeSession();
	}

	@org.junit.Test
	public void test() {
		//查询返回List<T>
		//select * from t_book_hb
		//from Book		
		/*String hql = "from Book";
		List list = session.createQuery(hql).list();
		list.forEach(b->{
			System.out.println(b);
		});*/
		
		//单个对象
		/*String hql = "from Book b where b.bookId=1";
		List list = session.createQuery(hql).list();
		list.forEach(b->{
			System.out.println(b);
		});*/
		
		//Object[]
		/*String hql = "select bookId,bookName,price from Book";
		Query query = session.createQuery(hql);
		List<Object[]> list = query.list();
		list.forEach(b->{
			System.out.println(Arrays.toString(b));
		});
//		for (Object[] o : list) {
//			System.out.println(Arrays.toString(o));
//		}
*/		
		//Map
		/*String hql = "select new Map(b.bookId as bookId,b.bookName as bookName,b.price as price) from Book b";
		Query query = session.createQuery(hql);
		List<Map> list = query.list();
		list.forEach(b->{
			System.out.println(b);
		});*/
		
		//构造方法
		/*String hql = "select new Book(b.bookId as bookId,b.bookName as bookName,b.price as price) from Book b";
		Query query = session.createQuery(hql);
		List list = query.list();
		list.forEach(b->{
			System.out.println(b);
		});*/
		
		//命名参数
		/*String hql = "from Book b where b.price >:min and b.price <=:max";
		Query query = session.createQuery(hql);
		query.setParameter("min", 20f);
		query.setParameter("max", 120f);
		List list = query.list();
		list.forEach(b->{
			System.out.println(b);
		});*/
		
		//连接查询
		/*String sql = "select * from t_book_hb b\r\n" + 
				"inner join t_book_category_hb bc\r\n" + 
				"on b.book_id=bc.bid\r\n" + 
				"inner join t_category_hb c\r\n" + 
				"on bc.cid=c.category_id";
		NativeQuery nativeQuery = session.createNativeQuery(sql);
		List<Object[]> list = nativeQuery.list();
		list.forEach(b->{
			System.out.println(Arrays.toString(b));
		});*/
		
		//聚合函数 sum() avg() count() max() min()
		/*String hql = "select sum(price),avg(price),"
				+ "count(price),max(price),"
				+ "min(price) from Book";
		Query query = session.createQuery(hql);
		List<Object[]> list = query.list();
		list.forEach(b->{
			System.out.println(Arrays.toString(b));
		});*/
		
		//hql分页
		
		String sql = "select * from t_book_hb";
		NativeQuery nativeQuery = session.createNativeQuery(sql);
		List<Object[]> list = nativeQuery.list();
		list.forEach(b->{
			System.out.println(Arrays.toString(b));
		});
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值