Hibernate返回分页记录总数

select count(*) from ”这句sql我估计没有有不知道是干什么用的,在jdbc,ibatis里很容易就会返回一个int或者Object对象,使得程序员很容易得到这个分页记录总数,可以在hibernate中就稍微有些麻烦了,因为hibernate用的是hql,但是虽然是hql但是也是有办法滴。

其实把hql当成sql用就ok了,代码也就几句:

public int contactsCount() {
		final String hql = "select count(*) from xxx";
		return  (int) this.getHibernateTemplate().execute(new HibernateCallback<Integer>() {
			public Integer doInHibernate(Session session) throws HibernateException, SQLException {
				Query query = session.createQuery(hql);
				List result=query.list();
				return Integer.parseInt(result.get(0).toString());
			}
		});
	}

  通过debug可以看到这个result里面成员的类型是Long型而且result的长度应该是1,所以在返回类型上做一些转换就可以用了。

猜你喜欢

转载自286.iteye.com/blog/1170607