hibernate下实现分页实例

来源:互联网 发布:传奇霸业数据汇总 编辑:程序博客网 时间:2024/05/01 17:40

action:

//  // 每页数据量

int MaxLine = 5或10或15(依项目自定义);   

 

  // 获得总页数  

 try {   

 Total = listdao.getTotalPage(userno, username);  

 } catch (SQLException e1) {  

  e1.printStackTrace();   

 request.setAttribute("message", "查询页数操作出错!");    

return mapping.findForward("error");   }   

// 设置总页数   TPages = (int) Math.ceil((double) this.Total / this.MaxLine);   

request.setAttribute("TotalPage", String.valueOf(TPages));   

// 设置当前页数   CPages = (int) Math.floor((double) Offset / this.MaxLine + 1);   

 request.setAttribute("pageNo",nowPageNum);

 

 // 每页数据量   int countP = MaxLine ;

// 临时变量   Map map = null;   

TbUser userbean = null;

// start:-----数据偏移量

  int start = (Integer.parseInt(nowPageNum) - 1)* countP;

// length:----每页显示的数据量   

int length = countP;

// dao 查询

userlist = listdao.getPageData(start, length,  username,  userno);

 

dao: 

public List getPageData(Integer start, Integer length, String username,    String userno) {

  Session session = null;   

Query query = null;   

StringBuffer hql = new StringBuffer("from TbUser where 1=1");

  if (username != null && !"".equals(username))

{    hql.append(" and username like :username");   }

  if (userno != null && !"".equals(userno))

 {    hql.append(" and userno=:userno");   }

   List resultlist= null;   

try {    session = getSession();    

query = session.createQuery(hql.toString());   

 if (username != null && !"".equals(username))

 {     query.setParameter("username", "%"+username+"%");    }

   if (userno != null && !"".equals(userno))

{     query.setParameter("userno", userno);    }

    if (start != null)    

 {query.setFirstResult(start); }  

 if (length != null)  

 {  query.setMaxResults(length);}

   resultlist= query.list();   

  } catch (HibernateException hibernateException)

{    log.error("search error!");   

 throw  hibernateException }

  return resultlist;  }

原创粉丝点击