Hibernate3
提供了DetachedCriteria,使得我們可以在Web層構造detachedCriteria,然后調用業務層Bean,進行動態條件查詢,根
據這一功能,我設計了通用的抽象Bean基類和分頁類支持,代碼來自于Quake
Wang的javaeye-core包的相應類,然后又做了很多修改。
分頁支持類:
java代碼:?
|
package com.javaeye.common.util;
import java.util.List;
publicclass PaginationSupport {
? ? ? ? publicfinalstaticint PAGESIZE = 30;
? ? ? ? privateint pageSize = PAGESIZE;
? ? ? ? privateList items;
? ? ? ? privateint totalCount;
? ? ? ? privateint[] indexes = newint[0];
? ? ? ? privateint startIndex = 0;
? ? ? ? public PaginationSupport(List items, int totalCount){
? ? ? ? ? ? ? ? setPageSize(PAGESIZE);
? ? ? ? ? ? ? ? setTotalCount(totalCount);
? ? ? ? ? ? ? ? setItems(items);? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? setStartIndex(0);
? ? ? ? }
? ? ? ? public PaginationSupport(List items, int totalCount, int startIndex){
? ? ? ? ? ? ? ? setPageSize(PAGESIZE);
? ? ? ? ? ? ? ? setTotalCount(totalCount);
? ? ? ? ? ? ? ? setItems(items);? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? setStartIndex(startIndex);
? ? ? ? }
? ? ? ? public PaginationSupport(List items, int totalCount, int pageSize, int startIndex){
? ? ? ? ? ? ? ? setPageSize(pageSize);
? ? ? ? ? ? ? ? setTotalCount(totalCount);
? ? ? ? ? ? ? ? setItems(items);
? ? ? ? ? ? ? ? setStartIndex(startIndex);
? ? ? ? }
? ? ? ? publicList getItems(){
? ? ? ? ? ? ? ? return items;
? ? ? ? }
? ? ? ? publicvoid setItems(List items){
? ? ? ? ? ? ? ? this.items = items;
? ? ? ? }
? ? ? ? publicint getPageSize(){
? ? ? ? ? ? ? ? return pageSize;
? ? ? ? }
? ? ? ? publicvoid setPageSize(int pageSize){
? ? ? ? ? ? ? ? this.pageSize = pageSize;
? ? ? ? }
? ? ? ? publicint getTotalCount(){
? ? ? ? ? ? ? ? return totalCount;
? ? ? ? }
? ? ? ? publicvoid setTotalCount(int totalCount){
? ? ? ? ? ? ? ? if(totalCount > 0){
? ? ? ? ? ? ? ? ? ? ? ? this.totalCount = totalCount;
? ? ? ? ? ? ? ? ? ? ? ? int count = totalCount / pageSize;
? ? ? ? ? ? ? ? ? ? ? ? if(totalCount % pageSize > 0)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? count++;
? ? ? ? ? ? ? ? ? ? ? ? indexes = newint[count];
? ? ? ? ? ? ? ? ? ? ? ? for(int i = 0; i < count; i++){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? indexes[i] = pageSize * i;
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? ? ? ? ? this.totalCount = 0;
? ? ? ? ? ? ? ? }
? ? ? ? }
? ? ? ? publicint[] getIndexes(){
? ? ? ? ? ? ? ? return indexes;
? ? ? ? }
? ? ? ? publicvoid setIndexes(int[] indexes){
? ? ? ? ? ? ? ? this.indexes = indexes;
? ? ? ? }
? ? ? ? publicint getStartIndex(){
? ? ? ? ? ? ? ? return startIndex;
? ? ? ? }
? ? ? ? publicvoid setStartIndex(int startIndex){
? ? ? ? ? ? ? ? if(totalCount <= 0)
? ? ? ? ? ? ? ? ? ? ? ? this.startIndex = 0;
? ? ? ? ? ? ? ? elseif(startIndex >= totalCount)
? ? ? ? ? ? ? ? ? ? ? ? this.startIndex = indexes[indexes.length - 1];
? ? ? ? ? ? ? ? elseif(startIndex < 0)
? ? ? ? ? ? ? ? ? ? ? ? this.startIndex = 0;
? ? ? ? ? ? ? ? else{
? ? ? ? ? ? ? ? ? ? ? ? this.startIndex = indexes[startIndex / pageSize];
? ? ? ? ? ? ? ? }
? ? ? ? }
? ? ? ? publicint getNextIndex(){
? ? ? ? ? ? ? ? int nextIndex = getStartIndex() + pageSize;
? ? ? ? ? ? ? ? if(nextIndex >= totalCount)
? ? ? ? ? ? ? ? ? ? ? ? return getStartIndex();
? ? ? ? ? ? ? ? else
? ? ? ? ? ? ? ? ? ? ? ? return nextIndex;
? ? ? ? }
? ? ? ? publicint getPreviousIndex(){
? ? ? ? ? ? ? ? int previousIndex = getStartIndex() - pageSize;
? ? ? ? ? ? ? ? if(previousIndex < 0)
? ? ? ? ? ? ? ? ? ? ? ? return0;
? ? ? ? ? ? ? ? else
? ? ? ? ? ? ? ? ? ? ? ? return previousIndex;
? ? ? ? }
}
|
抽象業務類
java代碼:?
|
/**
* Created on 2005-7-12
*/
package com.javaeye.common.business;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.javaeye.common.util.PaginationSupport;
publicabstractclass AbstractManager extends HibernateDaoSupport {
? ? ? ? privateboolean cacheQueries = false;
? ? ? ? privateString queryCacheRegion;
? ? ? ? publicvoid setCacheQueries(boolean cacheQueries){
? ? ? ? ? ? ? ? this.cacheQueries = cacheQueries;
? ? ? ? }
? ? ? ? publicvoid setQueryCacheRegion(String queryCacheRegion){
? ? ? ? ? ? ? ? this.queryCacheRegion = queryCacheRegion;
? ? ? ? }
? ? ? ? publicvoid save(finalObject entity){
? ? ? ? ? ? ? ? getHibernateTemplate().save(entity);
? ? ? ? }
? ? ? ? publicvoid persist(finalObject entity){
? ? ? ? ? ? ? ? getHibernateTemplate().save(entity);
? ? ? ? }
? ? ? ? publicvoid update(finalObject entity){
? ? ? ? ? ? ? ? getHibernateTemplate().update(entity);
? ? ? ? }
? ? ? ? publicvoid delete(finalObject entity){
? ? ? ? ? ? ? ? getHibernateTemplate().delete(entity);
? ? ? ? }
? ? ? ? publicObject load(finalClass entity, finalSerializable id){
? ? ? ? ? ? ? ? return getHibernateTemplate().load(entity, id);
? ? ? ? }
? ? ? ? publicObject get(finalClass entity, finalSerializable id){
? ? ? ? ? ? ? ? return getHibernateTemplate().get(entity, id);
? ? ? ? }
? ? ? ? publicList findAll(finalClass entity){
? ? ? ? ? ? ? ? return getHibernateTemplate().find("from " + entity.getName());
? ? ? ? }
? ? ? ? publicList findByNamedQuery(finalString namedQuery){
? ? ? ? ? ? ? ? return getHibernateTemplate().findByNamedQuery(namedQuery);
? ? ? ? }
? ? ? ? publicList findByNamedQuery(finalString query, finalObject parameter){
? ? ? ? ? ? ? ? return getHibernateTemplate().findByNamedQuery(query, parameter);
? ? ? ? }
? ? ? ? publicList findByNamedQuery(finalString query, finalObject[] parameters){
? ? ? ? ? ? ? ? return getHibernateTemplate().findByNamedQuery(query, parameters);
? ? ? ? }
? ? ? ? publicList find(finalString query){
? ? ? ? ? ? ? ? return getHibernateTemplate().find(query);
? ? ? ? }
? ? ? ? publicList find(finalString query, finalObject parameter){
? ? ? ? ? ? ? ? return getHibernateTemplate().find(query, parameter);
? ? ? ? }
? ? ? ? public PaginationSupport findPageByCriteria(final DetachedCriteria detachedCriteria){
? ? ? ? ? ? ? ? return findPageByCriteria(detachedCriteria, PaginationSupport.PAGESIZE, 0);
? ? ? ? }
? ? ? ? public PaginationSupport findPageByCriteria(final DetachedCriteria detachedCriteria, finalint startIndex){
? ? ? ? ? ? ? ? return findPageByCriteria(detachedCriteria, PaginationSupport.PAGESIZE, startIndex);
? ? ? ? }
? ? ? ? public PaginationSupport findPageByCriteria(final DetachedCriteria detachedCriteria, finalint pageSize,
? ? ? ? ? ? ? ? ? ? ? ? finalint startIndex){
? ? ? ? ? ? ? ? return(PaginationSupport) getHibernateTemplate().execute(new HibernateCallback(){
? ? ? ? ? ? ? ? ? ? ? ? publicObject doInHibernate(Session session)throws HibernateException {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Criteria criteria = detachedCriteria.getExecutableCriteria(session);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? int totalCount = ((Integer) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? criteria.setProjection(null);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? List items = criteria.setFirstResult(startIndex).setMaxResults(pageSize).list();
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? PaginationSupport ps = new PaginationSupport(items, totalCount, pageSize, startIndex);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? return ps;
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }, true);
? ? ? ? }
? ? ? ? publicList findAllByCriteria(final DetachedCriteria detachedCriteria){
? ? ? ? ? ? ? ? return(List) getHibernateTemplate().execute(new HibernateCallback(){
? ? ? ? ? ? ? ? ? ? ? ? publicObject doInHibernate(Session session)throws HibernateException {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Criteria criteria = detachedCriteria.getExecutableCriteria(session);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? return criteria.list();
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }, true);
? ? ? ? }
? ? ? ? publicint getCountByCriteria(final DetachedCriteria detachedCriteria){
? ? ? ? ? ? ? ? Integer count = (Integer) getHibernateTemplate().execute(new HibernateCallback(){
? ? ? ? ? ? ? ? ? ? ? ? publicObject doInHibernate(Session session)throws HibernateException {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Criteria criteria = detachedCriteria.getExecutableCriteria(session);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? return criteria.setProjection(Projections.rowCount()).uniqueResult();
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }, true);
? ? ? ? ? ? ? ? return count.intValue();
? ? ? ? } }
|
用戶在web層構造查詢條件detachedCriteria,和可選的startIndex,調用業務bean的相應findByCriteria方法,返回一個PaginationSupport的實例ps。
ps.getItems()得到已分頁好的結果集
ps.getIndexes()得到分頁索引的數組
ps.getTotalCount()得到總結果數
ps.getStartIndex()當前分頁索引
ps.getNextIndex()下一頁索引
ps.getPreviousIndex()上一頁索引
連續看了兩篇robbin有關DetachedCriteria的介紹,感覺真的不錯,尤其是上面的示例代碼,讓我著實覺得該對我原來的分頁查詢做一下代碼重構了。
我把原本我的做法也提供出來供大家討論吧:
首先,為了實現分頁查詢,我封裝了一個Page類:
java代碼:?
|
/*Created on 2005-4-14*/
package org.flyware.util.page;
/**
* @author Joa
*
*/ publicclass Page {
? ?
? ? /** imply if the page has previous page */
? ? privateboolean hasPrePage;
? ?
? ? /** imply if the page has next page */
? ? privateboolean hasNextPage;
? ? ? ?
? ? /** the number of every page */
? ? privateint everyPage;
? ?
? ? /** the total page number */
? ? privateint totalPage;
? ? ? ?
? ? /** the number of current page */
? ? privateint currentPage;
? ?
? ? /** the begin index of the records by the current query */
? ? privateint beginIndex;
? ?
? ?
? ? /** The default constructor */
? ? public Page(){
? ? ? ?
? ? }
? ?
? ? /** construct the page by everyPage
? ? ?* @param everyPage
? ? ?* */
? ? public Page(int everyPage){
? ? ? ? this.everyPage = everyPage;
? ? }
? ?
? ? /** The whole constructor */
? ? public Page(boolean hasPrePage, boolean hasNextPage,?
? ? ? ? ? ? ? ? ? ? int everyPage, int totalPage,
? ? ? ? ? ? ? ? ? ? int currentPage, int beginIndex){
? ? ? ? this.hasPrePage = hasPrePage;
? ? ? ? this.hasNextPage = hasNextPage;
? ? ? ? this.everyPage = everyPage;
? ? ? ? this.totalPage = totalPage;
? ? ? ? this.currentPage = currentPage;
? ? ? ? this.beginIndex = beginIndex;
? ? }
? ? /**
? ? ?* @return
? ? ?* Returns the beginIndex.
? ? ?*/
? ? publicint getBeginIndex(){
? ? ? ? return beginIndex;
? ? }
? ?
? ? /**
? ? ?* @param beginIndex
? ? ?* The beginIndex to set.
? ? ?*/
? ? publicvoid setBeginIndex(int beginIndex){
? ? ? ? this.beginIndex = beginIndex;
? ? }
? ?
? ? /**
? ? ?* @return
? ? ?* Returns the currentPage.
? ? ?*/
? ? publicint getCurrentPage(){
? ? ? ? return currentPage;
? ? }
? ?
? ? /**
? ? ?* @param currentPage
? ? ?* The currentPage to set.
? ? ?*/
? ? publicvoid setCurrentPage(int currentPage){
? ? ? ? this.currentPage = currentPage;
? ? }
? ?
? ? /**
? ? ?* @return
? ? ?* Returns the everyPage.
? ? ?*/
? ? publicint getEveryPage(){
? ? ? ? return everyPage;
? ? }
? ?
? ? /**
? ? ?* @param everyPage
? ? ?* The everyPage to set.
? ? ?*/
? ? publicvoid setEveryPage(int everyPage){
? ? ? ? this.everyPage = everyPage;
? ? }
? ?
? ? /**
? ? ?* @return
? ? ?* Returns the hasNextPage.
? ? ?*/
? ? publicboolean getHasNextPage(){
? ? ? ? return hasNextPage;
? ? }
? ?
? ? /**
? ? ?* @param hasNextPage
? ? ?* The hasNextPage to set.
? ? ?*/
? ? publicvoid setHasNextPage(boolean hasNextPage){
? ? ? ? this.hasNextPage = hasNextPage;
? ? }
? ?
? ? /**
? ? ?* @return
? ? ?* Returns the hasPrePage.
? ? ?*/
? ? publicboolean getHasPrePage(){
? ? ? ? return hasPrePage;
? ? }
? ?
? ? /**
? ? ?* @param hasPrePage
? ? ?* The hasPrePage to set.
? ? ?*/
? ? publicvoid setHasPrePage(boolean hasPrePage){
? ? ? ? this.hasPrePage = hasPrePage;
? ? }
? ?
? ? /**
? ? ?* @return Returns the totalPage.
? ? ?*
? ? ?*/
? ? publicint getTotalPage(){
? ? ? ? return totalPage;
? ? }
? ?
? ? /**
? ? ?* @param totalPage
? ? ?* The totalPage to set.
? ? ?*/
? ? publicvoid setTotalPage(int totalPage){
? ? ? ? this.totalPage = totalPage;
? ? }
? ?
}
|
上面的這個Page類對象只是一個完整的Page描述,接下來我寫了一個PageUtil,負責對Page對象進行構造:
java代碼:?
|
/*Created on 2005-4-14*/
package org.flyware.util.page;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author Joa
*
*/ publicclass PageUtil {
? ?
? ? privatestaticfinal Log logger = LogFactory.getLog(PageUtil.class);
? ?
? ? /**
? ? ?* Use the origin page to create a new page
? ? ?* @param page
? ? ?* @param totalRecords
? ? ?* @return
? ? ?*/
? ? publicstatic Page createPage(Page page, int totalRecords){
? ? ? ? return createPage(page.getEveryPage(), page.getCurrentPage(), totalRecords);
? ? }
? ?
? ? /**?
? ? ?* the basic page utils not including exception handler
? ? ?* @param everyPage
? ? ?* @param currentPage
? ? ?* @param totalRecords
? ? ?* @return page
? ? ?*/
? ? publicstatic Page createPage(int everyPage, int currentPage, int totalRecords){
? ? ? ? everyPage = getEveryPage(everyPage);
? ? ? ? currentPage = getCurrentPage(currentPage);
? ? ? ? int beginIndex = getBeginIndex(everyPage, currentPage);
? ? ? ? int totalPage = getTotalPage(everyPage, totalRecords);
? ? ? ? boolean hasNextPage = hasNextPage(currentPage, totalPage);
? ? ? ? boolean hasPrePage = hasPrePage(currentPage);
? ? ? ?
? ? ? ? returnnew Page(hasPrePage, hasNextPage,?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? everyPage, totalPage,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? currentPage, beginIndex);
? ? }
? ?
? ? privatestaticint getEveryPage(int everyPage){
? ? ? ? return everyPage == 0 ? 10 : everyPage;
? ? }
? ?
? ? privatestaticint getCurrentPage(int currentPage){
? ? ? ? return currentPage == 0 ? 1 : currentPage;
? ? }
? ?
? ? privatestaticint getBeginIndex(int everyPage, int currentPage){
? ? ? ? return(currentPage - 1) * everyPage;
? ? }
? ? ? ?
? ? privatestaticint getTotalPage(int everyPage, int totalRecords){
? ? ? ? int totalPage = 0;
? ? ? ? ? ? ? ?
? ? ? ? if(totalRecords % everyPage == 0)
? ? ? ? ? ? totalPage = totalRecords / everyPage;
? ? ? ? else
? ? ? ? ? ? totalPage = totalRecords / everyPage + 1 ;
? ? ? ? ? ? ? ?
? ? ? ? return totalPage;
? ? }
? ?
? ? privatestaticboolean hasPrePage(int currentPage){
? ? ? ? return currentPage == 1 ? false : true;
? ? }
? ?
? ? privatestaticboolean hasNextPage(int currentPage, int totalPage){
? ? ? ? return currentPage == totalPage || totalPage == 0 ? false : true;
? ? }
? ?
}
|
上面的這兩個對象與具體的業務邏輯無關,可以獨立和抽象。
面對一個具體的業務邏輯:分頁查詢出User,每頁10個結果。具體做法如下:
1. 編寫一個通用的結果存儲類Result,這個類包含一個Page對象的信息,和一個結果集List:
java代碼:?
|
/*Created on 2005-6-13*/
package com.adt.bo;
import java.util.List;
import org.flyware.util.page.Page;
/**
* @author Joa
*/ publicclass Result {
? ? private Page page;
? ? privateList content;
? ? /**
? ? ?* The default constructor
? ? ?*/
? ? public Result(){
? ? ? ? super();
? ? }
? ? /**
? ? ?* The constructor using fields
? ? ?*
? ? ?* @param page
? ? ?* @param content
? ? ?*/
? ? public Result(Page page, List content){
? ? ? ? this.page = page;
? ? ? ? this.content = content;
? ? }
? ? /**
? ? ?* @return Returns the content.
? ? ?*/
? ? publicList getContent(){
? ? ? ? return content;
? ? }
? ? /**
? ? ?* @return Returns the page.
? ? ?*/
? ? public Page getPage(){
? ? ? ? return page;
? ? }
? ? /**
? ? ?* @param content
? ? ?*? ? ? ? ? ? The content to set.
? ? ?*/
? ? publicvoid setContent(List content){
? ? ? ? this.content = content;
? ? }
? ? /**
? ? ?* @param page
? ? ?*? ? ? ? ? ? The page to set.
? ? ?*/
? ? publicvoid setPage(Page page){
? ? ? ? this.page = page;
? ? } }
|
2. 編寫業務邏輯接口,并實現它(UserManager, UserManagerImpl)
java代碼:?
|
/*Created on 2005-7-15*/
package com.adt.service;
import net.sf.hibernate.HibernateException;
import org.flyware.util.page.Page;
import com.adt.bo.Result;
/**
* @author Joa
*/ publicinterface UserManager {
? ?
? ? public Result listUser(Page page)throws HibernateException;
}
|
java代碼:?
|
/*Created on 2005-7-15*/
package com.adt.service.impl;
import java.util.List;
import net.sf.hibernate.HibernateException;
import org.flyware.util.page.Page;
import org.flyware.util.page.PageUtil;
import com.adt.bo.Result;
import com.adt.dao.UserDAO;
import com.adt.exception.ObjectNotFoundException;
import com.adt.service.UserManager;
/**
* @author Joa
*/ publicclass UserManagerImpl implements UserManager {
? ?
? ? private UserDAO userDAO;
? ? /**
? ? ?* @param userDAO The userDAO to set.
? ? ?*/
? ? publicvoid setUserDAO(UserDAO userDAO){
? ? ? ? this.userDAO = userDAO;
? ? }
? ?
? ? /* (non-Javadoc)
? ? ?* @see com.adt.service.UserManager#listUser(org.flyware.util.page.Page)
? ? ?*/
? ? public Result listUser(Page page)throws HibernateException, ObjectNotFoundException {
? ? ? ? int totalRecords = userDAO.getUserCount();
? ? ? ? if(totalRecords == 0)
? ? ? ? ? ? throw new ObjectNotFoundException("userNotExist");
? ? ? ? page = PageUtil.createPage(page, totalRecords);
? ? ? ? List users = userDAO.getUserByPage(page);
? ? ? ? returnnew Result(page, users);
? ? }
}
|
其中,UserManagerImpl中調用userDAO的方法實現對User的分頁查詢,接下來編寫UserDAO的代碼:
3. UserDAO 和 UserDAOImpl:
java代碼:?
|
/*Created on 2005-7-15*/
package com.adt.dao;
import java.util.List;
import org.flyware.util.page.Page;
import net.sf.hibernate.HibernateException;
/**
* @author Joa
*/ publicinterface UserDAO extends BaseDAO {
? ?
? ? publicList getUserByName(String name)throws HibernateException;
? ?
? ? publicint getUserCount()throws HibernateException;
? ?
? ? publicList getUserByPage(Page page)throws HibernateException;
}
|
java代碼:?
|
/*Created on 2005-7-15*/
package com.adt.dao.impl;
import java.util.List;
import org.flyware.util.page.Page;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Query;
import com.adt.dao.UserDAO;
/**
* @author Joa
*/ publicclass UserDAOImpl extends BaseDAOHibernateImpl implements UserDAO {
? ? /* (non-Javadoc)
? ? ?* @see com.adt.dao.UserDAO#getUserByName(java.lang.String)
? ? ?*/
? ? publicList getUserByName(String name)throws HibernateException {
? ? ? ? String querySentence = "FROM user in class com.adt.po.User WHERE user.name=:name";
? ? ? ? Query query = getSession().createQuery(querySentence);
? ? ? ? query.setParameter("name", name);
? ? ? ? return query.list();
? ? }
? ? /* (non-Javadoc)
? ? ?* @see com.adt.dao.UserDAO#getUserCount()
? ? ?*/
? ? publicint getUserCount()throws HibernateException {
? ? ? ? int count = 0;
? ? ? ? String querySentence = "SELECT count(*) FROM user in class com.adt.po.User";
? ? ? ? Query query = getSession().createQuery(querySentence);
? ? ? ? count = ((Integer)query.iterate().next()).intValue();
? ? ? ? return count;
? ? }
? ? /* (non-Javadoc)
? ? ?* @see com.adt.dao.UserDAO#getUserByPage(org.flyware.util.page.Page)
? ? ?*/
? ? publicList getUserByPage(Page page)throws HibernateException {
? ? ? ? String querySentence = "FROM user in class com.adt.po.User";
? ? ? ? Query query = getSession().createQuery(querySentence);
? ? ? ? query.setFirstResult(page.getBeginIndex())
? ? ? ? ? ? ? ? .setMaxResults(page.getEveryPage());
? ? ? ? return query.list();
? ? }
}
|
至此,一個完整的分頁程序完成。前臺的只需要調用userManager.listUser(page)即可得到一個Page對象和結果集對象的綜合體,而傳入的參數page對象則可以由前臺傳入,如果用webwork,甚至可以直接在配置文件中指定。
下面給出一個webwork調用示例:
java代碼:?
|
/*Created on 2005-6-17*/
package com.adt.action.user;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.flyware.util.page.Page;
import com.adt.bo.Result;
import com.adt.service.UserService;
import com.opensymphony.xwork.Action;
/**
* @author Joa
*/ publicclass ListUser implementsAction{
? ? privatestaticfinal Log logger = LogFactory.getLog(ListUser.class);
? ? private UserService userService;
? ? private Page page;
? ? privateList users;
? ? /*
? ? ?* (non-Javadoc)
? ? ?*
? ? ?* @see com.opensymphony.xwork.Action#execute()
? ? ?*/
? ? publicString execute()throwsException{
? ? ? ? Result result = userService.listUser(page);
? ? ? ? page = result.getPage();
? ? ? ? users = result.getContent();
? ? ? ? return SUCCESS;
? ? }
? ? /**
? ? ?* @return Returns the page.
? ? ?*/
? ? public Page getPage(){
? ? ? ? return page;
? ? }
? ? /**
? ? ?* @return Returns the users.
? ? ?*/
? ? publicList getUsers(){
? ? ? ? return users;
? ? }
? ? /**
? ? ?* @param page
? ? ?*? ? ? ? ? ? The page to set.
? ? ?*/
? ? publicvoid setPage(Page page){
? ? ? ? this.page = page;
? ? }
? ? /**
? ? ?* @param users
? ? ?*? ? ? ? ? ? The users to set.
? ? ?*/
? ? publicvoid setUsers(List users){
? ? ? ? this.users = users;
? ? }
? ? /**
? ? ?* @param userService
? ? ?*? ? ? ? ? ? The userService to set.
? ? ?*/
? ? publicvoid setUserService(UserService userService){
? ? ? ? this.userService = userService;
? ? } }
|
上面的代碼似乎看不出什么地方設置了page的相關初值,事實上,可以通過配置文件來進行配置,例如,我想每頁顯示10條記錄,那么只需要:
java代碼:?
|
<?xml version="1.0"?>
<!DOCTYPE xwork PUBLIC "-//OpenSymphony Group//XWork 1.0//EN" "http://www.opensymphony.com/xwork/xwork-1.0.dtd">
<xwork>
? ? ? ?
? ? ? ? <package name="user" extends="webwork-interceptors">
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? <!-- The default interceptor stack name -->
? ? ? ? <default-interceptor-ref name="myDefaultWebStack"/>
? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? <action name="listUser" class="com.adt.action.user.ListUser">
? ? ? ? ? ? ? ? ? ? ? ? <param name="page.everyPage">10</param>
? ? ? ? ? ? ? ? ? ? ? ? <result name="success">/user/user_list.jsp</result>
? ? ? ? ? ? ? ? </action>
? ? ? ? ? ? ? ?
? ? ? ? </package>
</xwork>
|
這樣就可以通過配置文件和OGNL的共同作用來對page對象設置初值了。并可以通過隨意修改配置文件來修改每頁需要顯示的記錄數。
注:上面的<param>的配置,還需要webwork和Spring整合的配合。
我寫的一個用于分頁的類,用了泛型了,hoho
java代碼:?
|
package com.intokr.util;
import java.util.List;
/**
* 用于分頁的類<br>
* 可以用于傳遞查詢的結果也可以用于傳送查詢的參數<br>
*
* @version 0.01
* @author cheng
*/ publicclass Paginator<E> {
? ? ? ? privateint count = 0; // 總記錄數
? ? ? ? privateint p = 1; // 頁編號
? ? ? ? privateint num = 20; // 每頁的記錄數
? ? ? ? privateList<E> results = null; // 結果
? ? ? ? /**
? ? ? ? * 結果總數
? ? ? ? */
? ? ? ? publicint getCount(){
? ? ? ? ? ? ? ? return count;
? ? ? ? }
? ? ? ? publicvoid setCount(int count){
? ? ? ? ? ? ? ? this.count = count;
? ? ? ? }
? ? ? ? /**
? ? ? ? * 本結果所在的頁碼,從1開始
? ? ? ? *
? ? ? ? * @return Returns the pageNo.
? ? ? ? */
? ? ? ? publicint getP(){
? ? ? ? ? ? ? ? return p;
? ? ? ? }
? ? ? ? /**
? ? ? ? * if(p<=0) p=1
? ? ? ? *
? ? ? ? * @param p
? ? ? ? */
? ? ? ? publicvoid setP(int p){
? ? ? ? ? ? ? ? if(p <= 0)
? ? ? ? ? ? ? ? ? ? ? ? p = 1;
? ? ? ? ? ? ? ? this.p = p;
? ? ? ? }
? ? ? ? /**
? ? ? ? * 每頁記錄數量
? ? ? ? */
? ? ? ? publicint getNum(){
? ? ? ? ? ? ? ? return num;
? ? ? ? }
? ? ? ? /**
? ? ? ? * if(num<1) num=1
? ? ? ? */
? ? ? ? publicvoid setNum(int num){
? ? ? ? ? ? ? ? if(num < 1)
? ? ? ? ? ? ? ? ? ? ? ? num = 1;
? ? ? ? ? ? ? ? this.num = num;
? ? ? ? }
? ? ? ? /**
? ? ? ? * 獲得總頁數
? ? ? ? */
? ? ? ? publicint getPageNum(){
? ? ? ? ? ? ? ? return(count - 1) / num + 1;
? ? ? ? }
? ? ? ? /**
? ? ? ? * 獲得本頁的開始編號,為 (p-1)*num+1
? ? ? ? */
? ? ? ? publicint getStart(){
? ? ? ? ? ? ? ? return(p - 1) * num + 1;
? ? ? ? }
? ? ? ? /**
? ? ? ? * @return Returns the results.
? ? ? ? */
? ? ? ? publicList<E> getResults(){
? ? ? ? ? ? ? ? return results;
? ? ? ? }
? ? ? ? publicvoid setResults(List<E> results){
? ? ? ? ? ? ? ? this.results = results;
? ? ? ? }
? ? ? ? publicString toString(){
? ? ? ? ? ? ? ? StringBuilder buff = new StringBuilder();
? ? ? ? ? ? ? ? buff.append("{");
? ? ? ? ? ? ? ? buff.append("count:").append(count);
? ? ? ? ? ? ? ? buff.append(",p:").append(p);
? ? ? ? ? ? ? ? buff.append(",nump:").append(num);
? ? ? ? ? ? ? ? buff.append(",results:").append(results);
? ? ? ? ? ? ? ? buff.append("}");
? ? ? ? ? ? ? ? return buff.toString();
? ? ? ? }
}
|
偷窺自 http://forum.javaeye.com/
|