您好,登錄后才能下訂單哦!
這篇文章主要介紹了怎么使用Hibernate進行分頁的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇怎么使用Hibernate進行分頁文章都會有所收獲,下面我們一起來看看吧。
分頁是一種將包含多個記錄的列表拆分為子列表的技術。例如,您在Google上使用關鍵字搜索并收到數以萬計的結果。但是,每個Google頁面只為您顯示 10 個結果。其他結果將在下一頁顯示。
在使用Hibernate的Java應用程序中,一個查詢語句可以返回一個記錄列表,并且您會問這樣一個問題,即如何只獲取列表的一部分(從位置N1 到位置N2的記錄),并獲取有關總記錄的信息和總頁數。
休眠與 JPA
Hibernate和JPA是兩種相同的技術。如果您了解 Hibernate, 則可以輕松地使用JPA,反之亦然。但是,它們也有一些區別。其中一個區別是Hibernate提供了比JPA更好的分頁技術。在本課中,我將指導您使用Hibernate 5的分頁技術。請注意,該技術不受JPA支持。
您需要做的就是創建一個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進行分頁”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。