1. 程式人生 > >hibernate query分頁封裝

hibernate query分頁封裝

package com.ytby.util;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.ScrollableResults;

public class Page {
	private List result; // 結果集
	private int pageSize; // 頁大小
	private int startPage; // 起始頁 從1開始
	private ScrollableResults scrollableResults;
	private int totalResults; // 總記錄的條數
	private int totalPages; // 總頁數

	public Page(int startPage, int pageSize, Query query) {
		this.startPage = startPage;
		this.pageSize = pageSize;
		this.result = null;
		try {
			this.scrollableResults = query.scroll();
			this.scrollableResults.last();
			if (scrollableResults.getRowNumber() >= 0) {
				this.totalResults = this.scrollableResults.getRowNumber() + 1;
			} else {
				this.totalResults = 0;
			}
			setTotalPages();
			result = query.setFirstResult(
					(this.getStartPage() - 1) * this.pageSize).setMaxResults(
					this.pageSize).list();
		} catch (HibernateException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 得到查詢結果
	 * 
	 * @return 查詢結果
	 */
	public List getResult() {
		return result;
	}

	/**
	 * 得到起始頁
	 * 
	 * @return
	 */
	public int getStartPage() {
		if (startPage < 1) {
			startPage = 1;
		}
		if (startPage > totalPages) {
			startPage = totalPages;
		}
		return startPage;
	}

	/**
	 * 得到記錄總數
	 * 
	 * @return
	 */
	public int getTotalResults() {
		return totalResults;
	}

	/**
	 * 得到頁大小
	 * 
	 * @return
	 */
	public int getPageSize() {
		return pageSize;
	}

	/**
	 * 判斷是否是第一頁
	 * 
	 * @return
	 */
	public boolean isFirstPage() {
		return this.startPage == 1;
	}

	/**
	 * 判斷是否是有後一頁
	 * 
	 * @return
	 */
	public boolean hasNextPage() {
		return this.startPage < this.totalPages;
	}

	/**
	 * 判斷是否是有前一頁
	 * 
	 * @return
	 */
	public boolean hasPreviousPage() {
		return this.startPage > 1;
	}

	/**
	 * 設定總頁數
	 * 
	 */
	private void setTotalPages() {
		this.totalPages = this.totalResults / this.pageSize;
		if (totalPages * pageSize < totalResults) {
			totalPages++;
		}
	}

	/**
	 * 得到總頁數
	 * 
	 * @return
	 */
	public int getTotalPages() {
		return totalPages;
	}
}

dao層呼叫

	public Page getList( int pageSize, int pageIndex) {
		Session session = ht.getSessionFactory().openSession();
		String hql = "from User";
		
		Query query = session.createQuery(hql);
		
		Page pages = new Page(pageIndex, pageSize, query);
		session.close();
		return pages;

	}