hibernate之HQL
Posted liuwenwu9527
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hibernate之HQL相关的知识,希望对你有一定的参考价值。
一、hql语句基础知识
1. 什么是hql
HQL是Hibernate Query Language的缩写 hibernate查询语句
2. hql和sql区别/异同
HQL SQL
类名/属性 表名/列名
区分大小写,关键字不区分大小写 不区分大小写
别名 别名
?,从下标0开始计算位置(hibernate5之后不支持) ?,从顺序1开始计算位置
:命名参数 不支持:命名参数
面向对象的查询语言 面向结构查询语言
3. 处理返回的结果集
3.1 查单个对象 返回一个对象 用的最多
select没有逗号
3.2 查询两个列段以上 返回Object[]
b.bookId, b.bookName
3.3 Map函数,不区分大小写 返回的是map集合
new Map(b.bookId as bid, b.bookName as bname)
3.4 查两个列段及以上,也可返回对象,前提是有对应的构造函数
new 构造方法(attr1,attr2)
new Book(b.bookId, b.price)
3.5查询单个列段 返回String
Junit测试类 HqlTest:
package com.liuwenwu.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.liuwenwu.four.entity.Book; import com.liuwenwu.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<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);
4. hql中使用占位符
4.1 ?占位符
从下标0开始计算位置
hibernate5之后不再支持?占位符 因为存在sql攻击 传的不是正常传值,而是传的sql语句
select * from xxx where bid=?(select * from aa)
pst.serString(1,"select * from aa")
4.2 :命名参数的使用
/** * 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);
5. 连接查询
/** * HQL支持连接查询 */ @Test public void testList7() // sql写法:select * from t_hibernate_order o,t_hibernate_order_item oi where o.order_id=oi.oid 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));
6. 聚合函数 sum,avg,max,min,count
/** * HQL支持聚合函数 */ @Test public void testList8() Query query = session.createQuery("select count(*) from Book"); // getSingleResult是用来获取单条记录的 Long singleResult = (Long) query.getSingleResult(); System.out.println(singleResult);
7. hql分页
int page = 2;// 页码:page
int row = 10;// 每页行数:rows
query.setFirstResult((page - 1) * row);// 设置起始记录下标
query.setMaxResults(row);// 设置返回的最大结果集
/** * HQL分页 * sql limit 5,5 * hql from Book * 同样的可以自动根据方言生成分页语句 * setFirstResult:设置起始下标 * setMaxResults:设置偏移量 * mysql:hql limit 5,5 * oracle:select * from (select t.*,rownum rn hql t where t.rn >5)t1 where t1.rn<10 * */ @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);
二、hql通用分页查询方法
先导入两个分页工具类
PageBean:
package com.liuwenwu.five.util; import java.util.Map; import javax.servlet.http.HttpServletRequest; /** * 分页工具类 * */ public class PageBean private int page = 1;// 页码 private int rows = 3;// 页大小 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:
package com.liuwenwu.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);
之后我们写一个带查询条件的分页方法
/** * 需求: * 写一个带查询条件并且能分页的方法 * @param book * @param pageBean * @return */ public List<Book> list1(Book book,PageBean pageBean) Session session = SessionFactoryUtils.openSession(); Transaction transaction = session.beginTransaction(); String bookName = book.getBookName(); String hql="from Book where 1=1"; if(StringUtils.isNotBlank(bookName)) hql+=" and bookName like :bookName"; // query相当于前面sql所用的prepareStatement Query query = session.createQuery(hql); if(StringUtils.isNotBlank(bookName)) query.setParameter("bookName", bookName); // 通过写上述代码会发现,同样的if判断写了两次 // 下面这个代码每个实体类分页都得写 if(pageBean!=null&& pageBean.isPagination()) query.setFirstResult(pageBean.getStartIndex()); query.setMaxResults(pageBean.getRows()); List<Book> list=query.list(); transaction.commit(); session.close(); return list;
Junit测试
/** * 带查询条件的分页的方法测试 */ @Test public void list1() Book book=new Book(); PageBean pageBean=new PageBean(); // pageBean.setPage(2); book.setBookName("%少年阿宾%"); List<Book> list1 = this.bookDao.list1(book, pageBean); for (Book b : list1) System.out.println(b);
Book [bookId=5, bookName=少年阿宾, price=10.0] Book [bookId=6, bookName=少年阿宾2, price=10.0]
这样写太麻烦 我们来写一个通用的带查询分页方法
BaseDao:
package com.liuwenwu.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; /** * 1、设置参数的问题 * 2、分页代码重复的问题 * sql的通用分页 * getCountSql(sql) * select count(1) from (sql) t * * getCountHql(hql) * hql="from Book where bookName like :bookName" * hql="select * from new Book(bid,bookName) where bookName like :bookName" * select count(1) hql * * @author ASUS * */ public class BaseDao /** * 通用的参数设置方法 * @param map 参数键值对集合 * @param query 预定义处理hql对象 */ public void setParam(Map<String, Object> map,Query query) if(map!=null&&map.size()>0) Object value=null; Set<Entry<String, Object>> entrySet = map.entrySet(); for (Entry<String, Object> entry : entrySet) // 例子中的少年阿宾,但有时候它并不是单纯的字符串,可能是数字比如爱好,也可能是集合 value=entry.getValue(); //数组 if(value instanceof Object[]) query.setParameterList(entry.getKey(), (Object[])value); //集合 else if(value instanceof Collection) query.setParameterList(entry.getKey(), (Collection)value); //基本数据类型 else query.setParameter(entry.getKey(), value); public String getCountHql(String hql) // hql="from Book where bookName like :bookName" // hql="select * from new Book(bid,bookName) where bookName like :bookName" int index = hql.toUpperCase().indexOf("FROM"); return "select count(*)"+ hql.substring(index); /** * 通用查询方法 * @param session * @param map * @param hql * @param pageBean * @return */ public List executeQuery(Session session,Map<String, Object> map,String hql,PageBean pageBean) List list=null; if(pageBean!=null&&pageBean.isPagination()) String countHql=getCountHql(hql); Query countQuery = session.createQuery(countHql); this.setParam(map, countQuery); pageBean.setTotal(countQuery.getSingleResult().toString()); Query query = session.createQuery(hql); // 给预定义hql语句执行对象参数赋值,有多少赋值多少 this.setParam(map, query); //起始下标 query.setFirstResult(pageBean.getStartIndex()); //偏移量 query.setMaxResults(pageBean.getRows()); list=query.list(); else Query query = session.createQuery(hql); // 给预定义hql语句执行对象参数赋值,有多少赋值多少 this.setParam(map, query); list=query.list(); return list;
继承BaseDao后的通用分页加查询方法:
/** * 继承BaseDao的通用分页加查询方法 * @param book * @param pageBean * @return */ public List<Book> list2(Book book,PageBean pageBean) Session session = SessionFactoryUtils.openSession(); Transaction transaction = session.beginTransaction(); String bookName = book.getBookName(); Map<String, Object> map=new HashMap<>(); String hql="from Book where 1=1"; if(StringUtils.isNotBlank(bookName)) hql+=" and bookName like :bookName"; map.put("bookName", bookName); List<Book> list=super.executeQuery(session, map, hql, pageBean); transaction.commit(); session.close(); return list;
Junit测试:
/** * 继承BaseDao的通用带查询条件的分页的方法测试 */ @Test public void list2() Book book=new Book(); PageBean pageBean=new PageBean(); // pageBean.setPage(2); pageBean.setPagination(false); // book.setBookName("%少年阿宾%"); List<Book> list1 = this.bookDao.list2(book, pageBean); for (Book b : list1) System.out.println(b);
结果:
Book [bookId=1, bookName=西游记, price=50.0] Book [bookId=2, bookName=红楼梦, price=50.0] Book [bookId=3, bookName=水浒, price=50.0] Book [bookId=4, bookName=三国演义, price=50.0] Book [bookId=5, bookName=少年阿宾, price=10.0] Book [bookId=6, bookName=少年阿宾2, price=10.0] Book [bookId=7, bookName=诡秘之主, price=99.0]
以上是关于hibernate之HQL的主要内容,如果未能解决你的问题,请参考以下文章