当前位置: 移动技术网 > IT编程>开发语言>Java > Spring Hibernate实现分页功能

Spring Hibernate实现分页功能

2019年07月22日  | 移动技术网IT编程  | 我要评论

本实例采用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>
 <h1><a href="/paging/page/page?index=1" rel="external nofollow" >1</a></h1>
 <h1><a href="/paging/page/page?index=2" rel="external nofollow" >2</a></h1>
 <h1><a href="/paging/page/page?index=3" rel="external nofollow" >3</a></h1>
 
 <c:if test="${!empty list }">
 <c:foreach items="${list}" var="list">
 
 ${list.name}
 ${list.adderss}
 
 
 
     </c:foreach>
 </c:if>
 



 </body>
</html>

因为是简单例子所以界面就很简陋了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网