hibernate 通用分頁,查詢分頁的泛型類

君墨痕發表於2013-09-16

寫在泛型dao層的實現類裡,可以達到寫一次,然後繼承這個實現類,傳入各自的型別就可以達到很高的複用效果,增加開發效率

也可以作為查詢的分頁,自己動態構造查詢的語句,然後對應好傳入的引數,動態構造查詢語句的時候StringBuffer,直接用string型別效率低。

向上具體的方法,讓後上分頁的util

	/**
	 * Description:獲取一個分頁資料,包含list和totalCount
	 * 
	 * @return
	 */
	public PageUtil<M> getPageData(final String hql, final int offset,
			final int pageSize, final Object... paramlist) {
		PageUtil<M> page = new PageUtil<M>();
		List<M> list = this.listPage(hql, offset, pageSize, paramlist);
		String hql2 = "select count(*) " + hql;
		Number tempCountAll = this.unique(hql2, paramlist);
		int totalCount = tempCountAll.intValue();
		page.setList(list);
		page.setTotalCount(totalCount);
		return page;
	}

	/**
	 * Description: 按hql條件查詢語句返回分頁結果
	 * 
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<M> listPage(final String hql, final int offset,
			final int pageSize, final Object... paramlist) {
		return hibernateTemplate.executeFind(new HibernateCallback() {

			public List<M> doInHibernate(Session session)
					throws HibernateException, SQLException {
				Query query = (Query) session.createQuery(hql);
				if (paramlist != null) {
					for (int i = 0; i < paramlist.length; i++) {
						query.setParameter(i, paramlist[i]);
					}
				}
				if (offset > -1 && pageSize > -1) {
					query.setMaxResults(pageSize);
					query.setFirstResult(offset);
				}
				return query.list();
			}
		});
	}

	/**
	 * Description: 按hql條件查詢語句返回分頁結果的唯一值
	 * 
	 * @return
	 */
	public <T> T unique(final String hql, final Object... paramList) {
		T countAll = (T) hibernateTemplate.execute(new HibernateCallback<T>() {

			@SuppressWarnings("unchecked")
			public T doInHibernate(Session session) throws HibernateException,
					SQLException {
				Query query = session.createQuery(hql);
				if (paramList != null) {
					for (int i = 0; i < paramList.length; i++) {
						query.setParameter(i, paramList[i]);
					}
				}
				return (T) query.setMaxResults(1).uniqueResult();
			}
		});
		return countAll;
	}

然後是PageUtil類

public class PageUtil<M> {

	private List<M> list;
	private Integer totalCount;

	public List<M> getList() {
		return list;
	}

	public void setList(List<M> list) {
		this.list = list;
	}

	public Integer getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(Integer totalCount) {
		this.totalCount = totalCount;
	}

}


相關文章