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