之前给大家介绍了一下hibernate框架,那么下面要接着讲到的就是hibernate实现分页查询的内容,一起来看看具体的实现方式吧。
分页查询就是将数据库当中某一张表的记录数进行分页查询,在做分页查询时会有一个Page类,下面是一个Page类。
大家可以仔细看看,有非常详细的注解。package com.entity;
/**
* @author:秦林森
*/
import javax.persistence.criteria.CriteriaBuilder;
public class Page
{
/**
* 其中currentPage,perPageRows这两个参数是做分页查询必须具备的参数
* 原因是:hibernate中的Criteria或则是Query这两个接口:都有setFirstResult(Integer firstResult)
* 和setMaxResult(Integer maxResult),
* 这里的firstResult就是每页的开始的索引数:
* 每页开始的索引数的计算公式是:(currentPage-1)*perPageRows+1,(这是相对索引从1开始的)
* 但是Hibernate中的firstResult的索引是从0开始的,所以在hibernate中每页开始的索引数的计算公式是:
* (currentPage-1)*perPageRows+1-1=(currentPge-1)*perPageRows.
*
* maxResult就是每页能查询的最大记录数:也就是perPageRows.
*
* Math.ceil(totalRows/perPageRows)==totalPages;//这是根据总记录数和每页的记录数算出总页数的计算公式。
*/
private Integer currentPage; //当前页
private Integer perPageRows; //每页的记录数
private Integer totalRows; //总记录数:
private Integer totalPages; //总页数:
public Integer getCurrentPage()
{
return currentPage;
}
public void setCurrentPage(Integer currentPage)
{
this.currentPage = currentPage;
}
public Integer getPerPageRows()
{
return perPageRows;
}
public void setPerPageRows(Integer perPageRows)
{
this.perPageRows = perPageRows;
}
public Integer getTotalRows()
{
return totalRows;
}
public void setTotalRows(Integer totalRows)
{
this.totalRows = totalRows;
}
public Integer getTotalPages()
{
return totalPages;
}
public void setTotalPages(Integer totalPages)
{
this.totalPages = totalPages;
}
}
接下来用hibernate的Criteira接口进行查询
对应的实体类Employee的代码:package com.entity;
import javax.persistence.*;
@Entity
@Table(name = "EMPLOYEE")
public class Employee
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "salary")
private int salary;
//a constructor with no arguments
public Employee()
{}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public int getSalary()
{
return salary;
}
public void setSalary(int salary)
{
this.salary = salary;
}
}
//创建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用于连接数据库
hibernate.cfg.xml代码:<?xml version='1.0' encoding='utf-8'?>
hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.0.dtd">
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/test
root
130850a,
10
true
org.hibernate.dialect.MySQLDialect
thread
接着,再写一个用来启动Hibernate的util类:HibernateUtil代码:package com.util;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil
{
private static final SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
static
{
try
{
StandardServiceRegistry standardRegistry =
new StandardServiceRegistryBuilder()
.configure("hibernate.cfg.xml")
.build();
Metadata metaData =
new MetadataSources(standardRegistry)
.getMetadataBuilder()
.build();
sessionFactory = metaData.getSessionFactoryBuilder()
.build();
}
catch (Throwable th)
{
System.err.println("Enitial SessionFactory creation failed" + th);
throw new ExceptionInInitializerError(th);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
最后的话是分页查询代码,具体代码如下:package com.hibDemo;
import com.entity.Employee;
import com.entity.Page;
import com.util.HibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import java.util.List;
public class PaginationQuery
{
public void paginationByCriteria()
{
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction tx = null;
try
{
//do some work
tx = session.beginTransaction();
Page page = new Page();
/**
* 假设现在查询的是第一页,每页查询的最大记录数是3.
*/
page.setCurrentPage(1);
page.setPerPageRows(3);
Criteria criteria = session.createCriteria(Employee.class);
Integer currentPage = page.getCurrentPage(); //得到当前页
Integer perPageRows = page.getPerPageRows(); //得到每页的记录数:
/**
* 在Page类中我已说明了:每页开始的索引数在hibernate中的计算公式是:(currentPage-1)*perPageRows
*/
criteria.setFirstResult((currentPage - 1) * perPageRows);
criteria.setMaxResults(perPageRows);
List employees = criteria.list();
for (Employee employee: employees)
{
System.out.println("*********************");
System.out.println("id=" + employee.getId() + " firstName=" + employee.getFirstName() + " lastName=" + employee.getLastName());
}
tx.commit();
}
catch (Exception e)
{
if (tx != null)
{
tx.rollback();
}
e.printStackTrace();
}
finally
{
session.close(); //关闭流,一定要关闭,不然会影响运行速度。
}
}
public static void main(String[] args)
{
PaginationQuery paginationQuery = new PaginationQuery();
paginationQuery.paginationByCriteria();
}
}
注意,这个Page类为Hibernate中setFirstResult,和setMaxResult服务的。
你想成为一名java架构师吗?请继续关注奇Q工具网吧,更多的相关知识,可以为你分享哦。
推荐阅读: