用hibernate实现动态查询+分页的模板,适合于所有的页面

封装页面的信息,进行了泛型。

PageInfo.java
 1  package cn.jbit.auction.entity;
 2
 3 import java.util.List;
 4 /**
 5  * 分页封装类
 6  */
 7 public class PageInfo<T> {//此处进行了泛型<T>,使用与所有的对象
 8     public static final int PAGESIZE = 3;
 9     private Integer count;// 总记录数
10     private List<T> pageList;// 当前页的记录集合
11     private Integer pageIndex;// 当前页号
12     private Integer totalPages;// 总页数
13
14     public Integer getCount() {
15         return count;
16     }
17
18     public void setCount(Integer count) {
19         this.count = count;
20     }
21
22     public List<T> getPageList() {
23         return pageList;
24     }
25
26     public void setPageList(List<T> pageList) {
27         this.pageList = pageList;
28     }
29
30     public Integer getPageIndex() {
31         return pageIndex;
32     }
33
34     public void setPageIndex(Integer pageIndex) {
35         this.pageIndex = pageIndex;
36     }
37
38     public Integer getTotalPages() {
39         this.totalPages = this.count / this.PAGESIZE;
40         if (this.count % this.PAGESIZE != 0)
41             this.totalPages++;
42         return this.totalPages;
43     }
44
45 }

jsp页面auctionList.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<link href="css/common.css" rel="stylesheet" type="text/css" />
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
    function goToPage(pageIndex){
        document.forms[0].action=document.forms[0].action+"?pageIndex="+pageIndex;
        document.forms[0].submit();
    }
</script>
</head>

<body>
<form method="post" action="auctionList">
<div class="wrap">
<!-- main begin-->
  <div class="sale">
    <h1 class="lf">在线拍卖系统</h1>
      <c:if test="${not empty sessionScope.user}">
        <div class="logout right"><a href="doLogout" title="注销">注销</a></div>
    </c:if>
    <c:if test="${empty sessionScope.user}">
        <div class="logout right"><a href="login.jsp" title="登录">登录</a></div>
    </c:if>
  </div>
  <div class="forms">
    <label for="name">名称</label>
    <input name="auctionName" type="text" class="nwinput" id="name"/>
    <label for="names">描述</label>
    <input name="auctionDesc" type="text" id="names" class="nwinput"/>
    <label for="time">开始时间</label>
    <input name="auctionStartTime" type="text" id="time" class="nwinput"/>
    <label for="end-time">结束时间</label>
    <input name="auctionEndTime" type="text" id="end-time" class="nwinput" />
    <label for="price">起拍价</label>
    <input name="auctionStartPrice" type="text" id="price" class="nwinput" />
    <input type="submit"  value="查询" class="spbg buttombg f14  sale-buttom"/>
    <c:if test="${sessionScope.user.userisadmin==true}">
        <input type="button" onclick="location=‘addAuction.jsp‘"  value="发布" class="spbg buttombg f14  sale-buttom buttomb"/>
    </c:if>
    <br/>
    <c:if test="${sessionScope.user.userisadmin==false}">
      &nbsp;&nbsp;&nbsp;&nbsp;<a href="auctionResult"><b>查看竞拍结果</b></a>
      </c:if>
  </div>
  <div class="items">
      <ul class="rows even strong">
        <li>名称</li>
        <li class="list-wd">描述</li>
        <li>开始时间</li>
        <li>结束时间</li>
        <li>起拍价</li>
        <li class="borderno">操作</li>
      </ul>
      <c:forEach items="${requestScope.auctionPageInfo.pageList }" var="auction">
      <ul class="rows">
        <li>${auction.auctionname }</li>
        <li class="list-wd">${auction.auctiondesc }</li>
        <li>${auction.auctionstarttime }</li>
        <li>${auction.auctionendtime }</li>
        <li>${auction.auctionstartprice }</li>
        <li class="borderno red">
            <c:if test="${sessionScope.user.userisadmin==true }">
                   修改|
                  删除
              </c:if>
            <c:if test="${sessionScope.user.userisadmin==false }">
                  <a href="auctionDetail?auctionId=${auction.auctionid }">竞拍</a>
              </c:if>
        </li>
      </ul>
      </c:forEach>
      <div class="page">
        <a href="javascript:goToPage(1)">首页</a>
        <c:if test="${requestScope.auctionPageInfo.pageIndex!=1}">
            <a href="javascript:goToPage(${requestScope.auctionPageInfo.pageIndex-1 })">上一页</a>
        </c:if>
        <c:forEach step="1" begin="1" end="${requestScope.auctionPageInfo.totalPages }" var="pageIndex">
        <a href="javascript:goToPage(${pageIndex })">${pageIndex }</a>
        </c:forEach>
        <c:if test="${requestScope.auctionPageInfo.pageIndex!=requestScope.auctionPageInfo.totalPages}">
            <a href="javascript:goToPage(${requestScope.auctionPageInfo.pageIndex+1 })">下一页</a>
        </c:if>
        <a href="javascript:goToPage(${requestScope.auctionPageInfo.totalPages })" >尾页</a>
      </div>
  </div>
