当前位置: 移动技术网 > IT编程>开发语言>Java > Hibernate框架数据分页技术实例分析

Hibernate框架数据分页技术实例分析

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

本文实例讲述了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程序设计有所帮助。

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

相关文章:

验证码:
移动技术网