hibernateHQL
HQL 即Hibernate Query Language的缩写
hql和sql区别/异同
HQL SQL
类名/属性 表名/列名
区分大小写,关键字不区分大小写 不区分大小写
别名 别名
从下标0开始计算位置(hibernate5之后不支持) 从顺序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:
/**
* 查两个列段及以上,默认返回的是Object【】
*/
@Test
public void testList3() {
Query query = session.createQuery("select b.price,b.bookName as ss from Book b");
List<Object[]> list = query.list();
for (Object[] b : list) {
System.out.println(Arrays.toString(b));
}
}
map 函数:
/**
* 注意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支持连接查询
*/
@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分页:
/**
* 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);
}
}
按名字分页查询对应书籍信息
BookDao(继承BaseDao):
package com.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;
/**
* hibernate的通用查询Dao层
*
* @author xyls
*
*/
public class BaseDao {
/**
*
*
* @param category
*/
public List<Book> list1(Book book, PageBean pageBean) {
Session session = SessionFactoryUtils.openSession();
Transaction transaction = session.beginTransaction();
// 处理book实体类的条件查询
String bookName = book.getBookName();
//
String hql = " from Book where 1=1";
if (StringUtils.isNotBlank(bookName)) {
hql += " and bookName like : bookName";
}
Query query = session.createQuery(hql); if (StringUtils.isNotBlank(bookName)) {
query.setParameter("bookName", bookName);
}
// 处理分页
if (pageBean != null && pageBean.isPagination()) {
query.setFirstResult(pageBean.getStartIndex());
query.setMaxResults(pageBean.getRows());
}
List list = query.list();
transaction.commit();
session.close();
return list; }
public List<Book> list2(Book book, PageBean pageBean) {
Session session = SessionFactoryUtils.openSession();
Transaction transaction = session.beginTransaction();
// 处理book实体类的条件查询
String bookName = book.getBookName();
Map<String, Object> map=new HashMap<String,Object>();
//
String hql = " from Book where 1=1";
if (StringUtils.isNotBlank(bookName)) {
hql += " and bookName like : bookName";
map.put("bookName", bookName);
}
List list = super.executeQuery(session, hql, map, pageBean); transaction.commit();
session.close();
return list; }
BaseDao:
package com.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; /**
* hibernate的通用查询Dao层
*
* @author xyls
*
*/
public class BaseDao {
/**
* 给hibernate中的query对象中的参数列表赋值
*
* @param query
* @param map
*/
public void setParam(Query query, Map<String, Object> map) {
if (map != null && map.size() > 0) {
Set<Entry<String, Object>> entrySet = map.entrySet();
for (Entry<String, Object> entry : entrySet) {
Object value = entry.getValue();
if (value instanceof Collection)
query.setParameter(entry.getKey(), (Collection) value);
else if (value instanceof Object[])
query.setParameter(entry.getKey(), (Object[]) value);
else
query.setParameter(entry.getKey(), value); }
}
} /**
*
* @param hql
* @return
*/
public String getCountHql(String hql) {
return "select count(*)" + hql.substring(hql.toUpperCase().indexOf("FROM"));
} /**
* 通用hql语句查询
*
* @param session
* @param hql
* @param map
* @param pageBean
* @return
*/
public List executeQuery(Session session, String hql, Map<String, Object> map, PageBean pageBean) {
List list = null;
Query query = null;
if (pageBean != null && pageBean.isPagination()) {
String counthql = getCountHql(hql);
Query countQuery = session.createQuery(counthql);
this.setParam(countQuery, map);
pageBean.setTotal(countQuery.getSingleResult().toString()); query = session.createQuery(hql);
this.setParam(query, map);
query.setFirstResult(pageBean.getStartIndex());
query.setMaxResults(pageBean.getRows());
list = query.list(); } else {
query = session.createQuery(hql);
this.setParam(query, map);
list = query.list();
}
return list;
} }
PageBean:
package com.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 + "]";
} }
测试:
package com.dao; import java.util.List; import org.junit.Test; import com.entity.Book;
import com.entity.Category;
import com.util.PageBean; public class BookDaoTest {
private BookDao bookDao = new BookDao();
@Test
public void testList1() {
Book book = new Book();
// book.setBookName("%0030%");
PageBean pageBean = new PageBean();
pageBean.setPage(2);
List<Book> list1 = this.bookDao.list1(book, pageBean);
for (Book book2 : list1) {
System.out.println(book2);
}
} @Test
public void testList2() {
Book book = new Book();
book.setBookName("%0030%");
PageBean pageBean = new PageBean();
// pageBean.setPage(2);
List<Book> list1 = this.bookDao.list2(book, pageBean);
for (Book book2 : list1) {
System.out.println(book2);
}
}
}
testList1:
testList2:
hql实现不了的功能,可以考虑使用原生sql
多表(5+)联查
未配置映射文件中关系
hibernateHQL的更多相关文章
- hibernate-HQL连接查询
和SQL查询一样,HQL也支持各种各样的连接查询, 如内连接.外连接. 实例: package Test; import static org.junit.Assert.*; import java. ...
- hibernate----(Hql)另一种查询---利用Criteria类
package com.etc.test; import java.util.List; import org.hibernate.Criteria;import org.hibernate.Sess ...
- hibernate----(Hql)查询
package com.etc.test; import java.util.List;import java.util.Properties; import org.hibernate.Query; ...
- hibernate--HQL语法与详细解释
HQL查询: Criteria查询对查询条件进行了面向对象封装,符合编程人员的思维方式,不过HQL(Hibernate Query Lanaguage)查询提供了更加丰富的和灵活的查询特性,因此 Hi ...
- 28.Hibernate-HQL查询.md
目录 1.概述 2.HQL实例 3.Criteria 查询 4.SQL本地查询 5.分页 1.概述 1)Get/load主键查询 2)对象导航查询 3)HQL查询, Hibernate Query l ...
- Hibernate- HQL查询方式
HQL查询方式 01.基本查询 02.动态实例查询 03.分页查询 04.条件查询 05.连接查询 06.子查询
- Hibernate-HQL&QBC基础使用(分页)
@Test public void testHql() { Configuration configuration = new Configuration().configure(); Session ...
- Hibernate---Hql查询2---
hibernate.cfg.xml配置: <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configurati ...
- hibernateHQL语句
一.hql 1. 什么是hql HQL是Hibernate Query Language的缩写 查全部 2. hql和sql区别/异同 HQL SQL 类名/属性 表名/列名 区分大小写,关键字不区分 ...
随机推荐
- 跨域问题,解决方案-Nginx反向代理
跨域问题,解决之道 跨域问题,在日常开发过程中,是一个非常熟悉的名词.今天的话题,结合我之前的项目场景,讨论下<跨域问题,解决之道>. 跨域是什么 跨域问题,是由于JavaScript出于 ...
- jmeter 中使用正则表达式提取依赖参数
1:登录接口 这里有一个实际的登录接口,在响应中返回了一串token,如下图 那么我们在接下来的接口-经验库列表中,就必须带入这一串token,否则响应报错,如下图所示 如何获取登录的口令呢?这 ...
- vscode 格式化代码 与 eslint 有冲突的问题解决
项目中配置了eslint后,在使用vue界面里格式化的时候总是不一致.然后在配置中加了配置也无效(File - Preference - Setting) 查了下原因是在vue开发的时候我们一般都安装 ...
- mysql中的事务隔离级别
事务是逻辑上的一组操作,要么都执行,要么都不执行. 事务最经典的.经常被拿出来说的例子就是转账了.假如小花要给小白转账1000元,这个转账会涉及到两个关键操作就是:将小花的余额-1000,将小白的余额 ...
- 阿里面试实战题3----String,StringBuilder,StringBuffer区别
String public final class String implements java.io.Serializable, Comparable<String>, CharSequ ...
- dataTable 表插入新行
DataRow dr = dt.NewRow();//定义新行 dr["sumPrice"] = sumPrice;//对应字段赋值 d ...
- DockerFlie的基本命令解析
DockerFlie官网文档: https://docs.docker.com/engine/reference/builder/ DockerFile中文: http://www.docker ...
- 清新淡雅教育教学工作课件PPT模板
模板来源:http://ppt.dede58.com/jiaoxuekejian/26240.html
- 034.认证方式 | 基本认证 、Token认证、 AK/SK认证
认证方式 关于认证: https://www.cnblogs.com/badboyh2o/p/11068779.html https://www.cnblogs.com/badboyh2o/p/110 ...
- [20191106]善用column格式化输出.txt
[20191106]善用column格式化输出.txt # man columnDESCRIPTION The column utility formats its input into mu ...