用Hibernate實現分頁查詢

分頁查詢就是把數據庫中某張表的記錄數進行分頁查詢,在作分頁查詢時會有一個Page類,下面是一個Page類,我對其作了詳細的註解:java

 1 package com.entity;
 2 /**
 3  * @author:秦林森
 4  */
 5 
 6 import javax.persistence.criteria.CriteriaBuilder;
 7 
 8 public class Page {
 9     /**
10      *  其中currentPage,perPageRows這兩個參數是作分頁查詢必須具有的參數
11      *  緣由是:hibernate中的Criteria或則是Query這兩個接口:都有setFirstResult(Integer firstResult)
12      *  和setMaxResult(Integer maxResult),
13      *  這裏的firstResult就是每頁的開始的索引數:
14      *  每頁開始的索引數的計算公式是:(currentPage-1)*perPageRows+1,(這是相對索引從1開始的)
15      *  可是Hibernate中的firstResult的索引是從0開始的,因此在hibernate中每頁開始的索引數的計算公式是:
16      *  (currentPage-1)*perPageRows+1-1=(currentPge-1)*perPageRows.
17      *
18      *  maxResult就是每頁能查詢的最大記錄數:也就是perPageRows.
19      *
20      *  Math.ceil(totalRows/perPageRows)==totalPages;//這是根據總記錄數和每頁的記錄數算出總頁數的計算公式。
21      */
22     private Integer currentPage;//當前頁
23     private Integer perPageRows;//每頁的記錄數
24     private Integer totalRows;//總記錄數:
25     private Integer totalPages;//總頁數:
26     public Integer getCurrentPage() {
27         return currentPage;
28     }
29 
30     public void setCurrentPage(Integer currentPage) {
31         this.currentPage = currentPage;
32     }
33 
34     public Integer getPerPageRows() {
35         return perPageRows;
36     }
37 
38     public void setPerPageRows(Integer perPageRows) {
39         this.perPageRows = perPageRows;
40     }
41 
42     public Integer getTotalRows() {
43         return totalRows;
44     }
45 
46     public void setTotalRows(Integer totalRows) {
47         this.totalRows = totalRows;
48     }
49 
50     public Integer getTotalPages() {
51         return totalPages;
52     }
53 
54     public void setTotalPages(Integer totalPages) {
55         this.totalPages = totalPages;
56     }
57 }

下面用Hibernate的Criteira接口進行查詢:mysql

對應的實體類Employee的代碼以下:sql

 1 package com.entity;
 2 
 3 import javax.persistence.*;
 4 
 5 @Entity
 6 @Table(name = "EMPLOYEE")
 7 public class Employee {
 8     @Id
 9     @GeneratedValue(strategy = GenerationType.IDENTITY)
10     private int id;
11     @Column(name = "first_name")
12     private String firstName;
13     @Column(name = "last_name")
14     private String lastName;
15     @Column(name = "salary")
16     private int salary;
17     //a constructor with no arguments
18 
19 
20     public Employee() {
21     }
22 
23     public int getId() {
24         return id;
25     }
26 
27     public void setId(int id) {
28         this.id = id;
29     }
30 
31     public String getFirstName() {
32         return firstName;
33     }
34 
35     public void setFirstName(String firstName) {
36         this.firstName = firstName;
37     }
38 
39     public String getLastName() {
40         return lastName;
41     }
42 
43     public void setLastName(String lastName) {
44         this.lastName = lastName;
45     }
46 
47     public int getSalary() {
48         return salary;
49     }
50 
51     public void setSalary(int salary) {
52         this.salary = salary;
53     }
54 }

 //建立EMPLOYEE表的sql語句是:數據庫

create table EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   salary     INT  default NULL,
   PRIMARY KEY (id)
);

 

首先在寫一個配置文件:hibernate.cfg.xml用於鏈接數據庫;session

hibernate.cfg.xml的代碼以下:app

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-5.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">130850a,</property>
        <property name="hibernate.connection.pool_size">10</property>
        <property name="show_sql">true</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.current_session_context_class">thread</property>

        <mapping class="com.entity.Employee" />

    </session-factory>
</hibernate-configuration>

在寫一個用於啓動Hibernate的util類:HibernateUtil的代碼以下:ui

 1 package com.util;
 2 import org.hibernate.SessionFactory;
 3 import org.hibernate.boot.Metadata;
 4 import org.hibernate.boot.MetadataSources;
 5 import org.hibernate.boot.registry.StandardServiceRegistry;
 6 import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
 7 import org.hibernate.cfg.Configuration;
 8 import org.hibernate.service.ServiceRegistry;
 9 public class HibernateUtil {
10     private static final SessionFactory sessionFactory;
11 
12     private static ServiceRegistry serviceRegistry;
13 
14     static {
15         try {
16             StandardServiceRegistry standardRegistry =
17                     new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
18             Metadata metaData =
19                     new MetadataSources(standardRegistry).getMetadataBuilder().build();
20             sessionFactory = metaData.getSessionFactoryBuilder().build();
21         } catch (Throwable th) {
22 
23             System.err.println("Enitial SessionFactory creation failed" + th);
24             throw new ExceptionInInitializerError(th);
25 
26         }
27     }
28     public static SessionFactory getSessionFactory() {
29 
30         return sessionFactory;
31 
32     }
33 }

最後是分頁查詢的代碼,代碼以下:this

 1 package com.hibDemo;
 2 
 3 import com.entity.Employee;
 4 import com.entity.Page;
 5 import com.util.HibernateUtil;
 6 import org.hibernate.Criteria;
 7 import org.hibernate.Session;
 8 import org.hibernate.SessionFactory;
 9 import org.hibernate.Transaction;
10 
11 import java.util.List;
12 
13 public class PaginationQuery {
14 
15     public void paginationByCriteria(){
16         SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
17         Session session = sessionFactory.getCurrentSession();
18         Transaction tx=null;
19         try {
20             //do some work
21             tx=session.beginTransaction();
22             Page page = new Page();
23             /**
24              * 假設如今查詢的是第一頁,每頁查詢的最大記錄數是3.
25              */
26             page.setCurrentPage(1);
27             page.setPerPageRows(3);
28             Criteria criteria = session.createCriteria(Employee.class);
29             Integer currentPage = page.getCurrentPage();//獲得當前頁
30             Integer perPageRows = page.getPerPageRows();//獲得每頁的記錄數:
31             /**
32              * 在Page類中我已說明了:每頁開始的索引數在hibernate中的計算公式是:(currentPage-1)*perPageRows
33              */
34             criteria.setFirstResult((currentPage-1)*perPageRows);
35             criteria.setMaxResults(perPageRows);
36             List<Employee> employees = criteria.list();
37             for(Employee employee:employees){
38                 System.out.println("*********************");
39                 System.out.println("id="+employee.getId()+" firstName="+employee.getFirstName()+" lastName="+employee.getLastName());
40             }
41             tx.commit();
42 
43         } catch (Exception e) {
44             if(tx!=null){
45                 tx.rollback();
46             }
47             e.printStackTrace();
48         } finally {
49             session.close();//關閉流,必定要關閉,否則會影響運行速度。
50         }
51     }
52     public static void main(String[] args) {
53         PaginationQuery paginationQuery = new PaginationQuery();
54         paginationQuery.paginationByCriteria();
55     }
56 }

總結:這個Page類爲Hibernate中setFirstResult,和setMaxResult服務的,抓住這個就能夠了。代碼能夠隨便寫。url

相關文章
相關標籤/搜索