1 . 什么是HQL
HQL是Hibernate Query Language的缩写
2 . hql和sql区别/异同
HQL SQL
类名/属性 表名/列名
区分大小写,关键字不区分大小写 不区分大小写
别名 别名 as a
?,从下标0开始计算位置(hibernate5之后不支持) ?,从顺序1开始计算位置
:命名参数 不支持:命名参数
面向对象的查询语言 面向结构查询语言
注意:QuerySyntaxException:book is not mapped
3 . 处理返回的结果集
3.1 单个对象
select没有逗号
3.2 Object[]
b.bookId, b.bookName
3.3 Map
new Map(b.bookId as bid, b.bookName as bname)
3.4 new 构造方法(attr1,attr2)
new Book(b.bookId, b.price)
单个列段
4 . hql中使用占位符
4.1 ?占位符
从下标0开始计算位置
hibernate5之后不再支持?占位符
4.2 :命名参数
6 . 聚合函数
sum
avg
max
min
count
HqlTest:
package com.xhh.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.xhh.five.util.PageBean;
import com.xhh.four.dao.BookDao;
import com.xhh.four.entity.Book;
import com.xhh.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 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
工具类:
PageBean:
package com.xhh.five.util;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/**
* 分页工具类
*
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 5;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
// 获取前台向后台提交的所有参数
private Map 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 getParameterMap() {
return parameterMap;
}
public void setParameterMap(Map 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:
package com.xhh.five.util;
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);
}
}
测试;
test1:
test2:
test3:
…太多不挨个展示
Dao类:
BaseDao:
package com.xhh.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,pabean,class clz
* @author PC
*
*/
public class BaseDao {
public void setParam(Query query, Map paMap) {
if(paMap != null && paMap.size()>0) {
Set> entrySet = paMap.entrySet();
for (Entry entry : entrySet) {
String key = entry.getKey();
Object value = entry.getValue();
// value可能是数组
if(value instanceof Object[]) {
query.setParameterList(key, (Object[])value);
}else if(value instanceof Collection) {
// value可能是集合
query.setParameterList(key, (Collection)value);
}else {
query.setParameter(key,value);
}
}
}
}
/**
* 拼装符合条件的总记录数
* @param hql
* @return
*/
public String getCounttHql(String 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) {
List list =null;
Query query= null;
if(pageBean != null && pageBean.isPagination()) {
//查询出符合条件的总记录数
String countHql=getCounttHql(hql);
Query createQuery = session.createQuery(countHql);
this.setParam(createQuery, paMap);
pageBean.setTotal(createQuery.getSingleResult().toString());
// 返回符合条件记录
query=session.createQuery(hql);
this.setParam(query, paMap);;
query.setFirstResult(pageBean.getStartIndex());
query.setMaxResults(pageBean.getRows());
}else {
query = session.createQuery(hql);
this.setParam(query, paMap);
list = query.list();
}
return null;
}
}
BookDao:
package com.xhh.four.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.xhh.five.util.BaseDao;
import com.xhh.five.util.PageBean;
import com.xhh.five.util.StringUtils;
import com.xhh.four.entity.Book;
import com.xhh.four.entity.Category;
import com.xhh.util.SessionFactoryUtils;
import net.bytebuddy.implementation.bind.annotation.Super;
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语句的命名参数赋值 可简化
* 3、分页
* * @param pageBean
book@param
* @return
*/
public List list(Book book,PageBean pageBean){
Session session = SessionFactoryUtils.openSession();
// Transaction transaction = session.beginTransaction();
String hql = "from Book where 1=1";
String bname=book.getBookName();
// 这个是自动传递过来的,不要手写
Map map=new HashMap();
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;
}
/**
* 加强版
* @param book
* @param pageBean
* @return
*/
public List listPlus(Book book,PageBean pageBean){
Session session = SessionFactoryUtils.openSession();
// Transaction transaction = session.beginTransaction();
String hql = "from Book where 1=1";
String bname=book.getBookName();
// 这个是自动传递过来的,不要手写
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);
// transaction.commit();
session.close();
return list;
}
}
测试:
@Test
public void testList10() {
Book book=new Book();
PageBean pageBean = new PageBean();
// pageBean.setPage(2);
book.setBookName("%圣墟%");
List 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 list=this.bookDao.listPlus(book, pageBean);
for (Book b : list) {
System.out.println(b);
}
}