diff --git a/grails-hibernate/src/main/groovy/grails/orm/PagedResultList.java b/grails-hibernate/src/main/groovy/grails/orm/PagedResultList.java index 89abf10ec2d..444012e1639 100644 --- a/grails-hibernate/src/main/groovy/grails/orm/PagedResultList.java +++ b/grails-hibernate/src/main/groovy/grails/orm/PagedResultList.java @@ -27,6 +27,7 @@ import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.criterion.Projections; +import org.hibernate.impl.CriteriaImpl; import org.springframework.orm.hibernate3.HibernateCallback; /** @@ -159,14 +160,19 @@ public List subList(int i, int i1) { public int getTotalCount() { if(totalCount == Integer.MIN_VALUE) { totalCount = (Integer)hibernateTemplate.execute(new HibernateCallback() { - public Object doInHibernate(Session session) - throws HibernateException, - SQLException { - hibernateTemplate.applySettings(criteria); - criteria.setFirstResult(0); - criteria.setProjection(Projections.rowCount()); - int totalCount = ((Number)criteria.uniqueResult()).intValue(); - return totalCount; + public Object doInHibernate(Session session) throws HibernateException, SQLException { + CriteriaImpl impl = (CriteriaImpl) criteria; + Criteria totalCriteria = session.createCriteria(impl.getEntityOrClassName()); + hibernateTemplate.applySettings(totalCriteria); + + Iterator iterator = impl.iterateExpressionEntries(); + while (iterator.hasNext()) { + CriteriaImpl.CriterionEntry entry = (CriteriaImpl.CriterionEntry) iterator.next(); + totalCriteria.add(entry.getCriterion()); + } + totalCriteria.setProjection(impl.getProjection()); + totalCriteria.setProjection(Projections.rowCount()); + return ((Number)totalCriteria.uniqueResult()).intValue(); } }); } diff --git a/grails-test-suite-persistence/src/test/groovy/org/codehaus/groovy/grails/orm/hibernate/TotalCountWithOrderSpec.groovy b/grails-test-suite-persistence/src/test/groovy/org/codehaus/groovy/grails/orm/hibernate/TotalCountWithOrderSpec.groovy new file mode 100644 index 00000000000..3f1fb23f158 --- /dev/null +++ b/grails-test-suite-persistence/src/test/groovy/org/codehaus/groovy/grails/orm/hibernate/TotalCountWithOrderSpec.groovy @@ -0,0 +1,36 @@ +package org.codehaus.groovy.grails.orm.hibernate + +import grails.persistence.Entity + +/** + * Tests usage of total count when an order by is used + */ +class TotalCountWithOrderSpec extends GormSpec{ + + void "Test total with with order by"() { + when:"A pagination query is used with order by" + def criteria = Post.createCriteria() + def results = criteria.list (max: 10, offset: 5) { + order("dateCreated", "desc") + } + + then:"Both total count and results work" + results.size() == 0 + results.totalCount == 0 + } + + @Override + List getDomainClasses() { + [Post] + } +} +@Entity +class Post { + + String title + Date dateCreated + + static constraints = { + } +} +