`
t225com
  • 浏览: 660948 次
文章分类
社区版块
存档分类
最新评论

Hibernate分页

 
阅读更多

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;

}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics