Hibernate之HQL
作者:互联网
目录:
一,hql的定义
二,hql与sql的对比
三,hql的使用
四,Basedao
一、HQL的定义
1、定义:HQL是Hibernate Query Language的缩写,Hibernate语言查询,它是完全面向对象的查询语句,查询功能非常强。
二、HQL与SQL的对比
HQL(面向对象) SQL(面向结构)
类名/属性 表名/列名
区分大小写,关键字不区分大小写 不区分大小写
从下标0开始计算位置 从顺序1开始计算位置
支持命名参数 不支持命名参数
三、HQL的使用:
首先将相关的实体类和dao方法导入进去:
package com.lsy.three.hql;
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.lsy.two.entity.Book;
import com.lsy.two.util.SessionFactoryUtil;
public class HqlTest {
private Session session;
private Transaction transaction;
@Before
public void before() {
session = SessionFactoryUtil.getSession();
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 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支持连接查询
* sql是否支持连接查询,BaseDao,Vo
*
*/
@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(2);//起始下标
query.setMaxResults(3);//偏移量
List<Book> list = query.list();
for (Book b : list) {
System.out.println(b);
}
}
public void testList10() {
String hql="from Book where 1=1";
Book book=new Book();
if(book.getBookId()!=0) {
hql+=" and bookId=:bookId";
}
if(book.getBookName()!=null) {
hql+=" and bookName=:bookName";
}
Query query = session.createQuery(hql);
if(book.getBookId()!=0) {
query.setParameter("bookId", 1);
}
if(book.getBookName()!=null) {
query.setParameter("bookName", "%圣墟%");
}
query.setParameter("bookId", 1);
Book b = (Book) query.getSingleResult();
System.out.println(b);
}
}
PageBean
package com.lsy.three.hql;
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.lsy.three.hql;
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);
}
}
一 、HQL查询:一共有以下几种情况:
1、返回对象(多个):
代码:
/**
* 返回对象(多个)
*/
@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支持占位符、支持连接查询、支持聚合函数、支持分页:
1、支持占位符:
一共有三种情况:
1、第一种是根据对象来命名参数
2、第二种是根据数组来命名参数
3、第三种是根据集合来命名参数
/**
* 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);
}
/**
* HQL支持连接查询
* sql是否支持连接查询,BaseDao,Vo
*
*/
@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(2);//起始下标
query.setMaxResults(3);//偏移量
List<Book> list = query.list();
for (Book b : list) {
System.out.println(b);
}
}
四、BaseDao:
basedao是一个基础的dao包,在自定义mvc中也写了一个公用的dao方法,在设计dao层的时候,也涉及了设计的思路:
思路:
1、完成一个基础的查询方法
2、分析共同之处:
1、都有非空判断
2、都有query对象执行
3、都有通用分页
4、都有具体的对象/map
代码
package com.lsy.three.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.lsy.three.hql.PageBean;
/**
* 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 Administrator
*
*/
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;
}
}
bye~
标签:session,Hibernate,void,list,Book,HQL,query,public 来源: https://blog.csdn.net/Cat_Jay_Fish/article/details/120899118