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

Posted 如风105

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用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;

 

以上是关于用hibernate实现动态查询+分页的模板,适合于所有的页面的主要内容,如果未能解决你的问题,请参考以下文章

如何用 Hibernate 实现分页查询

Oracle -Mybatis动态SQL查询分页的实现

SSH hibernate 分页的几种实现方式

(JAVA)从数据库查出所有数据再分页的方法

请高人讲解java ajax实现分页的思路

hibernate实现分页