hibernate mysql分页_用Hibernate实现分页查询

分页查询就是把数据库中某张表的记录数进行分页查询,在做分页查询时会有一个Page类,下面是一个Page类,我对其做了详细的注解:

1 packagecom.entity;2 /**

3 *@author:秦林森4 */

5

6 importjavax.persistence.criteria.CriteriaBuilder;7

8 public classPage {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 publicInteger getCurrentPage() {27 returncurrentPage;28 }29

30 public voidsetCurrentPage(Integer currentPage) {31 this.currentPage =currentPage;32 }33

34 publicInteger getPerPageRows() {35 returnperPageRows;36 }37

38 public voidsetPerPageRows(Integer perPageRows) {39 this.perPageRows =perPageRows;40 }41

42 publicInteger getTotalRows() {43 returntotalRows;44 }45

46 public voidsetTotalRows(Integer totalRows) {47 this.totalRows =totalRows;48 }49

50 publicInteger getTotalPages() {51 returntotalPages;52 }53

54 public voidsetTotalPages(Integer totalPages) {55 this.totalPages =totalPages;56 }57 }

下面用Hibernate的Criteira接口进行查询:

对应的实体类Employee的代码如下:

1 packagecom.entity;2

3 import javax.persistence.*;4

5 @Entity6 @Table(name = "EMPLOYEE")7 public classEmployee {8 @Id9 @GeneratedValue(strategy =GenerationType.IDENTITY)10 private intid;11 @Column(name = "first_name")12 privateString firstName;13 @Column(name = "last_name")14 privateString lastName;15 @Column(name = "salary")16 private intsalary;17 //a constructor with no arguments

18

19

20 publicEmployee() {21 }22

23 public intgetId() {24 returnid;25 }26

27 public void setId(intid) {28 this.id =id;29 }30

31 publicString getFirstName() {32 returnfirstName;33 }34

35 public voidsetFirstName(String firstName) {36 this.firstName =firstName;37 }38

39 publicString getLastName() {40 returnlastName;41 }42

43 public voidsetLastName(String lastName) {44 this.lastName =lastName;45 }46

47 public intgetSalary() {48 returnsalary;49 }50

51 public void setSalary(intsalary) {52 this.salary =salary;53 }54 }

//创建EMPLOYEE表的sql语句是:

create table EMPLOYEE (

id INT NOT NULL auto_increment,

first_name VARCHAR(20) defaultNULL,

last_name VARCHAR(20) defaultNULL,

salary INTdefaultNULL,

PRIMARY KEY (id)

);

首先在写一个配置文件:hibernate.cfg.xml用于连接数据库;

hibernate.cfg.xml的代码如下:

/p>

"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的代码如下:

1 packagecom.util;2 importorg.hibernate.SessionFactory;3 importorg.hibernate.boot.Metadata;4 importorg.hibernate.boot.MetadataSources;5 importorg.hibernate.boot.registry.StandardServiceRegistry;6 importorg.hibernate.boot.registry.StandardServiceRegistryBuilder;7 importorg.hibernate.cfg.Configuration;8 importorg.hibernate.service.ServiceRegistry;9 public classHibernateUtil {10 private static finalSessionFactory sessionFactory;11

12 private staticServiceRegistry serviceRegistry;13

14 static{15 try{16 StandardServiceRegistry standardRegistry =

17 new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();18 Metadata metaData =

19 newMetadataSources(standardRegistry).getMetadataBuilder().build();20 sessionFactory =metaData.getSessionFactoryBuilder().build();21 } catch(Throwable th) {22

23 System.err.println("Enitial SessionFactory creation failed" +th);24 throw newExceptionInInitializerError(th);25

26 }27 }28 public staticSessionFactory getSessionFactory() {29

30 returnsessionFactory;31

32 }33 }

最后是分页查询的代码,代码如下:

1 packagecom.hibDemo;2

3 importcom.entity.Employee;4 importcom.entity.Page;5 importcom.util.HibernateUtil;6 importorg.hibernate.Criteria;7 importorg.hibernate.Session;8 importorg.hibernate.SessionFactory;9 importorg.hibernate.Transaction;10

11 importjava.util.List;12

13 public classPaginationQuery {14

15 public voidpaginationByCriteria(){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 = newPage();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)*perPageRows33 */

34 criteria.setFirstResult((currentPage-1)*perPageRows);35 criteria.setMaxResults(perPageRows);36 List 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 voidmain(String[] args) {53 PaginationQuery paginationQuery = newPaginationQuery();54 paginationQuery.paginationByCriteria();55 }56 }

总结:这个Page类为Hibernate中setFirstResult,和setMaxResult服务的,抓住这个就可以了。代码可以随便写。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值