Example analysis of Hibernate frame data paging technology _java

Source: Internet
Author: User
Tags int size first row

This article describes the Hibernate framework data paging technology. Share to everyone for your reference, specific as follows:

1. The basic idea of data paging mechanism:

(1) Determine the record span, that is, to determine the number of records displayed per page, depending on the actual situation.
(2) Gets the total number of records, that is, the total number of records to be displayed on the page, to determine the total number of distributions based on that number.
(3) Determine the total number of pages after pagination. Can be based on the formula: "Total number of pages = (Total records-1)/The number of records displayed per page + 1".
(4) Display the data according to the current page number. If the page is less than 1, make it equal to 1, or equal to the maximum number of pages if it is greater than the maximum number of pages.
(5) Displays the query results through a for, while loop statement distribution.

2. Get the first N records:

SQL syntax:

SELECT Top n from
table
WHERE ...
ORDER BY ...

For example: Get first 4 records

Select Top 4 * out car

3. Get the paging data:

String sql = ' select top ' +pagesize+ ' * from car where id '
(select top ' + (page-1) *pagesize+ ' ID from # ID ASC) ORDER by
ID ASC

The parameters are described below:

PageSize: Number of records displayed per page
Page: Current page
Car: Data table name

4.MySQL Database Paging

The MySQL database provides a limit function that allows you to easily implement data paging.
The limit function is used to limit the number of rows returned by a SELECT query statement.

Grammar:

SELECT ... From table
WHERE ...
ORDER BY ...
LIMIT [offset], rows

The parameters are described below:

Offset: Specifies the offset of the first row to be returned. The start line offset is 0. is optional.
Rows: Specifies the number of rows returned.

5.MySQL Get Paging data

/**
* *
@param page pages
* @param pagesize the number of records per page
* @return Returns the result set
/public
ResultSet FindOrder ( int page, int pagesize) {
  String strSQL = ' select * from car ' ORDER by ID limit ' + (page-1)
      * pagesize + "," + P Agesize + ""; Define SQL query Statement
  Statement pstmt = null;
  ResultSet rs = null; Define query result set object
  try {
    pstmt = conn.createstatement ();
    rs = Pstmt.executequery (strSQL); Execute query Statement
  } catch (Exception e) {
    e.printstacktrace ();
  } finally {
    try {
      if (pstmt!= null) {
   rs.close ();
        Pstmt.close ();
      }
    catch (Exception e) {
      e.printstacktrace ();
    }
  }
  Return RS; return result set
}

6. Sample Data pagination

6.1Paging Project Structure:

6.2car.java Program list:

Package com.cdd.util;
  /** * Vehicle information * @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 Program list:

Package com.cdd.util;
Import java.sql.*;
public class Getconn {
  static {
    try {
      class.forname ("Com.mysql.jdbc.Driver");//Implementation loading database driver in static block
    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 Program list:

Package com.cdd.util;
Import java.util.*;
Import java.sql.*;
  public class Paginationutil {getconn getconn = new Getconn ();
  Connection conn = Getconn.getconn (); Based on paging public List findgrade (int page, int pagesize) {String strSQL = ' select * from car ' ORDER by ID limit ' + (PA GE-1) * pagesize + "," + pagesize + "";
    Define SQL query statement Statement pstmt = null; ResultSet rs = null; Define query result set object List lstlist = new ArrayList ();
      Defines the collection object try {pstmt = Conn.createstatement (); rs = Pstmt.executequery (strSQL); Execute Query statement while (Rs.next ()) {//Loop traverse query result set car car = new car ()///Create 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); adding objects to the collection} catch (Exception e) {E.printStackTrace ();
          Finally {try {if (pstmt!= null) {rs.close ();
        Pstmt.close ();
      } catch (Exception e) {e.printstacktrace (); } return lstlist; Return query Collection Object}/** * * @param page pages * @param pagesize the number of records per page * @return return result set/public ResultSet F Indorder (int page, int pagesize) {String strSQL = ' select * from car ' ORDER by ID limit ' + (page-1) * pages Ize + "," + pagesize + "";
    Define SQL query statement Statement pstmt = null; ResultSet rs = null;
      Define query result set Object try {pstmt = Conn.createstatement (); rs = Pstmt.executequery (strSQL);
    Execute query statement} catch (Exception e) {e.printstacktrace ();
          Finally {try {if (pstmt!= null) {rs.close ();
        Pstmt.close ();
      } catch (Exception e) {e.printstacktrace (); } return RS;
    Returns the result set} 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 List of programs:

<%@ 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" >  

6.6 Access Address:

http://x-pc:8080/Paging/index.jsp

6.7 Running Results screenshot:

7.Hibernate Paging

7.1HQL Paging

HQL mainly through the Setfirstresult () method and the Setmaxresults () method to implement data paging.

(1) the Setfirstresult (int index) method retrieves the start index position of the data, and the index position starts at 0.

(2) the setmaxresults (int amount) method calculates the maximum number of record bars to load at a time, by default from the Set start index position to the last.

For example: Retrieves 5 records starting at index position 2

Query q = session.createquery ("form Car");
Q.setfirstresult (2);
Q.setmaxresults (5);

7.2QBC Paging

For example: Retrieves 5 records starting at index position 2

Criteria C = Session.createcriteria ("form Car");
C.setfirstresult (2);
C.setmaxresults (5);

7.3 Data Paging Method:

/** * Use HQL statement for paging query * @param hql The HQL statement that needs to be queried * @param offset the first record index * @param pageSize the number of records to be displayed per page * @return all records on the current page * * * PU Blic list findbypage (final String hql, final int offset, final int pageSize) {//Execute Query list L with a Hibernatecallback object ist = gethibernatetemplate (). Executefind (New Hibernatecallback () {//the method that the Hibernatecallback interface must implement public Ob  Ject Doinhibernate (Session session) throws Hibernateexception, SQLException {//execute Hibernate paging query List
      result = Session.createquery (HQL). Setfirstresult (offset). Setmaxresults (pageSize). List ();
    return result;
  }
  });
return list;
 /** * Use HQL statement for paging query * @param hql The HQL statement that needs to be queried * @param value if the HQL has a parameter that needs to be passed in, value is the parameter of the incoming HQL statement * @param offset first record index * @param pageSize the number of records to be displayed per page * @return all records for the current page/public List findbypage (final String hql, final Object value, fin Al int offset, final int pageSize) {//through a Hibernatecallback object to execute the query list List = GethibernatetemplatE (). Executefind (New Hibernatecallback () {//implements the method that the Hibernatecallback interface must implement the public Object doinhibernate (sessio N session) throws Hibernateexception, SQLException {//execute Hibernate paging query List result = Session.createq Uery (HQL)//is the HQL statement passed in the argument. Setparameter (0, value). Setfirstresult (offset). Setmaxresults (page
      Size). List ();
    return result;
  }
  });
return list; /** * Use HQL statement for paging query * @param hql The HQL statement that needs to be queried * @param values if the HQL has more than one parameter to pass in, values are the parameter array of the incoming HQL * @param offset first record
  Index * @param pageSize the number of records to display per page * @return all records for the current page/public List findbypage (final String hql, final object[] values, Final int offset, final int pageSize) {//execute query list = Gethibernatetemplate () through a Hibernatecallback object. execut
      Efind (New Hibernatecallback () {//the method that the Hibernatecallback interface must implement public Object Doinhibernate
   Throws Hibernateexception, SQLException {//execute Hibernate paging query   Query query = session.createquery (HQL);
      Pass in the argument for the HQL statement 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;

 }

Hopefully this article will help you with Java programming based on the Hibernate framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.