Hibernate数据库分页显示

 

在写这篇博客之前,先深深吸口气.因为这种弱智的分页显示会让很多JAVA的学习者嗤之以鼻.

我在网络上找了很多关于Hibernate分页的东西,一直得不到要领,又是些Pagebean又是什么东东的,结果把他们的代码复制过来,数据库建好,包导进去.........等我忙了半天之后,还是出错.

我是那种喜欢看着别人的代码,运行起来之后才去分析代码为什么这样.这样或者那样的页面效果是怎么样实现的.可是如果让我先看别人的代码,然后再运行,我不太喜欢.

于是今天豁出去了,做了一个分页的功能.

代码全部复制过来.尽量说一点废话解释下.(如果谁有完整的分页代码,请给我个连接.或者QQ461628072联系)

1.建立两个JSP页面(JSP页面需要用到Struts标签,所以要导入Struts-----我用的是struts1.X版本的.)

index.jsp 和 ss.jsp 代码如下

 

  1. <%@ taglib prefix="logic" uri="/WEB-INF/struts-logic.tld"%>  
  2. <%@ taglib prefix="bean" uri="/WEB-INF/struts-bean.tld"%>  
  3. <%@ taglib prefix="html" uri="/WEB-INF/struts-html.tld"%>  
  4. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  5. <%  
  6.     String path = request.getContextPath();  
  7.     String basePath = request.getScheme() + "://"  
  8.             + request.getServerName() + ":" + request.getServerPort()  
  9.             + path + "/";  
  10. %>  
  11. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  12. <html>  
  13.     <head>  
  14.         <base href="<%=basePath%>">  
  15.         <title>My JSP 'index.jsp' starting page</title>  
  16.         <meta http-equiv="pragma" content="no-cache">  
  17.         <meta http-equiv="cache-control" content="no-cache">  
  18.         <meta http-equiv="expires" content="0">  
  19.         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  20.         <meta http-equiv="description" content="This is my page">  
  21.         <!-- 
  22.     <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css"> 
  23.     -->  
  24.     </head>  
  25.     <body>  
  26.         <logic:notEmpty name="list">  
  27.             <logic:iterate id="ls" name="list">  
  28.                 <bean:write property="name" name="ls" />  
  29.             </logic:iterate>  
  30.         </logic:notEmpty>  
  31.         <html:link href="/page/search.do?action=firstPage&page=1" mce_href="page/search.do?action=firstPage&page=1">首页信息</html:link>  
  32.     </body>  
  33. </html>  
 

 

 

  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. <%@ taglib prefix="logic" uri="/WEB-INF/struts-logic.tld"%>  
  3. <%@ taglib prefix="bean" uri="/WEB-INF/struts-bean.tld"%>  
  4. <%@ taglib prefix="html" uri="/WEB-INF/struts-html.tld"%>  
  5. <%  
  6.     String path = request.getContextPath();  
  7.     String basePath = request.getScheme() + "://"  
  8.             + request.getServerName() + ":" + request.getServerPort()  
  9.             + path + "/";  
  10. %>  
  11. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  12. <html>  
  13.     <head>  
  14.         <base href="<%=basePath%>">  
  15.         <title>My JSP 'ss.jsp' starting page</title>  
  16.         <meta http-equiv="pragma" content="no-cache">  
  17.         <meta http-equiv="cache-control" content="no-cache">  
  18.         <meta http-equiv="expires" content="0">  
  19.         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  20.         <meta http-equiv="description" content="This is my page">  
  21.         <!-- 
  22.     <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css"> 
  23.     -->  
  24.     </head>  
  25.     <body>  
  26.         <logic:notEmpty name="list">  
  27.             <table bgcolor="green" width="400" border="0" cellspacing="1">  
  28.                 <logic:iterate id="ls" name="list">  
  29.                     <tr style="background-color: white; height: 30px;">  
  30.                         <td>  
  31.                             <bean:write property="name" name="ls" />  
  32.                         </td>  
  33.                         <td>  
  34.                             <bean:write property="sex" name="ls" />  
  35.                         </td>  
  36.                     </tr>  
  37.                 </logic:iterate>  
  38.             </table>  
  39.         </logic:notEmpty>  
  40.         <%  
  41.             String pg = (String) request.getAttribute("page");  
  42.             int pp = 0;  
  43.             if (pg != null || !pg.equals(""))  
  44.                 pp = Integer.parseInt(pg);  
  45.         %>  
  46.         当前显示的数据是<%=pp%>页  
  47.         <html:link href="/page/search.do?action=firstPage&page=1" mce_href="page/search.do?action=firstPage&page=1">首页信息</html:link>  
  48.         <%  
  49.             int last = pp - 1;  
  50.             String l = Integer.toString(last);  
  51.         %>  
  52.         <a href="/page/search.do?action=lastPage&page=<%=l%" mce_href="page/search.do?action=lastPage&page=<%=l%">>上一页</a>  
  53.         <%  
  54.             int next = pp + 1;  
  55.             String n = Integer.toString(next);  
  56.         %>  
  57.         <a href="/page/search.do?action=nextPage&page=<%=n%" mce_href="page/search.do?action=nextPage&page=<%=n%">>下一页</a>  
  58.         <html:link href="/page/search.do?action=endPage" mce_href="page/search.do?action=endPage">最后一页</html:link>  
  59.     </body>  
  60. </html>  
 

 

