关闭

Hibernate分页

526人阅读 评论(0) 收藏 举报

DAO类

package com.coolpep.order.dao;

import java.util.List;

public interface PaginationDAO {
 
 public int getCount(String cond) throws Exception;
 
 public int getPage(String cond) throws Exception;
 
 public List getPage(String cond, int page, int cont) throws Exception;

}

DAPImpl类

package com.coolpep.order.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.coolpep.order.dao.PaginationDAO;
import com.coolpep.order.factory.DAOFactory;

public class PaginationDAOImpl implements PaginationDAO {
 
 private Session session = null;
 private int totalPage;   //总页数
 private int totalCount;  //总行数
 private int pageSize = 5;   //页面显示条数
 private int currentPage; //当前页码

 public PaginationDAOImpl() {
  // TODO Auto-generated constructor stub
  this.session = new Configuration().configure().buildSessionFactory().openSession();
 }
 
 
 /**
  * 汇总数据获取数据总行数
  *
  * */
 public int getCount(String cond) throws Exception{
  int totalCount = 0;

  try {
   Transaction tran = this.session.beginTransaction();
   Query q = this.session.createQuery("select count(*) from Orders where osource=?");
   q.setString(0, cond);
   List list = q.list();
   totalCount = ((Integer) list.get(0)).intValue();
   tran.commit();
   this.session.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
  
  return totalCount;
 }
 
 /**
  * 汇总数据获取数据总页数
  *
  * */
 public int getPage(String cond) throws Exception{
  
  try{
   Transaction tran = this.session.beginTransaction();
   DAOFactory dao = new DAOFactory();
   totalCount = dao.getPaginationDAOInstance().getCount(cond);
   if(totalCount%pageSize>0)
    totalPage = totalCount/pageSize + 1;
   if(totalCount%pageSize==0)
    totalPage = totalCount/pageSize;
   if(totalCount%pageSize<0)
    totalPage = totalCount/pageSize;
   tran.commit();
   this.session.close();
  } catch (Exception e){
   e.printStackTrace();
  }
  return totalPage;
 }
 
 /**
  * 根据条件分页
  *
  * @param cond  查找条件
  * @param page  当前页数
  * @param count
  * */
 public List getPage(String cond, int currentPage, int pageSize){
  List list = null;
  String hql = "from Orders where osource=?";
  Query q = this.session.createQuery(hql);
  q.setString(0, cond);
  q.setFirstResult(pageSize*(currentPage-1));
  q.setMaxResults(pageSize);
  list = q.list();
  return list;
  
 }
 

}
 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:205870次
    • 积分:2902
    • 等级:
    • 排名:第12670名
    • 原创:72篇
    • 转载:48篇
    • 译文:0篇
    • 评论:30条
    文章分类
    最新评论