怎么使用Hibernate进行分页
这篇文章主要介绍了怎么使用Hibernate进行分页的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇怎么使用Hibernate进行分页文章都会有所收获,下面我们一起来看看吧。
1.什么是分页?
分页是一种将包含多个记录的列表拆分为子列表的技术。例如,您在Google上使用关键字搜索并收到数以万计的结果。但是,每个Google页面只为您显示 10 个结果。其他结果将在下一页显示。
在使用Hibernate的Java应用程序中,一个查询语句可以返回一个记录列表,并且您会问这样一个问题,即如何只获取列表的一部分(从位置N1 到位置N2的记录),并获取有关总记录的信息和总页数。
休眠与 JPA
Hibernate和JPA是两种相同的技术。如果您了解 Hibernate, 则可以轻松地使用JPA,反之亦然。但是,它们也有一些区别。其中一个区别是Hibernate提供了比JPA更好的分页技术。在本课中,我将指导您使用Hibernate 5的分页技术。请注意,该技术不受JPA支持。
2.使用 Hibernate 进行分页
您需要做的就是创建一个Query对象,并提供page、maxResult、maxNavigationResult 参数来创建一个PaginationResult对象。PaginationResult
是一个实用程序类,可帮助您实现查询并返回适合上述参数的记录列表。
package org.o7planning.tutorial.hibernate.pagination;import java.util.ArrayList;import java.util.List;import org.hibernate.ScrollMode;import org.hibernate.ScrollableResults;import org.hibernate.query.Query;public class PaginationResult<E> { private int totalRecords; private int currentPage; private List<E> list; private int maxResult; private int totalPages; private int maxNavigationPage; private List<Integer> navigationPages; // @page: 1, 2, .. public PaginationResult(Query<E> query, int page, int maxResult, int maxNavigationPage) { final int pageIndex = page - 1 < 0 ? 0 : page - 1; int fromRecordIndex = pageIndex * maxResult; int maxRecordIndex = fromRecordIndex + maxResult; ScrollableResults resultScroll = query.scroll(ScrollMode.SCROLL_INSENSITIVE ); List<E> results = new ArrayList<E>(); boolean hasResult = resultScroll.first(); if (hasResult) { // Scroll to position: hasResult = resultScroll.scroll(fromRecordIndex); if (hasResult) { do { E record = (E) resultScroll.get(0); results.add(record); } while (resultScroll.next()// && resultScroll.getRowNumber() >= fromRecordIndex && resultScroll.getRowNumber() < maxRecordIndex); } // Go to Last record. resultScroll.last(); } // Total Records this.totalRecords = resultScroll.getRowNumber() + 1; this.currentPage = pageIndex + 1; this.list = results; this.maxResult = maxResult; if (this.totalRecords % this.maxResult == 0) { this.totalPages = this.totalRecords / this.maxResult; } else { this.totalPages = (this.totalRecords / this.maxResult) + 1; } this.maxNavigationPage = maxNavigationPage; if (maxNavigationPage < totalPages) { this.maxNavigationPage = maxNavigationPage; } resultScroll.close(); this.calcNavigationPages(); } private void calcNavigationPages() { this.navigationPages = new ArrayList<Integer>(); int current = this.currentPage > this.totalPages ? this.totalPages : this.currentPage; int begin = current - this.maxNavigationPage / 2; int end = current + this.maxNavigationPage / 2; // The first page navigationPages.add(1); if (begin > 2) { // Using for '...' navigationPages.add(-1); } for (int i = begin; i < end; i++) { if (i > 1 && i < this.totalPages) { navigationPages.add(i); } } if (end < this.totalPages - 2) { // Using for '...' navigationPages.add(-1); } // The last page. navigationPages.add(this.totalPages); } public int getTotalPages() { return totalPages; } public int getTotalRecords() { return totalRecords; } public int getCurrentPage() { return currentPage; } public List<E> getList() { return list; } public int getMaxResult() { return maxResult; } public List<Integer> getNavigationPages() { return navigationPages; } }
例子:
package org.o7planning.tutorial.hibernate.entities; import java.util.Date;import java.util.HashSet;import java.util.Set; import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.Lob;import javax.persistence.ManyToOne;import javax.persistence.OneToMany;import javax.persistence.Table;import javax.persistence.Temporal;import javax.persistence.TemporalType;import javax.persistence.UniqueConstraint;@Entity@Table(name = "EMPLOYEE", // uniqueConstraints = { @UniqueConstraint(columnNames = { "EMP_NO" }) })public class Employee { @Id @Column(name = "EMP_ID") private Long empId; @Column(name = "EMP_NO", length = 20, nullable = false) private String empNo; @Column(name = "EMP_NAME", length = 50, nullable = false) private String empName; @Column(name = "JOB", length = 30, nullable = false) private String job; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "MNG_ID") private Employee manager; @Column(name = "HIRE_DATE", nullable = false) @Temporal(TemporalType.DATE) private Date hideDate; @Column(name = "SALARY", nullable = false) private Float salary; @Lob @Column(name = "IMAGE", length = Integer.MAX_VALUE, nullable = true) private byte[] image; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "DEPT_ID", nullable = false) private Department department; @OneToMany(fetch = FetchType.LAZY, mappedBy = "empId") private Set<Employee> employees = new HashSet<Employee>(0); // Getter & Setter }
package org.o7planning.tutorial.hibernate.entities; import java.util.HashSet;import java.util.Set;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.FetchType;import javax.persistence.Id;import javax.persistence.OneToMany;import javax.persistence.Table;import javax.persistence.UniqueConstraint; @Entity@Table(name = "DEPARTMENT", // uniqueConstraints = { @UniqueConstraint(columnNames = { "DEPT_NO" }) })public class Department { @Id @Column(name = "DEPT_ID") private Integer deptId; @Column(name = "DEPT_NO", length = 20, nullable = false) private String deptNo; @Column(name = "DEPT_NAME", nullable = false) private String deptName; @Column(name = "LOCATION") private String location; @OneToMany(fetch = FetchType.LAZY, mappedBy = "department") private Set<Employee> employees = new HashSet<Employee>(0); public Department() { } // Getter & Setter}
package org.o7planning.tutorial.hibernate.beans;public class EmployeeInfo { private Long empId; private String empNo; private String empName; private String deptNo; private String deptName; public EmployeeInfo() { } // This constructor is used by Hibernate Query. public EmployeeInfo(Long empId, String empNo, String empName, String deptNo, String deptName) { this.empId = empId; this.empNo = empNo; this.empName = empName; this.deptNo = deptNo; this.deptName = deptName; } // Getter & Setter}
例子:
package org.o7planning.tutorial.hibernate.pagination;import java.util.List;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.query.Query;import org.o7planning.tutorial.hibernate.HibernateUtils;import org.o7planning.tutorial.hibernate.entities.Employee;public class PaginationExample1 { public static void main(String[] args) { // Have sessionFactory object... SessionFactory factory = HibernateUtils.getSessionFactory(); Session session = factory.getCurrentSession(); String sql = "Select e from " + Employee.class.getName() + " e " // + " Where e.empId > :empId "; Query<Employee> query = session.createQuery(sql, Employee.class); query.setParameter("empId", 100); int page = 1; int maxResult = 20; int maxNavigationResult = 10; PaginationResult<Employee> result = new PaginationResult<Employee>(query, page, maxResult, maxNavigationResult); // Result: List<Employee> emps = result.getList(); int totalPages = result.getTotalRecords(); int totalRecords = result.getTotalRecords(); // 1 2 3 4 5 ... 11 12 13 List<Integer> navPages = result.getNavigationPages(); } }
例子:
package org.o7planning.tutorial.hibernate.pagination;import java.util.List;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.query.Query;import org.o7planning.tutorial.hibernate.HibernateUtils;import org.o7planning.tutorial.hibernate.beans.EmployeeInfo;import org.o7planning.tutorial.hibernate.entities.Employee;public class PaginationExample2 { public static void main(String[] args) { // Get sessionFactory object... SessionFactory factory = HibernateUtils.getSessionFactory(); Session session = factory.getCurrentSession(); String sql = "Select new " + EmployeeInfo.class.getName() // + " (e.empId,e.empNo,e.empName,d.deptNo,d.deptName) " // + " from " + Employee.class.getName() + " e " // + " Join e.department d " // + " Order by e.empNo "; Query<EmployeeInfo> query = session.createQuery(sql, EmployeeInfo.class); int page = 1; int maxResult = 20; int maxNavigationResult = 10; PaginationResult<EmployeeInfo> result = new PaginationResult<EmployeeInfo>(query, page, maxResult, maxNavigationResult); // Result: List<EmployeeInfo> emps = result.getList(); int totalPages = result.getTotalRecords(); int totalRecords = result.getTotalRecords(); // 1 2 3 4 5 ... 11 12 13 List<Integer> navPages = result.getNavigationPages(); } }
以及使用PaginationResult的JSP代码片段的示例 :
<c:if test="${paginationProducts.totalPages > 1}"> <div class="page-navigator"> <c:forEach items="${paginationProducts.navigationPages}" var = "page"> <c:if test="${page != -1 }"> <a href="productList?page=${page}" class="nav-item">${page}</a> </c:if> <c:if test="${page == -1 }"> <span class="nav-item"> ... </span> </c:if> </c:forEach> </div> </c:if>
关于“怎么使用Hibernate进行分页”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“怎么使用Hibernate进行分页”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注蜗牛博客行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
评论