<!-- main end-->
</div>
</form>
</body>
</html>

Servlet页面

AuctionListServlet
package cn.jbit.auction.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.jbit.auction.biz.IAuctionBiz;
import cn.jbit.auction.biz.impl.AuctionBizImpl;
import cn.jbit.auction.entity.Auction;
import cn.jbit.auction.entity.PageInfo;
import cn.jbit.auction.util.Tool;

public class AuctionListServlet extends EncodingServlet {

    public AuctionListServlet() {
        super();
    }

    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            IAuctionBiz biz = new AuctionBizImpl();
            int pageIndex=1;
            if(request.getParameter("pageIndex")!=null){
                pageIndex=new Integer(request.getParameter("pageIndex")).intValue();
            }
            Auction condition=new Auction();
            if(request.getParameter("auctionName")!=null&&!"".equals(request.getParameter("auctionName"))){
                condition.setAuctionname(request.getParameter("auctionName"));
            }
            if(request.getParameter("auctionDesc")!=null&&!"".equals(request.getParameter("auctionDesc"))){
                condition.setAuctiondesc(request.getParameter("auctionDesc"));
            }
            if(request.getParameter("auctionStartTime")!=null&&!"".equals(request.getParameter("auctionStartTime"))){
                condition.setAuctionstarttime(new java.sql.Timestamp(Tool.strToDate(request.getParameter("auctionStartTime"), "yyyy-MM-dd HH:mm:dd").getTime()));
            }
            if(request.getParameter("auctionEndTime")!=null&&!"".equals(request.getParameter("auctionEndTime"))){
                condition.setAuctionendtime(new java.sql.Timestamp(Tool.strToDate(request.getParameter("auctionEndTime"), "yyyy-MM-dd HH:mm:dd").getTime()));
            }
            if(request.getParameter("auctionStartPrice")!=null&&!"".equals(request.getParameter("auctionStartPrice"))){
                condition.setAuctionstartprice(new Double(request.getParameter("auctionStartPrice")));
            }
            PageInfo<Auction> auctionPageinfo = biz.find(condition,pageIndex);
            request.setAttribute("auctionPageInfo", auctionPageinfo);
            request.getRequestDispatcher("auctionList.jsp").forward(request, response);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            request.setAttribute("message", e.getMessage());
            request.getRequestDispatcher("error.jsp").forward(request,response);
        }
    }

    public void init() throws ServletException {
        // Put your code here
    }

}

dao层的实现方法

public PageInfo<Auction> select(Auction condition, int pageIndex)
            throws Exception {
        PageInfo<Auction> pageInfo = new PageInfo<Auction>();
        Session session = HibernateUtil.currentSession();
        DetachedCriteria dc = DetachedCriteria.forClass(Auction.class);
        Criteria c = session.createCriteria(Auction.class);// 用于列表
        Criteria c1 = session.createCriteria(Auction.class);// 用于查询总记录数
        if (condition.getAuctionname() != null
                && !condition.getAuctionname().equals("")) {
            c.add(Restrictions.ilike("auctionname", condition.getAuctionname(),
                    MatchMode.ANYWHERE));
            c1.add(Restrictions.ilike("auctionname",
                    condition.getAuctionname(), MatchMode.ANYWHERE));
        }
        if (condition.getAuctiondesc() != null
                && !"".equals(condition.getAuctiondesc())) {
            c.add(Restrictions.ilike("auctiondesc", condition.getAuctiondesc(),
                    MatchMode.ANYWHERE));
            c1.add(Restrictions.ilike("auctiondesc",
                    condition.getAuctiondesc(), MatchMode.ANYWHERE));
        }
        if (condition.getAuctionstarttime() != null) {
            c.add(Restrictions.ge("auctionstarttime",
                    condition.getAuctionstarttime()));
            c1.add(Restrictions.ge("auctionstarttime",
                    condition.getAuctionstarttime()));
        }
        if (condition.getAuctionendtime() != null) {
            c.add(Restrictions.le("auctionendtime",
                    condition.getAuctionendtime()));
            c1.add(Restrictions.le("auctionendtime",
                    condition.getAuctionendtime()));
        }
        if (condition.getAuctionstartprice() != null) {
            c.add(Restrictions.ge("auctionstartprice",
                    condition.getAuctionstartprice()));
            c1.add(Restrictions.ge("auctionstartprice",
                    condition.getAuctionstartprice()));
        }
        c.addOrder(Order.desc("auctionstarttime"));
        // 总记录数
        int count = (Integer) c1.setProjection(Projections.rowCount())
                .uniqueResult();
        pageInfo.setCount(count);
        // 当前页号
        pageInfo.setPageIndex(pageIndex);
        // 分页
        // 每页显示的记录数
        c.setMaxResults(PageInfo.PAGESIZE);
        c.setFirstResult((pageIndex - 1) * PageInfo.PAGESIZE);
        List<Auction> list = c.list();
        pageInfo.setPageList(list);
        return pageInfo;
    }

