Hibernate框架數據分頁技巧實例剖析。本站提示廣大學習愛好者:(Hibernate框架數據分頁技巧實例剖析)文章只能為提供參考,不一定能成為您想要的結果。以下是Hibernate框架數據分頁技巧實例剖析正文
本文實例講述了Hibernate框架數據分頁技巧。分享給年夜家供年夜家參考,詳細以下:
1.數據分頁機制根本思惟:
(1)肯定記載跨度,即肯定每頁顯示的記載條數,可依據現實情形而定。
(2)獲得記載總數,即獲得要顯示在頁面中的總記載數,其目標是依據該數來肯定總的散布數。
(3)肯定分頁後的總頁數。可依據公式:“總頁數=(總記載數 - 1) / 每頁顯示的記載數 + 1”。
(4)依據以後頁數顯示數據。假如該頁數小於1,則使其等於1;假如年夜於最年夜頁數,則使其等於最年夜頁數。
(5)經由過程For、While輪回語句散布顯示查詢成果。
2.獲得前n筆記錄:
SQL語法:
SELECT TOP n FROM table WHERE ... ORDER BY ...
例如:獲得前4筆記錄
select top 4 * from car
3.獲得分頁數據:
String sql = "select top"+pagesize+"* from car where id not in (select top "+(page-1)*pagesize+"id from car order by id ASC) order by id ASC
個中參數解釋以下:
pagesize:每頁顯示的記載數
page:以後頁數
car:數據表名
4.MySQL 數據庫分頁
MySQL數據庫供給了LIMIT函數,應用該函數可輕松完成數據分頁。
LIMIT函數用來限制SELECT查詢語句前往的行數。
語法:
SELECT ...FROM table WHERE... ORDER BY ... LIMIT [offset], rows
個中參數解釋以下:
offset:指定要前往的第一行的偏移量。開端行的偏移量是0。是可選的。
rows:指定前往行的數量。
5.MySQL獲得分頁數據
/** * * @param page 第幾頁 * @param pagesize 每頁顯示記載數 * @return 前往成果集 */ public ResultSet findOrder(int page, int pagesize) { String strSql = "select * from car order by id limit " + (page - 1) * pagesize + "," + pagesize + ""; // 界說SQL查詢語句 Statement pstmt = null; ResultSet rs = null; // 界說查詢成果集對象 try { pstmt = conn.createStatement(); rs = pstmt.executeQuery(strSql); // 履行查詢語句 } catch (Exception e) { e.printStackTrace(); } finally { try { if (pstmt != null) { rs.close(); pstmt.close(); } } catch (Exception e) { e.printStackTrace(); } } return rs; // 前往成果集 }
6.數據分頁示例
6.1Paging項目構造:
6.2Car.java法式清單:
package com.cdd.util; /** * 車輛信息 * @author Xu Qiao Hui * */ public class Car { private String Id; private String name;; private String brand; private String engineNum; private String state; private String remarks; public Car(int size){} public Car(){} public Car(String id, String name, String brand, String engineNum, String state, String remarks) { super(); Id = id; this.name = name; this.brand = brand; this.engineNum = engineNum; this.state = state; this.remarks = remarks; } public String getId() { return Id; } public void setId(String id) { Id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getEngineNum() { return engineNum; } public void setEngineNum(String engineNum) { this.engineNum = engineNum; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } }
6.3GetConn.java法式清單:
package com.cdd.util; import java.sql.*; public class GetConn { static { try { Class.forName("com.mysql.jdbc.Driver"); // 靜態塊中完成加載數據庫驅動 } catch (ClassNotFoundException e) { e.printStackTrace(); } } public Connection getConn() { Connection connection = null; String url = "jdbc:mysql://localhost:3306/oa"; String userName = "root"; String passWord = "1120"; try { connection = DriverManager.getConnection(url, userName, passWord); System.out.println("ok"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return connection; } public static void main(String[] args) { GetConn getConn = new GetConn(); getConn.getConn(); } }
6.4PaginationUtil.java法式清單:
package com.cdd.util; import java.util.*; import java.sql.*; public class PaginationUtil { GetConn getConn = new GetConn(); Connection conn = getConn.getConn(); // 依據分頁 public List findGrade(int page, int pagesize) { String strSql = "select * from car order by id limit " + (page - 1) * pagesize + "," + pagesize + ""; // 界說SQL查詢語句 Statement pstmt = null; ResultSet rs = null; // 界說查詢成果集對象 List lstList = new ArrayList(); // 界說聚集對象 try { pstmt = conn.createStatement(); rs = pstmt.executeQuery(strSql); // 履行查詢語句 while (rs.next()) { // 輪回遍歷查詢成果集 Car car = new Car(); // 創立car car.setId(rs.getString("Id")); car.setName(rs.getString("name")); car.setBrand(rs.getString("brand")); car.setEngineNum(rs.getString("engineNum")); car.setState(rs.getString("state")); car.setRemarks(rs.getString("remarks")); lstList.add(car); // 向聚集中添加對象 } } catch (Exception e) { e.printStackTrace(); } finally { try { if (pstmt != null) { rs.close(); pstmt.close(); } } catch (Exception e) { e.printStackTrace(); } } return lstList; // 前往查詢聚集對象 } /** * * @param page 第幾頁 * @param pagesize 每頁顯示記載數 * @return 前往成果集 */ public ResultSet findOrder(int page, int pagesize) { String strSql = "select * from car order by id limit " + (page - 1) * pagesize + "," + pagesize + ""; // 界說SQL查詢語句 Statement pstmt = null; ResultSet rs = null; // 界說查詢成果集對象 try { pstmt = conn.createStatement(); rs = pstmt.executeQuery(strSql); // 履行查詢語句 } catch (Exception e) { e.printStackTrace(); } finally { try { if (pstmt != null) { rs.close(); pstmt.close(); } } catch (Exception e) { e.printStackTrace(); } } return rs; // 前往成果集 } public int allPage(int pagesize) { int allp = 0; try { Statement pstmt = conn.createStatement(); pstmt.execute("select count(*) from car"); ResultSet rs = pstmt.getResultSet(); System.out.print("00"); rs.next(); int all = rs.getInt(1); System.out.print(all); allp = (all - 1) / pagesize + 1; System.out.println(allp); } catch (SQLException e) { e.printStackTrace(); } return allp; } public static void main(String[] args) { PaginationUtil pageinationUtil = new PaginationUtil(); List list = pageinationUtil.findGrade(2, 6); for (int i = 0; i < list.size(); i++) { Car car = (Car) list.get(i); System.out.println(car.getId() + " " + car.getName()); } } }
6.5index.jsp法式清單:
<%@ page language="java" import="java.util.*,com.cdd.util.*;" pageEncoding="gbk"%> <% 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%>"> <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"> --> </head> <body> <center> <h5> 車輛信息分頁顯示 </h5> </center> <table width="400" height="44" border="1" align="center" bordercolor="#CC00CC" class="unnamed1"> <tr> <td width="83"> 車商標 </td> <td width="67"> 車輛稱號 </td> <td width="67"> 品牌 </td> <td width="67"> 動員機編號 </td> </tr> <% PaginationUtil paginationUtil = new PaginationUtil(); int pageNo = 0; if (request.getParameter("No") == null) { pageNo = 1; } else { pageNo = Integer.parseInt(request.getParameter("No")); } List cc = paginationUtil.findGrade(pageNo, 3); Iterator i = cc.iterator(); while (i.hasNext()) { Car car = (Car) i.next(); out.print("<tr><td>" + car.getId() + "</td>" + "<td>" + car.getName() + "</td>" + "<td>" + car.getBrand() + "</td>" + "<td>" + car.getEngineNum() + "</td></tr>"); } int all = paginationUtil.allPage(3); %> </table> <center> 共<%=all%>頁,以後頁是第<%=pageNo%>頁 <% if (pageNo > 1) { %> <a href="index.jsp?No=<%=pageNo - 1%>">上一頁</a> <% } %> <% if (pageNo < all) { %> <a href="index.jsp?No=<%=pageNo + 1%>">下一頁</a> <% } %> </center> </body> </html>
6.6拜訪地址:
http://x-pc:8080/Paging/index.jsp
6.7運轉成果截圖:
7.Hibernate分頁
7.1HQL分頁
HQL重要是經由過程setFirstResult()辦法與setMaxResults()辦法來完成數據分頁。
(1)setFirstResult(int index)辦法 用於檢索數據開端索引地位,索引地位肇端值為0。
(2)setMaxResults(int amount) 辦法用於盤算每次最多加載的記載條數,默許情形下從設定的開端索引地位到最初。
例如:檢索出從索引地位2開端的5筆記錄
Query q = session.createQuery("form car"); q.setFirstResult(2); q.setMaxResults(5);
7.2QBC分頁
例如:檢索出從索引地位2開端的5筆記錄
Criteria c = session.createCriteria("form car"); c.setFirstResult(2); c.setMaxResults(5);
7.3 數據分頁辦法:
/** * 應用hql語句停止分頁查詢 * @param hql 須要查詢的hql語句 * @param offset 第一筆記錄索引 * @param pageSize 每頁須要顯示的記載數 * @return 以後頁的一切記載 */ public List findByPage(final String hql, final int offset, final int pageSize) { //經由過程一個HibernateCallback對象來履行查詢 List list = getHibernateTemplate() .executeFind(new HibernateCallback() { //完成HibernateCallback接口必需完成的辦法 public Object doInHibernate(Session session) throws HibernateException, SQLException { //履行Hibernate分頁查詢 List result = session.createQuery(hql) .setFirstResult(offset) .setMaxResults(pageSize) .list(); return result; } }); return list; } /** * 應用hql語句停止分頁查詢 * @param hql 須要查詢的hql語句 * @param value 假如hql有一個參數須要傳入,value就是傳入hql語句的參數 * @param offset 第一筆記錄索引 * @param pageSize 每頁須要顯示的記載數 * @return 以後頁的一切記載 */ public List findByPage(final String hql , final Object value , final int offset, final int pageSize) { //經由過程一個HibernateCallback對象來履行查詢 List list = getHibernateTemplate() .executeFind(new HibernateCallback() { //完成HibernateCallback接口必需完成的辦法 public Object doInHibernate(Session session) throws HibernateException, SQLException { //履行Hibernate分頁查詢 List result = session.createQuery(hql) //為hql語句傳入參數 .setParameter(0, value) .setFirstResult(offset) .setMaxResults(pageSize) .list(); return result; } }); return list; } /** * 應用hql語句停止分頁查詢 * @param hql 須要查詢的hql語句 * @param values 假如hql有多個個參數須要傳入,values就是傳入hql的參數數組 * @param offset 第一筆記錄索引 * @param pageSize 每頁須要顯示的記載數 * @return 以後頁的一切記載 */ public List findByPage(final String hql, final Object[] values, final int offset, final int pageSize) { //經由過程一個HibernateCallback對象來履行查詢 List list = getHibernateTemplate() .executeFind(new HibernateCallback() { //完成HibernateCallback接口必需完成的辦法 public Object doInHibernate(Session session) throws HibernateException, SQLException { //履行Hibernate分頁查詢 Query query = session.createQuery(hql); //為hql語句傳入參數 for (int i = 0 ; i < values.length ; i++) { query.setParameter( i, values[i]); } List result = query.setFirstResult(offset) .setMaxResults(pageSize) .list(); return result; } }); return list; }
願望本文所述對年夜家基於Hibernate框架的Java法式設計有所贊助。