本篇文章给大家分享的是有关在Spring项目中使用 Hibernate如何实现一个分页功能,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
最关键的是运用Hibernate的query里面的两个方法:
query.setFirstResult((p.getPage()-1)*p.getRows()); 指定从那个对象开始查询,参数的索引位置是从0开始的。
query.setMaxResults(p.getRows()); 分页时,一次最多产寻的对象数 主要实现类:
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如何实现一个分页功能,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。