dao层接口

PageInfo<Auction> select(Auction condition,int pageIndex) throws Exception;

biz层的实现方法

public PageInfo<Auction> find(Auction condition,int pageIndex) throws Exception {
        return this.dao.select(condition, pageIndex);
    }

biz层的接口

PageInfo<Auction> find(Auction condition,int pageIndex) throws Exception;
时间: 2024-10-06 21:54:05

用hibernate实现动态查询+分页的模板,适合于所有的页面的相关文章

Hibernate与Jpa的关系,以及使用分页和动态查询

最近由于项目调动,我去了使用JPA的项目组, 因为之前的项目组使用MyBatis,所以一时间关于JPA和Hibernate的知识体系记得不熟,导致出现了混乱:在网上看到了这篇文章,终于解决了我心中的疑惑:JPA是一种规范,Hibernate实现了这种规范 . 这篇短小精悍的文章给了我很多的启发,于是,我把它"复制"到了本文! http://blog.sina.com.cn/s/blog_5f1619e80100yoxz.html 我知道Jpa是一种规范,而Hibernate是它的一种实

hibernate中带查询条件的分页

所谓分页,从数据库中分,则是封装一个分页类.利用分页对象进行分页. 但,分页往往带查询条件. 分页类的三个重要数据:[当前页码数],[数据库中的总记录数],[每页显示的数据的条数] 原理:select * from  [表名] where   [字段名]  like   ['%条件%']    limit  [开始查询的索引],[每页显示的数据] 带查询条件的分页分两步 (1)第一步:查询出符合条件的数据的总条数 ---->select count(*) from [表名] where  [字段

动态多条件查询分页以及排序(一)--MVC与Entity Framework版url分页版

一.前言 多条件查询分页以及排序  每个系统里都会有这个的代码 做好这块 可以大大提高开发效率  所以博主分享下自己的6个版本的 多条件查询分页以及排序 二.目前状况 不论是ado.net 还是EF 在做多条件搜索时 都有这类似的代码 这样有几个不好的地方 1.当增加查询条件,需要改代码,对应去写相应的代码. 2.对多表查询以及or的支持 不是很好.而我们很常见的需求不可能是一个表的查询 3. 这样写表示层直接出现 了SQL语句 或者 linq 的拉姆达表达式  这是很不好的 表示层不应该知道数

[Hibernate] 通过 properties 类和 hql 语句进行动态查询

//需要保证Emp和EmpProperties中的setter和getter以及属性以及 参数占位符(:eName) 的一致//动态查询 @Test public void test4(){ EmpProperties ep=new EmpProperties(); //set query conditions ep.seteName("%A%"); ep.setStartDate(new Date(383155200000L)); ep.setEndDate(new Date());

Hibernate的几种查询方式-HQL,QBC,QBE,离线查询,复合查询,分页查询

HQL查询方式 这一种我最常用,也是最喜欢用的,因为它写起来灵活直观,而且与所熟悉的SQL的语法差不太多.条件查询.分页查询.连接查询.嵌套查询,写起来与SQL语法基本一致,唯一不同的就是把表名换成了类或者对象.其它的,包括一些查询函数(count(),sum()等).查询条件的设定等,全都跟SQL语法一样. 示例: Session session = SessionFactory.getCurrentSession(); User user = null; Transaction ts = s

动态查询列表页面的分页

方法一:在controller层中接受参数,并作为查询条件,在maybatis使用动态查询,多个查询条件可以放在一个map中,并且查询条件存进request域,在页面中使用el表达式字符串拼接来保持上一次的查询条件,可以像以下代码,但如果条件过多,则需要很多的代码,如果将查询条件放在map中传到前台,用set存放foreach处理过的条件(&key=value),也可以. ${rolename!=null?"&rolename=".concat(rolename):&q

SpringBoot中使用Spring Data Jpa 实现简单的动态查询的两种方法

首先谢谢大佬的简书文章:http://www.jianshu.com/p/45ad65690e33# 这篇文章中讲的是spring中使用spring data jpa,使用了xml配置文件.我现在使用的是spring boot ,没有了xml文件配置就方便多了.我同样尝试了两种方式,也都是简单的查询,需要更复杂的查询,还需要我研究研究.往下看,需要先配置springboot的开发环境,需要大致了解springboot,这里可以看下面两篇文章: springboot 项目新建 springboot

Hibernate(十)HQL查询二

一.数据库的emp名和dept表 建立持久化类和配置文件,可以用MyEclipse直接生成 持久化类 package entity; import java.util.Date; public class Emp implements java.io.Serializable { // Fields private Short empno; private Dept dept; private String ename; private String job; private Short mgr

spring data jpa的动态查询封装(转)

最近使用spring data jpa做了两个项目,对于动态查询的不友好做了个类似hibernate的封装,记录也分享下 首先定义一个所有条件的容器,继承Specification Java代码   /** * 定义一个查询条件容器 * @author lee * * @param <T> */ public class Criteria<T> implements Specification<T>{ private List<Criterion> crit