在hibernate中,在查询总数时,会使用如下方法;

public Integer getCount(final DetachedCriteria detachedCriteria) {
         return (Integer) getHibernateTemplate().execute(new HibernateCallback() {

@Override
             public Object doInHibernate(Session session)
                     throws HibernateException, SQLException {
                 Criteria criteria = detachedCriteria.getExecutableCriteria(session);

int totalCount = (Integer) criteria.setProjection(
                         Projections.rowCount()).uniqueResult();

criteria.setProjection(null);
//
                 criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
                 return totalCount;
             }
         }, true);
     }

有时在int totalCount = (Integer) criteria.setProjection(
                         Projections.rowCount()).uniqueResult();这一句会报NullPointException。

原因是这句代码之前出现了criteria.addOrder(Order.desc("sc.createTime"));这样的排序语句。

把排序语句放到总数查询的后面即可。有时候你注释了缓存也仍然会影响的,需要把注释的语句也删掉。

05-02 07:34