最近很纠结hibernatetemplate如何进行分页,查了不少资料才找到相关的解决方法,其实这个方法也不是很好,本来hibernatetemplate已经封装好了sessionfactory,却硬要取session
@SuppressWarnings("unchecked")
public List<Blog> getListForPage(String hql,int offset,
int length) {
Session session=hibernateTemplate.getSessionFactory().getCurrentSession();
return session.createQuery("from Blog")
.setFirstResult(offset).setMaxResults(length)
.list();
}
上面这个方法是用来取一个页面多少条显示数据的
String hql = "from Blog b where b.bcategory=" + bcategory;
List<Blog> blogs = getListForPage(hql, (pageNo - 1) * pageCount,
pageCount);
此为调用上方法pagecount是用来记录一页显示多少条数据,pageno记录页码
除了上面问题外,我也碰到了用hql查询数据总数的问题,不知怎么的integer转为int型数据的intvalue方法总会出错,所以我用了下面这个方法
List<Integer> total = (List<Integer>) hibernateTemplate.find(
"select count(*) from Blog b where b.bcategory=?", bcategory);
int totalCount=Integer.parseInt(""+total.get(0)); //亲测能够把integer类型转为int类型