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 类名/属性 表名/列名 区分大小写,关键字不区分 ...
随机推荐
- C# - VS2019 DataGridView导出到Excel的三种方法
//原文出处:http://www.yongfa365.com/Item/DataGridViewToExcel.html 1 #region DataGridView数据显示到Excel /// & ...
- 关于C# webapi ,接口返回字符串和json格式 ,返回值中有反斜杠
最近遇到一个比较郁闷的问题,记录一下 写了一个接口,想返回json 数据,但是返回值中总是带有反斜杠... ,下面来看原因 首先,配置 webapi的路由 App_Start 文件夹下 ,WebApi ...
- C#关于反序列化实例时,接收实体字段少于或大于原实体对象 解析测试
在项目中总会用到son解析,比如RabbitMQ中使用json串解析,比如发过来的实体对象有50个字段,而实际只需要用到里面的几个字段,这时我们创建实体时,只需要创建需要的几个字段即可. 测试实例,首 ...
- CentOS环境下通过YUM安装软件,搭建lnmp环境
安装nginx.php-fpm和mysql. yum install nginx yum install php-fpm yum install mysql CentOS下LNMP环境配置 1. 配置 ...
- Data Management Technology(1) -- Introduction
1.Database concepts (1)Data & Information Information Is any kind of event that affects the stat ...
- Hadoop HA 架构
为什么要用集群? 企业里面,多台机器 伪分布式 每一个角色都是一个进程 HDFS: NN SNN DN YARN: RM NM 大数据所有组件, 都是主从架构 master-slave HDFS读写请 ...
- [20191112]oracle共享连接模式端口.txt
[20191112]oracle共享连接模式端口.txt --//如果使用共享服务模式,你可以发现每次重启数据库对应的端口号会发生变化.# netstat -tunlp | egrep "A ...
- Attaching an entity of type 'xxx' failed because another entity of the same type already has the same primary key value.
问题的详细描述: Attaching an entity of type 'xxxxx' failed because another entity of the same type already ...
- centos7.6 创建磁盘格式化
fdisk /dev/vdb mkfs.ext4 /dev/vdb echo '/dev/vdb /sdata ext4 defaults 0 0' >> /etc/fstab mount ...
- 记录Ubuntu下使用docker使用
关键词:docker.Dockerfile等等. 这里主要记录Ubuntu下docker使用细节. 首先是如何安装,然后如何创建docker镜像.搭建docker服务器.运行使用docker. 1. ...