您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關(guān)在Spring項目中使用 Hibernate如何實現(xiàn)一個分頁功能,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
最關(guān)鍵的是運用Hibernate的query里面的兩個方法:
query.setFirstResult((p.getPage()-1)*p.getRows()); 指定從那個對象開始查詢,參數(shù)的索引位置是從0開始的。
query.setMaxResults(p.getRows()); 分頁時,一次最多產(chǎn)尋的對象數(shù) 主要實現(xiàn)類:
package com.paging; import java.util.List; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.SessionFactory; import com.user.User; import sun.nio.cs.US_ASCII; public class Paging { final int num=3; @Resource SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public List<User> paging(int index) { String hql = "from User"; Query query = sessionFactory.getCurrentSession().createQuery(hql); query.setFirstResult((index-1)*num); query.setMaxResults(num); return query.list(); } }
web層:
package com.web; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.paging.Paging; import com.user.User; @Controller @RequestMapping("/Page") public class Web { @Resource Paging paging; public void setPaging(Paging paging) { this.paging = paging; } @RequestMapping("/page") public String page(Model model,int index) { List<User> list = paging.paging(index); model.addAttribute("list", list); return "index"; } }
jsp頁面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>" rel="external nofollow" > <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" > --> </head> <body> <h2><a href="/Paging/Page/page?index=1" rel="external nofollow" >1</a></h2> <h2><a href="/Paging/Page/page?index=2" rel="external nofollow" >2</a></h2> <h2><a href="/Paging/Page/page?index=3" rel="external nofollow" >3</a></h2> <c:if test="${!empty list }"> <c:forEach items="${list}" var="list"> ${list.name} ${list.adderss} </c:forEach> </c:if> </body> </html>
以上就是在Spring項目中使用 Hibernate如何實現(xiàn)一個分頁功能,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降摹OM隳芡ㄟ^這篇文章學到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。