我写了个通用的方法,可以根据自己传入的HQL作相应的查询, 问题是如何得到 总记录数呢?  : public PageModel searchByHql(PageModel pageModel, String hql) {
List list = new ArrayList();
final int pageNo = pageModel.getPageNo();
final int pageSize = pageModel.getPageSize();
try { 
Session session=this.getHibernateTemplate().getSessionFactory().getCurrentSession();
list = session.createQuery(hql).setFirstResult((pageNo - 1) * pageSize).setMaxResults(pageSize).list();
pageModel.setTotalRecords(this.getTotalRecords(hql));
pageModel.setList(list);

}catch(Exception e) {
e.printStackTrace();
throw new AppException("查询异常");
}
return pageModel;

}如代码中的红色部分 本来我写一个方法 select count(*) +hql 但是很多hql语句中都有 order by等 就查不出来啊!诸位前辈有什么好办法不,最好有一个通用的方法,
 最好不是先把所有的都查出来 在取大小 
 

解决方案 »

  1.   

    搞定了 :private int getTotalRecords(String hql) {
    Long totalRecords = 0L;
    String s1; int i = hql.toLowerCase().indexOf("from");
    int j = hql.toLowerCase().indexOf("order by");
    if (j > 0)
    s1 = (new StringBuilder()).append("select count(*) ").append(
    hql.substring(i, j)).toString();
    else
    s1 = (new StringBuilder()).append("select count(*) ").append(
    hql.substring(i, hql.length())).toString();

    try {
    totalRecords = (Long) this.getSession().createQuery(s1).uniqueResult();
    return totalRecords.intValue();
    } catch (RuntimeException e) {
    return -1;
    }
    }