JSP页面完成之后,就是关于Hibernate类的东东了.

TUser.java代码 (这些代码都是使用MyEclipse6.0 自动生成的,不是自己写的.

(以下HibernateSessionFactory.java hibernate.cfg.xml /TUser.hbm.xml 也都是通过自动生成的,如果你懒得生成,全部复制过去.)

 

  1. package hibernate;  
  2. /** 
  3.  * TUser entity. 
  4.  *  
  5.  * @author MyEclipse Persistence Tools 
  6.  */  
  7. public class TUser implements java.io.Serializable {  
  8.     // Fields  
  9.     private Integer id;  
  10.     private String name;  
  11.     private String sex;  
  12.     // Constructors  
  13.     /** default constructor */  
  14.     public TUser() {  
  15.     }  
  16.     /** minimal constructor */  
  17.     public TUser(Integer id) {  
  18.         this.id = id;  
  19.     }  
  20.     /** full constructor */  
  21.     public TUser(Integer id, String name, String sex) {  
  22.         this.id = id;  
  23.         this.name = name;  
  24.         this.sex = sex;  
  25.     }  
  26.     // Property accessors  
  27.     public Integer getId() {  
  28.         return this.id;  
  29.     }  
  30.     public void setId(Integer id) {  
  31.         this.id = id;  
  32.     }  
  33.     public String getName() {  
  34.         return this.name;  
  35.     }  
  36.     public void setName(String name) {  
  37.         this.name = name;  
  38.     }  
  39.     public String getSex() {  
  40.         return this.sex;  
  41.     }  
  42.     public void setSex(String sex) {  
  43.         this.sex = sex;  
  44.     }  
  45. }  
 

 

HibernateSessionFactory.java代码

 

  1. package hibernate;  
  2. import org.hibernate.HibernateException;  
  3. import org.hibernate.Session;  
  4. import org.hibernate.cfg.Configuration;  
  5. /** 
  6.  * Configures and provides access to Hibernate sessions, tied to the 
  7.  * current thread of execution.  Follows the Thread Local Session 
  8.  * pattern, see {@link http://hibernate.org/42.html }. 
  9.  */  
  10. public class HibernateSessionFactory {  
  11.     /**  
  12.      * Location of hibernate.cfg.xml file. 
  13.      * Location should be on the classpath as Hibernate uses   
  14.      * #resourceAsStream style lookup for its configuration file.  
  15.      * The default classpath location of the hibernate config file is  
  16.      * in the default package. Use #setConfigFile() to update  
  17.      * the location of the configuration file for the current session.    
  18.      */  
  19.     private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";  
  20.     private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();  
  21.     private  static Configuration configuration = new Configuration();  
  22.     private static org.hibernate.SessionFactory sessionFactory;  
  23.     private static String configFile = CONFIG_FILE_LOCATION;  
  24.     static {  
  25.         try {  
  26.             configuration.configure(configFile);  
  27.             sessionFactory = configuration.buildSessionFactory();  
  28.         } catch (Exception e) {  
  29.             System.err  
  30.                     .println("%%%% Error Creating SessionFactory %%%%");  
  31.             e.printStackTrace();  
  32.         }  
  33.     }  
  34.     private HibernateSessionFactory() {  
  35.     }  
  36.       
  37.     /** 
  38.      * Returns the ThreadLocal Session instance.  Lazy initialize 
  39.      * the <code>SessionFactory</code> if needed. 
  40.      * 
  41.      *  @return Session 
  42.      *  @throws HibernateException 
  43.      */  
  44.     public static Session getSession() throws HibernateException {  
  45.         Session session = (Session) threadLocal.get();  
  46.         if (session == null || !session.isOpen()) {  
  47.             if (sessionFactory == null) {  
  48.                 rebuildSessionFactory();  
  49.             }  
  50.             session = (sessionFactory != null) ? sessionFactory.openSession()  
  51.                     : null;  
  52.             threadLocal.set(session);  
  53.         }  
  54.         return session;  
  55.     }  
  56.     /** 
  57.      *  Rebuild hibernate session factory 
  58.      * 
  59.      */  
  60.     public static void rebuildSessionFactory() {  
  61.         try {  
  62.             configuration.configure(configFile);  
  63.             sessionFactory = configuration.buildSessionFactory();  
  64.         } catch (Exception e) {  
  65.             System.err  
  66.                     .println("%%%% Error Creating SessionFactory %%%%");  
  67.             e.printStackTrace();  
  68.         }  
  69.     }  
  70.     /** 
  71.      *  Close the single hibernate session instance. 
  72.      * 
  73.      *  @throws HibernateException 
  74.      */  
  75.     public static void closeSession() throws HibernateException {  
  76.         Session session = (Session) threadLocal.get();  
  77.         threadLocal.set(null);  
  78.         if (session != null) {  
  79.             session.close();  
  80.         }  
  81.     }  
  82.     /** 
  83.      *  return session factory 
  84.      * 
  85.      */  
  86.     public static org.hibernate.SessionFactory getSessionFactory() {  
  87.         return sessionFactory;  
  88.     }  
  89.     /** 
  90.      *  return session factory 
  91.      * 
  92.      *  session factory will be rebuilded in the next call 
  93.      */  
  94.     public static void setConfigFile(String configFile) {  
  95.         HibernateSessionFactory.configFile = configFile;  
  96.         sessionFactory = null;  
  97.     }  
  98.     /** 
  99.      *  return hibernate configuration 
  100.      * 
  101.      */  
  102.     public static Configuration getConfiguration() {  
  103.         return configuration;  
  104.     }  
  105. }  
 

 

接着是配置文件: TUser.hbm.xml

 

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
  3. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  4. <!--  
  5.     Mapping file autogenerated by MyEclipse Persistence Tools 
  6. -->  
  7. <hibernate-mapping>  
  8.     <class name="hibernate.TUser" table="t_user" catalog="test">  
  9.         <id name="id" type="java.lang.Integer">  
  10.             <column name="id" />  
  11.             <generator class="assigned" />  
  12.         </id>  
  13.         <property name="name" type="java.lang.String">  
  14.             <column name="name" length="50" />  
  15.         </property>  
  16.         <property name="sex" type="java.lang.String">  
  17.             <column name="sex" length="11" />  
  18.         </property>  
  19.     </class>  
  20. </hibernate-mapping>  
 

 

配置文件:hibernate.cfg.xml

 

  1. <?xml version='1.0' encoding='UTF-8'?>  
  2. <!DOCTYPE hibernate-configuration PUBLIC  
  3.           "-//Hibernate/Hibernate Configuration DTD 3.0//EN"  
  4.           "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">  
  5. <!-- Generated by MyEclipse Hibernate Tools.                   -->  
  6. <hibernate-configuration>  
  7.     <session-factory>  
  8.         <property name="connection.username">root</property>  
  9.         <property name="connection.url">  
  10.             jdbc:mysql://localhost:3306/MySQL  
  11.         </property>  
  12.         <property name="dialect">  
  13.             org.hibernate.dialect.MySQLDialect  
  14.         </property>  
  15.         <property name="myeclipse.connection.profile">MySQL</property>  
  16.         <property name="connection.password">root</property>  
  17.         <property name="connection.driver_class">  
  18.             com.mysql.jdbc.Driver  
  19.         </property>  
  20.         <mapping resource="hibernate/TUser.hbm.xml" />  
  21.     </session-factory>  
  22. </hibernate-configuration>  
 

 

接着我写了一个DAO .只有一个查询的方法:UserDAO.JAVA

  1. package hibernate;  
  2. import org.hibernate.Query;  
  3. import org.hibernate.Session;  
  4. /******************************************************************************* 
  5.  * @Auther 李成 
  6.  * @Create_Date Apr 20, 2009 4:02:24 PM 
  7.  * @Company 昆明英聚科技有限责任公司 
  8.  ******************************************************************************/  
  9. public class UserDAO {  
  10.     /** 
  11.      * 获取所有用户的信息,返回类型为Query. 
  12.      *  
  13.      * @return 
  14.      */  
  15.     public Query getUserQuery() {  
  16.         Session session = HibernateSessionFactory.getSession();  
  17.         String hql = "from TUser";  
  18.         Query query = session.createQuery(hql);  
  19.         return query;  
  20.     }  
  21. }  
 

 

接下来的代码全部是我自己写的.大家可以先行复制,然后部署到项目里面.

PageBean.java

 

  1. package page.page;  
  2. import java.util.List;  
  3. import org.hibernate.Query;  
  4. /******************************************************************************* 
  5.  * @Auther 李成 
  6.  * @Create_Date Apr 20, 2009 4:04:38 PM 
  7.  * @Company 昆明英聚科技有限责任公司 
  8.  ******************************************************************************/  
  9. public class PageBean {  
  10.     private int pagesize = 5// 每页显示5条数据.  
  11.     /** 
  12.      * 获取到指定页的信息 
  13.      *  
  14.      * @param query 
  15.      * @param page 
  16.      * @return 
  17.      */  
  18.     public List getNumberPage(Query query, int page) {  
  19.         List list = query.setFirstResult((page - 1) * pagesize).setMaxResults(  
  20.                 pagesize).list();  
  21.         return list;  
  22.     }  
  23. }  
 

 

SearchForm.java

 

  1. package page.action;  
  2. import org.apache.struts.action.ActionForm;  
  3. public class SearchForm extends ActionForm {  
  4.     private String action;  
  5.     private String page;  
  6.     public String getAction() {  
  7.         return action;  
  8.     }  
  9.     public void setAction(String action) {  
  10.         this.action = action;  
  11.     }  
  12.     public String getPage() {  
  13.         return page;  
  14.     }  
  15.     public void setPage(String page) {  
  16.         this.page = page;  
  17.     }  
  18. }  
 

 

SearchAction.java

 

  1. package page.action;  
  2. import hibernate.UserDAO;  
  3. import java.util.List;  
  4. import javax.servlet.http.HttpServletRequest;  
  5. import javax.servlet.http.HttpServletResponse;  
  6. import org.apache.struts.action.Action;  
  7. import org.apache.struts.action.ActionForm;  
  8. import org.apache.struts.action.ActionForward;  
  9. import org.apache.struts.action.ActionMapping;  
  10. import org.hibernate.Query;  
  11. import page.page.PageBean;  
  12. import page.service.SearchService;  
  13. /******************************************************************************* 
  14.  * @Auther 李成 
  15.  * @Create_Date Apr 20, 2009 4:17:22 PM 
  16.  * @Company 昆明英聚科技有限责任公司 
  17.  ******************************************************************************/  
  18. public class SearchAction extends Action {  
  19.     @Override  
  20.     public ActionForward execute(ActionMapping mapping, ActionForm form,  
  21.             HttpServletRequest request, HttpServletResponse response)  
  22.             throws Exception {  
  23.         // TODO Auto-generated method stub  
  24.         SearchForm searchForm = (SearchForm) form;  
  25.         String action = searchForm.getAction();  
  26.         String page = searchForm.getPage();  
  27.         System.out.println("action = " + action + " and page = " + page);  
  28.         UserDAO dao = new UserDAO();  
  29.         Query query = dao.getUserQuery();  
  30.         if (action.equals("firstPage")) {  
  31.             SearchService service = new SearchService();  
  32.             List<Object> list = service.getList(query, page);  
  33.             request.setAttribute("page""1");  
  34.             request.setAttribute("list", list);  
  35.         } else if (action.equals("lastPage") || action.equals("nextPage")) { // 获得上一页/下一页的数据  
  36.             SearchService service = new SearchService();  
  37.             List<Object> list = service.getList(query, page);  
  38.             request.setAttribute("page", page);  
  39.             request.setAttribute("list", list);  
  40.         } else {  
  41.             request.setAttribute("page""1");  
  42.         }  
  43.         return mapping.findForward("success");  
  44.     }  
  45. }  
 

 

SearchService.java

 

  1. package page.service;  
  2. import java.util.List;  
  3. import org.hibernate.Query;  
  4. import page.page.PageBean;  
  5. /******************************************************************************* 
  6.  * @Auther 李成 
  7.  * @Create_Date Apr 20, 2009 4:20:23 PM 
  8.  * @Company 昆明英聚科技有限责任公司 
  9.  ******************************************************************************/  
  10. public class SearchService {  
  11.     public List<Object> getList(Query query, String page) {  
  12.         List<Object> list = null;  
  13.         PageBean bean = new PageBean();  
  14.         int pa = Integer.parseInt(page); // 把字符串的页数转换成整数  
  15.         list = bean.getNumberPage(query, pa);  
  16.         return list;  
  17.     }  
  18. }  
 

 

最后是配置文件:

struts-config.xml

 

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">  
  3. <struts-config>  
  4.     <data-sources />  
  5.     <form-beans>  
  6.         <form-bean name="form" type="page.action.SearchForm"></form-bean>  
  7.     </form-beans>  
  8.     <global-exceptions />  
  9.     <global-forwards />  
  10.     <action-mappings>  
  11.         <action path="/search" name="form"  
  12.             type="page.action.SearchAction">  
  13.             <forward name="success" path="/ss.jsp"></forward>  
  14.         </action>  
  15.     </action-mappings>  
  16.     <message-resources parameter="ApplicationResources" />  
  17. </struts-config>  
 

 

web.xml

 

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  3.   <servlet>  
  4.     <servlet-name>action</servlet-name>  
  5.     <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>  
  6.     <init-param>  
  7.       <param-name>config</param-name>  
  8.       <param-value>/WEB-INF/struts-config.xml</param-value>  
  9.     </init-param>  
  10.     <init-param>  
  11.       <param-name>debug</param-name>  
  12.       <param-value>3</param-value>  
  13.     </init-param>  
  14.     <init-param>  
  15.       <param-name>detail</param-name>  
  16.       <param-value>3</param-value>  
  17.     </init-param>  
  18.     <load-on-startup>0</load-on-startup>  
  19.   </servlet>  
  20.   <servlet-mapping>  
  21.     <servlet-name>action</servlet-name>  
  22.     <url-pattern>*.do</url-pattern>  
  23.   </servlet-mapping>  
  24.   <welcome-file-list>  
  25.     <welcome-file>index.jsp</welcome-file>  
  26.   </welcome-file-list>  
  27. </web-app>  
 

 

我实现的效果如下..................................

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值