hibernate分页

分页应该是软件开发中常见的功能。使用HIBERNATE分页。将其提取,留个记录。上代码

PaginationVo  分页的对象。

/**

*

*@authorleixiaowu

*@describe

*@date2010-12-8

*@packagecn.com.ait.energysaving.model.vo

*/

public class PaginationVo implements Serializable {

 /**

*

*/

 private static final long serialVersionUID = 1L;

 /** 每页显示 */ private int pageShowNum = 50;

 /** 总页数 */

privateinttotalPages=0;

/**总记录数*/

privateintrecordSize=0;

/**当前页面*/

privateintcurrentPage=1;

/**要分页对象*/

 private List<?> pageObjects;

 public int getCurrentCursor() {

returnpageShowNum*(currentPage-1);

 }

 /**

*拿到当前页面对象

*

*@return

*@throwsException

  */

 public int getCurrentPage() {

if(currentPage<=0){

currentPage=1;

}

if(currentPage>getTotalPages()){

currentPage=getTotalPages();

}

returncurrentPage;

 }

 public List<?> getPageObjects() {

returnpageObjects;

 }

 public int getPageShowNum() {

returnpageShowNum;

 }

 public int getRecordSize() {

returnrecordSize;

 }

 /**

*拿到总页数

*

*@return

*/

 public int getTotalPages() {

  if (recordSize > 0) {

totalPages=recordSize%getPageShowNum()==0?recordSize

/getPageShowNum():recordSize/getPageShowNum()+1;

}

returntotalPages;

 }

 public void setCurrentPage(int currentPage) {

this.currentPage=currentPage;

 }

 public void setPageObjects(List<?> pageObjects) {

this.pageObjects=pageObjects;

 }

 public void setPageShowNum(int pageShowNum) {

this.pageShowNum=pageShowNum;

 }

 public void setRecordSize(int recordSize) {

this.recordSize=recordSize;

 }

 public void setTotalPages(int totalPages) {

this.totalPages=totalPages;

 }

}

DAO中用于查询

public List<?> getObjectsByPagination(final String sql, final int first,   final int size, final Class entityClass_) throws DaoException {

  try {

returnsuper.getHibernateTemplate().executeFind(

     new HibernateCallback() {

      @Override

publicObjectdoInHibernate(Sessionsession)

throwsHibernateException,SQLException{

Queryquery=null;

if(null==entityClass_){

query=session.createQuery(sql);

}else{

query=session.createSQLQuery(sql).addEntity(

entityClass_);

       }

       query.setFirstResult(first);

query.setMaxResults(size);

returnquery.list();

}

     });

  } catch (Exception e) {

log.error(e);

this.saveLog(newLogEntity(newDate(),"",e+""));

thrownewDaoException(RCUDError.search_error+e);

}

 }

Service中将条件做判断,并查询数据的多少

isnull(cpValue);

//组装SQL

SqlCriteriasqlCriteria=createSqlCriteria(cpValue);

try{

intsize=this.baseDao.getSize("selectcount(*)from("

+sqlCriteria.toString()+")");

if(size<=0){

returnnull;

}else{

page.setRecordSize(size);

}

}catch(Exceptione){

log.error(e);

thrownewSimpleException(e.getMessage());

  }

  @SuppressWarnings("unchecked")

List<CpFlightRouteEntity>cps=super.getObjectsByCondition(

sqlCriteria,page,CpFlightRouteEntity.class);

if(null==cps||cps.isEmpty()){

returnnull;

  }

相关推荐