- 浏览: 150053 次
- 性别:
- 来自: 大连
文章分类
最新评论
-
zhuxinquan61:
你好,我是一个初学者,不知道是不是有validation.xm ...
struts中的Validator-rules.xml配置文件详解 -
wukele:
中文文件名压缩后是乱码~
JAVA压缩文件或文件夹的代码 -
suncjh:
高强度文件夹加密大师
U盘、移动硬盘加密工具绿色版 -
sbpcx:
assdust110 写道jiasky 写道请问楼主的头像是不 ...
Hibernate查询详解 -
yeshuang:
里面的很多的东西
SSH2整合步骤
应用Hibernate3的DetachedCriteria实现分页查询
--------------------------------------------------------------------------------
Hibernate3 提供了DetachedCriteria,使得我们可以在Web层构造detachedCriteria,然后调用业务层Bean,进行动态条件查询,根据这一功能,我设计了通用的抽象Bean基类和分页类支持,代码来自于Quake Wang的javaeye-core包的相应类,然后又做了很多修改。
分页支持类:
java代码:
package com.iteye.common.util;
import java.util.List;
public class PaginationSupport {
public final static int 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.iteye.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.iteye.common.util.PaginationSupport;
public abstract class AbstractManager extends HibernateDaoSupport {
private boolean cacheQueries = false;
private String 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
*
*/
public class Page {
/** imply if the page has previous page */
private boolean hasPrePage;
/** imply if the page has next page */
private boolean hasNextPage;
/** the number of every page */
private int everyPage;
/** the total page number */
private int totalPage;
/** the number of current page */
private int currentPage;
/** the begin index of the records by the current query */
private int 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.
*/
public int getBeginIndex(){
return beginIndex;
}
/**
* @param beginIndex
* The beginIndex to set.
*/
public void setBeginIndex(int beginIndex){
this.beginIndex = beginIndex;
}
/**
* @return
* Returns the currentPage.
*/
public int getCurrentPage(){
return currentPage;
}
/**
* @param currentPage
* The currentPage to set.
*/
public void setCurrentPage(int currentPage){
this.currentPage = currentPage;
}
/**
* @return
* Returns the everyPage.
*/
publicint getEveryPage(){
return everyPage;
}
/**
* @param everyPage
* The everyPage to set.
*/
public void setEveryPage(int everyPage){
this.everyPage = everyPage;
}
/**
* @return
* Returns the hasNextPage.
*/
public boolean getHasNextPage(){
return hasNextPage;
}
/**
* @param hasNextPage
* The hasNextPage to set.
*/
public void setHasNextPage(boolean hasNextPage){
this.hasNextPage = hasNextPage;
}
/**
* @return
* Returns the hasPrePage.
*/
public boolean getHasPrePage(){
return hasPrePage;
}
/**
* @param hasPrePage
* The hasPrePage to set.
*/
public void setHasPrePage(boolean hasPrePage){
this.hasPrePage = hasPrePage;
}
/**
* @return Returns the totalPage.
*
*/
public int getTotalPage(){
return totalPage;
}
/**
* @param totalPage
* The totalPage to set.
*/
public void 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
*
*/
public class PageUtil {
private static final Log logger = LogFactory.getLog(PageUtil.class);
/**
* Use the origin page to create a new page
* @param page
* @param totalRecords
* @return
*/
public static 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
*/
public static 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);
}
private static int getEveryPage(int everyPage){
return everyPage == 0 ? 10 : everyPage;
}
private static int getCurrentPage(int currentPage){
return currentPage == 0 ? 1 : currentPage;
}
private static int getBeginIndex(int everyPage, int currentPage){
return(currentPage - 1) * everyPage;
}
private static int getTotalPage(int everyPage, int totalRecords){
int totalPage = 0;
if(totalRecords % everyPage == 0)
totalPage = totalRecords / everyPage;
else
totalPage = totalRecords / everyPage + 1 ;
return totalPage;
}
private static boolean hasPrePage(int currentPage){
return currentPage == 1 ? false : true;
}
private static boolean 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
*/
public class Result {
private Page page;
private List 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.
*/
public List getContent(){
return content;
}
/**
* @return Returns the page.
*/
public Page getPage(){
return page;
}
/**
* @param content
* The content to set.
*/
public void setContent(List content){
this.content = content;
}
/**
* @param page
* The page to set.
*/
public void 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
*/
public interface 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
*/
public class UserManagerImpl implements UserManager {
private UserDAO userDAO;
/**
* @param userDAO The userDAO to set.
*/
public void 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
*/
public interface UserDAO extends BaseDAO {
public List getUserByName(String name)throws HibernateException;
public int getUserCount()throws HibernateException;
public List 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
*/
public class UserDAOImpl extends BaseDAOHibernateImpl implements UserDAO {
/* (non-Javadoc)
* @see com.adt.dao.UserDAO#getUserByName(java.lang.String)
*/
public List 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()
*/
public int 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)
*/
public List 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
*/
public class ListUser implementsAction{
private static final Log logger = LogFactory.getLog(ListUser.class);
private UserService userService;
private Page page;
privateList users;
/*
* (non-Javadoc)
*
* @see com.opensymphony.xwork.Action#execute()
*/
public String 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.
*/
public List getUsers(){
return users;
}
/**
* @param page
* The page to set.
*/
public void setPage(Page page){
this.page = page;
}
/**
* @param users
* The users to set.
*/
public void setUsers(List users){
this.users = users;
}
/**
* @param userService
* The userService to set.
*/
public void 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
*/
public class Paginator<E> {
private int count = 0; // 总记录数
private int p = 1; // 页编号
private int num = 20; // 每页的记录数
private List<E> results = null; // 结果
/**
* 结果总数
*/
public int getCount(){
return count;
}
public void setCount(int count){
this.count = count;
}
/**
* 本结果所在的页码,从1开始
*
* @return Returns the pageNo.
*/
public int getP(){
return p;
}
/**
* if(p<=0) p=1
*
* @param p
*/
public void setP(int p){
if(p <= 0)
p = 1;
this.p = p;
}
/**
* 每页记录数量
*/
public int getNum(){
return num;
}
/**
* if(num<1) num=1
*/
public void setNum(int num){
if(num < 1)
num = 1;
this.num = num;
}
/**
* 获得总页数
*/
public int getPageNum(){
return(count - 1) / num + 1;
}
/**
* 获得本页的开始编号,为 (p-1)*num+1
*/
public int getStart(){
return(p - 1) * num + 1;
}
/**
* @return Returns the results.
*/
public List<E> getResults(){
return results;
}
public void setResults(List<E> results){
this.results = results;
}
public String 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();
}
}
--------------------------------------------------------------------------------
Hibernate3 提供了DetachedCriteria,使得我们可以在Web层构造detachedCriteria,然后调用业务层Bean,进行动态条件查询,根据这一功能,我设计了通用的抽象Bean基类和分页类支持,代码来自于Quake Wang的javaeye-core包的相应类,然后又做了很多修改。
分页支持类:
java代码:
package com.iteye.common.util;
import java.util.List;
public class PaginationSupport {
public final static int 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.iteye.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.iteye.common.util.PaginationSupport;
public abstract class AbstractManager extends HibernateDaoSupport {
private boolean cacheQueries = false;
private String 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
*
*/
public class Page {
/** imply if the page has previous page */
private boolean hasPrePage;
/** imply if the page has next page */
private boolean hasNextPage;
/** the number of every page */
private int everyPage;
/** the total page number */
private int totalPage;
/** the number of current page */
private int currentPage;
/** the begin index of the records by the current query */
private int 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.
*/
public int getBeginIndex(){
return beginIndex;
}
/**
* @param beginIndex
* The beginIndex to set.
*/
public void setBeginIndex(int beginIndex){
this.beginIndex = beginIndex;
}
/**
* @return
* Returns the currentPage.
*/
public int getCurrentPage(){
return currentPage;
}
/**
* @param currentPage
* The currentPage to set.
*/
public void setCurrentPage(int currentPage){
this.currentPage = currentPage;
}
/**
* @return
* Returns the everyPage.
*/
publicint getEveryPage(){
return everyPage;
}
/**
* @param everyPage
* The everyPage to set.
*/
public void setEveryPage(int everyPage){
this.everyPage = everyPage;
}
/**
* @return
* Returns the hasNextPage.
*/
public boolean getHasNextPage(){
return hasNextPage;
}
/**
* @param hasNextPage
* The hasNextPage to set.
*/
public void setHasNextPage(boolean hasNextPage){
this.hasNextPage = hasNextPage;
}
/**
* @return
* Returns the hasPrePage.
*/
public boolean getHasPrePage(){
return hasPrePage;
}
/**
* @param hasPrePage
* The hasPrePage to set.
*/
public void setHasPrePage(boolean hasPrePage){
this.hasPrePage = hasPrePage;
}
/**
* @return Returns the totalPage.
*
*/
public int getTotalPage(){
return totalPage;
}
/**
* @param totalPage
* The totalPage to set.
*/
public void 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
*
*/
public class PageUtil {
private static final Log logger = LogFactory.getLog(PageUtil.class);
/**
* Use the origin page to create a new page
* @param page
* @param totalRecords
* @return
*/
public static 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
*/
public static 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);
}
private static int getEveryPage(int everyPage){
return everyPage == 0 ? 10 : everyPage;
}
private static int getCurrentPage(int currentPage){
return currentPage == 0 ? 1 : currentPage;
}
private static int getBeginIndex(int everyPage, int currentPage){
return(currentPage - 1) * everyPage;
}
private static int getTotalPage(int everyPage, int totalRecords){
int totalPage = 0;
if(totalRecords % everyPage == 0)
totalPage = totalRecords / everyPage;
else
totalPage = totalRecords / everyPage + 1 ;
return totalPage;
}
private static boolean hasPrePage(int currentPage){
return currentPage == 1 ? false : true;
}
private static boolean 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
*/
public class Result {
private Page page;
private List 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.
*/
public List getContent(){
return content;
}
/**
* @return Returns the page.
*/
public Page getPage(){
return page;
}
/**
* @param content
* The content to set.
*/
public void setContent(List content){
this.content = content;
}
/**
* @param page
* The page to set.
*/
public void 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
*/
public interface 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
*/
public class UserManagerImpl implements UserManager {
private UserDAO userDAO;
/**
* @param userDAO The userDAO to set.
*/
public void 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
*/
public interface UserDAO extends BaseDAO {
public List getUserByName(String name)throws HibernateException;
public int getUserCount()throws HibernateException;
public List 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
*/
public class UserDAOImpl extends BaseDAOHibernateImpl implements UserDAO {
/* (non-Javadoc)
* @see com.adt.dao.UserDAO#getUserByName(java.lang.String)
*/
public List 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()
*/
public int 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)
*/
public List 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
*/
public class ListUser implementsAction{
private static final Log logger = LogFactory.getLog(ListUser.class);
private UserService userService;
private Page page;
privateList users;
/*
* (non-Javadoc)
*
* @see com.opensymphony.xwork.Action#execute()
*/
public String 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.
*/
public List getUsers(){
return users;
}
/**
* @param page
* The page to set.
*/
public void setPage(Page page){
this.page = page;
}
/**
* @param users
* The users to set.
*/
public void setUsers(List users){
this.users = users;
}
/**
* @param userService
* The userService to set.
*/
public void 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
*/
public class Paginator<E> {
private int count = 0; // 总记录数
private int p = 1; // 页编号
private int num = 20; // 每页的记录数
private List<E> results = null; // 结果
/**
* 结果总数
*/
public int getCount(){
return count;
}
public void setCount(int count){
this.count = count;
}
/**
* 本结果所在的页码,从1开始
*
* @return Returns the pageNo.
*/
public int getP(){
return p;
}
/**
* if(p<=0) p=1
*
* @param p
*/
public void setP(int p){
if(p <= 0)
p = 1;
this.p = p;
}
/**
* 每页记录数量
*/
public int getNum(){
return num;
}
/**
* if(num<1) num=1
*/
public void setNum(int num){
if(num < 1)
num = 1;
this.num = num;
}
/**
* 获得总页数
*/
public int getPageNum(){
return(count - 1) / num + 1;
}
/**
* 获得本页的开始编号,为 (p-1)*num+1
*/
public int getStart(){
return(p - 1) * num + 1;
}
/**
* @return Returns the results.
*/
public List<E> getResults(){
return results;
}
public void setResults(List<E> results){
this.results = results;
}
public String 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();
}
}
发表评论
-
SSH2整合步骤
2011-01-11 15:41 1930SSH2整合步骤 -
进销存管理系统项目->工程框架
2010-11-25 14:30 1417此文档需要下载;代码没有写完整! -
实例讲解spring整合struts的几种方式
2010-11-19 13:09 984[size=small]实例讲解spring整合struts的 ... -
Spring整合Struts
2010-11-19 13:03 951为什么整合? 使用Spring的IOC功能将业务类注入Acti ... -
Spring整合Hibernate的步骤
2010-11-19 13:02 1182为什么要整合Hibernate? 1、使用Spring的IOC ... -
Eclipse + MyEclipse整合Struts+Spring+Hibernate简单例子开发
2010-11-19 09:29 1049此文档需要下载! -
图解SSH(struts2,spring,hibernate)框架配置步骤
2010-11-18 10:14 1124此文档需要下载 -
Struts2、Hibernate、spring整合过程总结
2010-11-18 10:05 982Struts2、Hibernate、spring整合过程总结 ... -
Struts2、Hibernate、Spring整合的泛型DAO,以及通用的分页技术 三
2010-11-18 09:58 11689.分页数据信息类 view plaincopy to c ... -
Struts2、Hibernate、Spring整合的泛型DAO,以及通用的分页技术 二
2010-11-18 09:56 17383.具体的DAO接口 view plaincopy to ... -
Struts2、Hibernate、Spring整合的泛型DAO,以及通用的分页技术 一
2010-11-18 09:52 11891.基本DAO泛型接口 view plaincopy t ... -
JAVA通过IP查询详细地址
2010-11-17 10:54 21371. 首先,我们需要一个免费的IP地址库. 纯真I ... -
偷窥struts+hibernate分页(第一种方法)
2010-11-17 10:18 791根据原文有点改动。原文忘记在那里看到了。看到提个醒 新建表 ...
相关推荐
2. Usb摄像头偷窥终结者.exe:这是程序的可执行文件,用户可以通过运行这个文件启动“USB摄像头偷窥终结者”软件。它包含了软件的用户界面、控制逻辑以及与USB摄像头交互的代码。 该软件的工作原理可能是这样的:当...
【U盘偷窥者主程序】是一种特殊类型的恶意软件,主要设计用于在用户不知情的情况下监视和窃取通过U盘(USB闪存驱动器)进行的数据传输。这种类型的恶意程序通常利用U盘的便捷性和普遍性,通过伪装成正常文件或利用...
【标题】"桌面偷窥器"所提及的是一款软件,主要功能是远程监控或查看他人的桌面活动。这种类型的软件通常被用于企业管理员对员工的工作监控,或者在技术支持场景下远程协助用户解决问题。然而,未经同意的个人使用...
在IT行业,远程控制软件是一种能够允许用户通过网络对另一台计算机进行操作的应用程序。这类软件通常用于系统管理、技术支持或恶意活动,如黑客攻击。在这里,我们关注的是合法的开发和理解远程控制软件的工作原理。...
鼠标键盘记录偷窥器鼠标键盘记录偷窥器鼠标键盘记录偷窥器鼠标键盘记录偷窥器鼠标键盘记录偷窥器鼠标键盘记录偷窥器鼠标键盘记录偷窥器
在本资源中,"CSS3可爱偷窥小狗动画代码.zip"是一个包含HTML和CSS源码的压缩包,用于创建一个动态的、具有趣味性的“可爱偷窥小狗”动画效果。这个动画可能展示了一只小狗从屏幕边缘探头探脑的形象,为网站增添互动...
易语言是一种以“易”为理念,面向初学者的中文编程语言。它采用直观的中文语法,降低了编程的学习门槛,使得非计算机专业背景的人也能快速上手编程。在本项目中,开发者使用易语言编写了这个密码文本偷窥器的源代码...
1. **恶意软件**:U盘偷窥者是一种可能的恶意软件,通常这类软件设计用于非法监控用户活动,窃取数据,或者在用户不知情的情况下复制文件。它们可能通过U盘等移动存储设备传播,利用人们的日常使用习惯进行感染。 2...
Java 2引入的findClass方法使得创建自定义ClassLoader变得更加容易,我们只需要覆盖findClass,而无需完全实现loadClass,简化了过程。 自定义ClassLoader的工作原理是,首先创建一个ClassLoader的实例,然后使用这...
2. **钩子技术**:“Hook”在编程中是指一种机制,用于拦截和修改系统调用或消息。这里的“passwordhook.dll”可能就实现了这样的钩子,监听密码框的事件,然后暴露密码内容。 3. **API和控件**:Microsoft提供的...
标题 "偷窥各种桌面程序SPwdSpyDemo_Src" 提示我们这可能是一个关于桌面应用程序密码监测或安全漏洞的研究项目。这个项目的源代码可能包含了用于分析、监控或模拟桌面应用程序密码输入过程的代码。描述中同样重复了...
在《第二单元 第5课 第2框 尊重和维护隐私权》的教学中,我们主要关注的是公民的隐私权以及如何在日常生活中尊重并保护这一基本权利。隐私权是公民的一项基本人权,它涉及到个人信息、生活领域和个人选择的自由。在...
打倒偷窥者——局域网扫描攻防战归纳.pdf
扫描开放的端口,以及如何关闭开放的端口。
内容为网络端口教程的文档 是 exe 格式
以下是四种创建PPT课件章节页的方法: 1. **黑板素材**: 黑板背景能够唤起人们对传统教学环境的记忆,吸引学员的注意力。可以使用带有教师或相关主题图像的黑板图片,增加视觉冲击力。网络上(如Google和...
谁在偷窥你的隐私智能家居安全不得不防.pdf
这是一个不可多得的工具,它不仅能偷窥各种桌面程序的密码框,还能窥到IE页面中的密码框,这个程序就是本文要介绍的——SuperPasswordSpy++。 关键字:hook,ie,com,钩子,安全上下文