Hibernate分页查询小结
通常使用的Hibernate通常是三种:hql查询,QBC查询和QBE查询:
1、QBE(Qurey By Example)检索方式
QBE
是最简单的,但是功能也是最弱的,QBE的功能不是特别强大,仅在某些场合下有用。一个典型的使用场合就是在查询窗口中让用户输入一系列的查询条件,然后
返回匹配的对象。QBE只支持=和like比较运算符,无法不大区间值,及其或的匹配。在这种情况下,还是采用HQL检索方式或QBC检索方式。
- /**
- * @function 根据传递过来的Object,分页显示在数据库中与其匹配的记录
- * @param pageNo
- * 当前页数
- * @param pageSize
- * 每页显示的记录数
- * @param object
- * 将查询条件封装为Object
- * @return 将查询结果封装为Pager返回
- */
- public Pager findPageByExample(int pageNo, int pageSize, Object object)
- {
- Pager pager = null;
- try
- {
- Criteria criteria = this.getSession().createCriteria(
- Class.forName(this.getEntity()));
- if (object != null)
- {
- criteria.add(Example.create(object).enableLike());
- }
- // 获取根据条件分页查询的总行数
- int rowCount = (Integer) criteria.setProjection(
- Projections.rowCount()).uniqueResult();
- criteria.setProjection(null);
- ) * pageSize);
- criteria.setMaxResults(pageSize);
- List result = criteria.list();
- pager = new Pager(pageSize, pageNo, rowCount, result);
- } catch (RuntimeException re)
- {
- throw re;
- } finally
- {
- return pager;
- }
- }
- /**
- * @function 根据传递过来的Object,分页显示在数据库中与其匹配的记录
- * @param pageNo
- * 当前页数
- * @param pageSize
- * 每页显示的记录数
- * @param object
- * 将查询条件封装为Object
- * @return 将查询结果封装为Pager返回
- */
- public Pager findPageByExample(int pageNo, int pageSize, Object object)
- {
- Pager pager = null;
- try
- {
- Criteria criteria = this.getSession().createCriteria(
- Class.forName(this.getEntity()));
- if (object != null)
- {
- criteria.add(Example.create(object).enableLike());
- }
- // 获取根据条件分页查询的总行数
- int rowCount = (Integer) criteria.setProjection(
- Projections.rowCount()).uniqueResult();
- criteria.setProjection(null);
- criteria.setFirstResult((pageNo - 1) * pageSize);
- criteria.setMaxResults(pageSize);
- List result = criteria.list();
- pager = new Pager(pageSize, pageNo, rowCount, result);
- } catch (RuntimeException re)
- {
- throw re;
- } finally
- {
- return pager;
- }
- }
注意代码的第20行,即criteria.add(Example.create(object).enableLike());这一行,需将Example.create(object)调用.enableLike()方法,不然不能模糊查询。
在BO层将需要模糊查询的列用"%%"串起来,不然仍然和"="一样。
BO层代码:
- /**
- * @function 将传递过来的参数封装成抢修人员Bean,分页查询符合条件的记录
- * @param pageNo
- * 当前的页码
- * @param pageSize
- * 每页显示的记录数
- * @param mendName
- * 抢修人员的名称
- * @param specialty
- * 抢修人员的工种
- * @param post
- * 抢修人员的职称
- * @return 将符合条件的记录数以及页码信息封装成PagerBean返回
- */
- public Pager getInfoByQuery(int pageNo, int pageSize, String mendName,
- String specialty, String post)
- {
- EicMend eicMend = new EicMend();
- )
- {
- eicMend.setMendname("%" + mendName + "%");
- }
- )
- {
- eicMend.setSpecialty(specialty);
- }
- )
- {
- eicMend.setPost(post);
- }
- Pager pager = erpManagerDao
- .findPageByExample(pageNo, pageSize, eicMend);
- return pager;
- }
- /**
- * @function 将传递过来的参数封装成抢修人员Bean,分页查询符合条件的记录
- * @param pageNo
- * 当前的页码
- * @param pageSize
- * 每页显示的记录数
- * @param mendName
- * 抢修人员的名称
- * @param specialty
- * 抢修人员的工种
- * @param post
- * 抢修人员的职称
- * @return 将符合条件的记录数以及页码信息封装成PagerBean返回
- */
- public Pager getInfoByQuery(int pageNo, int pageSize, String mendName,
- String specialty, String post)
- {
- EicMend eicMend = new EicMend();
- if (mendName != null && mendName.length() > 0)
- {
- eicMend.setMendname("%" + mendName + "%");
- }
- if (specialty != null && specialty.length() > 0)
- {
- eicMend.setSpecialty(specialty);
- }
- if (post != null && post.length() > 0)
- {
- eicMend.setPost(post);
- }
- Pager pager = erpManagerDao
- .findPageByExample(pageNo, pageSize, eicMend);
- return pager;
- }
执行SQL语句如下:
- Hibernate: select count(*) as y0_ from YJZX.EIC_MEND this_ where
- (this_.MENDNAME like ? and this_.POST like ?)
- Hibernate: select * from ( select this_.MENDID as MENDID23_0_, ……
- this_.EXPERTREMARK as EXPERTR28_23_0_ from YJZX.EIC_MEND this_ where
- (this_.MENDNAME like ? and this_.POST like ?) ) where rownum <= ?
- Hibernate: select count(*) as y0_ from YJZX.EIC_MEND this_ where
- (this_.MENDNAME like ? and this_.POST like ?)
- Hibernate: select * from ( select this_.MENDID as MENDID23_0_, ……
- this_.EXPERTREMARK as EXPERTR28_23_0_ from YJZX.EIC_MEND this_ where
- (this_.MENDNAME like ? and this_.POST like ?) ) where rownum <= ?
所以只需将需模糊查询的列用“%%”链接即可。
2、QBC(Qurey By Criteria)检索方式
采用HQL检索方式时,在应用程序中需要定义基于字符串形式的HQL查询语句。QBC
API提供了检索对象的另一种方式,它主要由Criteria接口、Criterion接口和Restrictions接口组成,它支持在运行时动态生成
查询语句。比较常见的是两种传参方式:一种是用map传参,另一种是用Criterion…不定参数传参。
Map传参方式范例如下:
DAO层:
- /**
- * @function 分页显示符合所有的记录数,将查询结果封装为Pager
- * @param pageNo
- * 当前页数
- * @param pageSize
- * 每页显示的条数
- * @param map
- * 将查询条件封装为map
- * @return 查询结果Pager
- */
- public Pager findPageByCriteria(int pageNo, int pageSize, Map map)
- {
- Pager pager = null;
- try
- {
- Criteria criteria = this.getSession().createCriteria(
- Class.forName(this.getEntity()));
- if (map != null)
- {
- Set<String> keys = map.keySet();
- for (String key : keys)
- {
- criteria.add(Restrictions.like(key, map.get(key)));
- }
- }
- // 获取根据条件分页查询的总行数
- int rowCount = (Integer) criteria.setProjection(
- Projections.rowCount()).uniqueResult();
- criteria.setProjection(null);
- ) * pageSize);
- criteria.setMaxResults(pageSize);
- List result = criteria.list();
- pager = new Pager(pageSize, pageNo, rowCount, result);
- } catch (RuntimeException re)
- {
- throw re;
- } finally
- {
- return pager;
- }
- }
- /**
- * @function 分页显示符合所有的记录数,将查询结果封装为Pager
- * @param pageNo
- * 当前页数
- * @param pageSize
- * 每页显示的条数
- * @param map
- * 将查询条件封装为map
- * @return 查询结果Pager
- */
- public Pager findPageByCriteria(int pageNo, int pageSize, Map map)
- {
- Pager pager = null;
- try
- {
- Criteria criteria = this.getSession().createCriteria(
- Class.forName(this.getEntity()));
- if (map != null)
- {
- Set<String> keys = map.keySet();
- for (String key : keys)
- {
- criteria.add(Restrictions.like(key, map.get(key)));
- }
- }
- // 获取根据条件分页查询的总行数
- int rowCount = (Integer) criteria.setProjection(
- Projections.rowCount()).uniqueResult();
- criteria.setProjection(null);
- criteria.setFirstResult((pageNo - 1) * pageSize);
- criteria.setMaxResults(pageSize);
- List result = criteria.list();
- pager = new Pager(pageSize, pageNo, rowCount, result);
- } catch (RuntimeException re)
- {
- throw re;
- } finally
- {
- return pager;
- }
- }
Map传参方式对应BO层代码:
- /**
- * @function 将传递过来的参数封装成抢修人员Bean,分页查询符合条件的记录
- * @param pageNo
- * 当前的页码
- * @param pageSize
- * 每页显示的记录数
- * @param mendName
- * 抢修人员的名称
- * @param specialty
- * 抢修人员的工种
- * @param post
- * 抢修人员的职称
- * @return 将符合条件的记录数以及页码信息封装成PagerBean返回
- */
- public Pager getInfoByQuery2(int pageNo, int pageSize, String mendName,
- String specialty, String post)
- {
- Map map = new HashMap();
- )
- {
- map.put("mendname", "%" + mendName + "%");
- }
- )
- {
- map.put("specialty", specialty);
- }
- )
- {
- map.put("post", post);
- }
- Pager pager = erpManagerDao.findPageByCriteria(pageNo, pageSize, map);
- return pager;
- }
- /**
- * @function 将传递过来的参数封装成抢修人员Bean,分页查询符合条件的记录
- * @param pageNo
- * 当前的页码
- * @param pageSize
- * 每页显示的记录数
- * @param mendName
- * 抢修人员的名称
- * @param specialty
- * 抢修人员的工种
- * @param post
- * 抢修人员的职称
- * @return 将符合条件的记录数以及页码信息封装成PagerBean返回
- */
- public Pager getInfoByQuery2(int pageNo, int pageSize, String mendName,
- String specialty, String post)
- {
- Map map = new HashMap();
- if (mendName != null && mendName.length() > 0)
- {
- map.put("mendname", "%" + mendName + "%");
- }
- if (specialty != null && specialty.length() > 0)
- {
- map.put("specialty", specialty);
- }
- if (post != null && post.length() > 0)
- {
- map.put("post", post);
- }
- Pager pager = erpManagerDao.findPageByCriteria(pageNo, pageSize, map);
- return pager;
- }
第二种方式:Criterion…不定参数传参方式。其代码如下所示:
DAO层代码:
- /**
- * @function 分页显示符合所有的记录数,将查询结果封装为Pager
- * @param pageNo
- * 当前页数
- * @param pageSize
- * 每页显示的条数
- * @param criterions
- * 不定参数Criterion
- * @return 查询结果Pager
- */
- public Pager findPageByCriteria(int pageNo, int pageSize,
- Criterion... criterions)
- {
- Pager pager = null;
- try
- {
- Criteria criteria = this.getSession().createCriteria(
- Class.forName(this.getEntity()));
- if (criterions != null)
- {
- for (Criterion criterion : criterions)
- {
- if (criterion != null)
- {
- criteria.add(criterion);
- }
- }
- }
- // 获取根据条件分页查询的总行数
- int rowCount = (Integer) criteria.setProjection(
- Projections.rowCount()).uniqueResult();
- criteria.setProjection(null);
- ) * pageSize);
- criteria.setMaxResults(pageSize);
- List result = criteria.list();
- pager = new Pager(pageSize, pageNo, rowCount, result);
- } catch (RuntimeException re)
- {
- throw re;
- } finally
- {
- return pager;
- }
- }
- /**
- * @function 分页显示符合所有的记录数,将查询结果封装为Pager
- * @param pageNo
- * 当前页数
- * @param pageSize
- * 每页显示的条数
- * @param criterions
- * 不定参数Criterion
- * @return 查询结果Pager
- */
- public Pager findPageByCriteria(int pageNo, int pageSize,
- Criterion... criterions)
- {
- Pager pager = null;
- try
- {
- Criteria criteria = this.getSession().createCriteria(
- Class.forName(this.getEntity()));
- if (criterions != null)
- {
- for (Criterion criterion : criterions)
- {
- if (criterion != null)
- {
- criteria.add(criterion);
- }
- }
- }
- // 获取根据条件分页查询的总行数
- int rowCount = (Integer) criteria.setProjection(
- Projections.rowCount()).uniqueResult();
- criteria.setProjection(null);
- criteria.setFirstResult((pageNo - 1) * pageSize);
- criteria.setMaxResults(pageSize);
- List result = criteria.list();
- pager = new Pager(pageSize, pageNo, rowCount, result);
- } catch (RuntimeException re)
- {
- throw re;
- } finally
- {
- return pager;
- }
- }
Criterion…不定参数传参方式对应BO层代码:
- /**
- * @function 将传递过来的参数封装成抢修人员Bean,分页查询符合条件的记录
- * @param pageNo
- * 当前的页码
- * @param pageSize
- * 每页显示的记录数
- * @param mendName
- * 抢修人员的名称
- * @param specialty
- * 抢修人员的工种
- * @param post
- * 抢修人员的职称
- * @return 将符合条件的记录数以及页码信息封装成PagerBean返回
- */
- public Pager getInfoByQuery3(int pageNo, int pageSize, String mendName,
- String specialty, String post)
- {
- Criterion criterion1 = null, criterion2 = null, criterion3 = null;
- )
- {
- criterion1 = Restrictions.ilike("mendname", mendName,
- MatchMode.ANYWHERE);
- }
- )
- {
- criterion2 = Restrictions.ilike("specialty", specialty,
- MatchMode.EXACT);
- }
- )
- {
- criterion3 = Restrictions.ilike("post", post, MatchMode.EXACT);
- }
- Pager pager = erpManagerDao.findPageByCriteria(pageNo, pageSize,
- criterion1, criterion2, criterion3);
- return pager;
- }
- /**
- * @function 将传递过来的参数封装成抢修人员Bean,分页查询符合条件的记录
- * @param pageNo
- * 当前的页码
- * @param pageSize
- * 每页显示的记录数
- * @param mendName
- * 抢修人员的名称
- * @param specialty
- * 抢修人员的工种
- * @param post
- * 抢修人员的职称
- * @return 将符合条件的记录数以及页码信息封装成PagerBean返回
- */
- public Pager getInfoByQuery3(int pageNo, int pageSize, String mendName,
- String specialty, String post)
- {
- Criterion criterion1 = null, criterion2 = null, criterion3 = null;
- if (mendName != null && mendName.length() > 0)
- {
- criterion1 = Restrictions.ilike("mendname", mendName,
- MatchMode.ANYWHERE);
- }
- if (specialty != null && specialty.length() > 0)
- {
- criterion2 = Restrictions.ilike("specialty", specialty,
- MatchMode.EXACT);
- }
- if (post != null && post.length() > 0)
- {
- criterion3 = Restrictions.ilike("post", post, MatchMode.EXACT);
- }
- Pager pager = erpManagerDao.findPageByCriteria(pageNo, pageSize,
- criterion1, criterion2, criterion3);
- return pager;
- }
3、HQL检索方式
HQL(Hibernate Query Language)是面向对象的查询语言,它和SQL查询语言有些相识。在Hibernate提供的各种检索方式中,HQL是使用最广的一种检索方式。
使用Query接口分页查询DAO代码:
- /**
- * @function 分页显示符合所有的记录数,将查询结果封装为Pager
- * @param pageNo
- * 当前页数
- * @param pageSize
- * 每页显示的条数
- * @param instance
- * 将查询条件封装为专家Bean
- * @return 查询结果Pager
- */
- public List<Object> findPageByQuery(int pageNo, int pageSize, String hql,
- Map map)
- {
- List<Object> result = null;
- try
- {
- Query query = this.getSession().createQuery(hql);
- Iterator it = map.keySet().iterator();
- while (it.hasNext())
- {
- Object key = it.next();
- query.setParameter(key.toString(), map.get(key));
- }
- ) * pageSize);
- query.setMaxResults(pageSize);
- result = query.list();
- } catch (RuntimeException re)
- {
- throw re;
- }
- return result;
- }
- /**
- * @function 分页显示符合所有的记录数,将查询结果封装为Pager
- * @param pageNo
- * 当前页数
- * @param pageSize
- * 每页显示的条数
- * @param instance
- * 将查询条件封装为专家Bean
- * @return 查询结果Pager
- */
- public List<Object> findPageByQuery(int pageNo, int pageSize, String hql,
- Map map)
- {
- List<Object> result = null;
- try
- {
- Query query = this.getSession().createQuery(hql);
- Iterator it = map.keySet().iterator();
- while (it.hasNext())
- {
- Object key = it.next();
- query.setParameter(key.toString(), map.get(key));
- }
- query.setFirstResult((pageNo - 1) * pageSize);
- query.setMaxResults(pageSize);
- result = query.list();
- } catch (RuntimeException re)
- {
- throw re;
- }
- return result;
- }
查询所有记录数的DAO代码:
- /**
- * @function 根据查询条件查询记录数的个数
- * @param hql
- * hql查询语句
- * @param map
- * 用map封装查询条件
- * @return 数据库中满足查询条件的数据的条数
- */
- public int getTotalCount(String hql, Map map)
- {
- try
- {
- Query query = this.getSession().createQuery(hql);
- Iterator it = map.keySet().iterator();
- while (it.hasNext())
- {
- Object key = it.next();
- query.setParameter(key.toString(), map.get(key));
- }
- );
- return i;
- } catch (RuntimeException re)
- {
- throw re;
- }
- }
- /**
- * @function 根据查询条件查询记录数的个数
- * @param hql
- * hql查询语句
- * @param map
- * 用map封装查询条件
- * @return 数据库中满足查询条件的数据的条数
- */
- public int getTotalCount(String hql, Map map)
- {
- try
- {
- Query query = this.getSession().createQuery(hql);
- Iterator it = map.keySet().iterator();
- while (it.hasNext())
- {
- Object key = it.next();
- query.setParameter(key.toString(), map.get(key));
- }
- Integer i = (Integer) query.list().get(0);
- return i;
- } catch (RuntimeException re)
- {
- throw re;
- }
- }
BO层代码:
- /**
- * @function 将传递过来的参数封装成专家Bean,分页查询符合条件的记录
- * @param pageNo
- * 当前的页码
- * @param pageSize
- * 每页显示的记录数
- * @param expertName
- * 专家的名称
- * @param expertSpecialty
- * 专家的专业类别
- * @param post
- * 专家的行政职位
- * @return 将符合条件的记录数以及页码信息封装成PagerBean返回
- */
- public Pager getInfoByQuery(int pageNo, int pageSize, String expertName,
- String expertSpecialty, String post)
- {
- StringBuffer hql = new StringBuffer();
- hql.append("select count(expertid) from EicExpert where 1=1 ");
- Map map = new HashMap();
- )
- {
- map.put("expertname", "%" + expertName + "%");
- hql.append("and expertname like :expertname ");
- }
- )
- {
- map.put("expertspecialty", expertSpecialty);
- hql.append("and expertspecialty like :expertspecialty ");
- }
- )
- {
- map.put("post", post);
- hql.append("and post like :post ");
- }
- );
- List result = erpManagerDao.findPageByQuery(pageNo, pageSize,
- queryHql, map);
- int rowCount = erpManagerDao.getTotalCount(hql.toString(), map);
- Pager pager = new Pager(pageSize, pageNo, rowCount, result);
- return pager;
- }
Hibernate分页查询小结的更多相关文章
- Hibernate 分页 查询
昨天的作业 分页: 主要的代码块:(明天实现分页的封装) package com.cy.beans; import java.util.List; /** * 定义一个分页对象 * @author ...
- Hibernate分页查询的两个方法
Hibernate中HQL查询语句有一个分页查询, session.setMaxResult(参数)和session.setFirstResult(参数) 如果只设置session.setMaxRes ...
- hibernate分页查询的各种方法
统计总数: public Integer countAll1() { String hql = "select count(*) from News as news"; List ...
- hibernate分页查询的实现
在mysql中新建数据好USER表,字段有3个,分别是id.username.password,贴上脚本仅供参考 create table `ding`.`user`( `id ...
- [Hibernate] 分页查询
@Test public void test9(){ //根据部门编号进行分组,再根据每个部门总工资>5000 Session ss=HibernateUtil.getSession(); St ...
- Hibernate分页查询报错
不知道什么原因,就是这里报错的
- Hibernate的查询,二级缓存,连接池
Hibernate的查询,二级缓存,连接池 1.Hibernate查询数据 Hibernate中的查询方法有5中: 1.1.Get/Load主键查询 使用get或者load方法来查询,两者之间的区别在 ...
- Hibernate分页功能数据重复问题
今天遇到一个很憋屈的问题那就是hibernate分页查询中出现重复数据,本来一直没有在意,以为是数据问题,但是一查程序和数据都没有问题,继续深入查看,找到问题了就是order By 时出的问题,唉.. ...
- 用Hibernate和Struts2+jsp实现分页查询、修改删除
1.首先用get的方法传递一个页数过去 2.通过Struts2跳转到Action 3.通过request接受主页面index传过的页数,此时页数是1, 然后调用service层的方法获取DAO层分页查 ...
随机推荐
- 11--Python 备份文件程序
最近看了下<A Byte of Python>, 看见一个非常有意思的程序,用python进行文件行备份的练习程序, 自己在机器上敲代码运行了一遍,结果出现了一个小问题,路径出错--&qu ...
- Apriori算法-位运算-C语言
原文地址:http://blog.csdn.net/liema2000/article/details/6118423 //////////////////////////////////////// ...
- Dell7040mt安装win7系统说明
几天新买的Dell7040mt收到了,机器预装了win10系统,把win10作为开发平台,可能会有一些问题,所以改为win7,今天折腾了一天,终于把win7系统装上了.总结一下安装的步骤. 1 准备启 ...
- Linux平台从文件中查找字符赋值于变量
以telnet方式登录Linux主机,在默认目录下用命令创建一个包含DUT wanIP的文本文件.[root] echo wanIP=88.0.100.253 > ./wanIP.txt在默认目 ...
- MyEclipse的Expressions没有结果的解决办法
之前我的Expressions在Value这一列什么都不显示,就连简单的1+2结果3都不显示出来. 然后我咬咬牙把它卸载了,然后重装就好了,我也不清楚是什么原因. 1.之前我安装的目录是"C ...
- php根据时间显示刚刚,几分钟前,今天,昨天的实现代码
如果大家有更好的方案欢迎交流 function diffBetweenTwoDay($pastDay){ $timeC = time() - strtotime($pastDay); $dateC = ...
- SSH returns “too many authentication failures” error – HostGator
I am an avid fan of using HostGator for small business WordPress website hosting. I love that they u ...
- 二分三角形的时候尤其需要注意!!! HDU 5115 二分+模拟
题目大意:http://blog.csdn.net/snowy_smile/article/details/49535301 思路:分类讨论,分别在[1,2].(2,3).[3,4).[4,1]相遇, ...
- SQL 查询时间段内的时间
declare @dt1 as datetime declare @dt2 as datetime set @dt1 = '2008-01-01' set @dt2 = '2009-01-01' ;w ...
- 使用oracle数据库开发,异常总结
最近两天使用的oracle数据库开发项目时遇到了2个异常,第一个是执行sql语句时报异常:“ORA-00911: 无效字符”,如下图: sql语句如下: 断点调试,把sql语句拷贝到pl/sql里执行 ...