List of usage examples for org.hibernate.criterion Projection isGrouped
public boolean isGrouped();
From source file:org.candlepin.model.DetachedCandlepinQuery.java
License:Open Source License
/** * {@inheritDoc}/*from www .j a v a 2s. c o m*/ */ @Override @SuppressWarnings({ "unchecked", "checkstyle:indentation" }) public int getRowCount() { CriteriaImpl executable = (CriteriaImpl) this.getExecutableCriteria(); // Impl note: // We're using the projection method here over using a cursor to scroll the results due to // limitations on various connectors' cursor implementations. Some don't properly support // fast-forwarding/jumping (Oracle) and others fake the whole thing by running the query // and pretending to scroll (MySQL). Until these are addressed, the hack below is going to // be far more performant and significantly safer (which makes me sad). // Remove any ordering that may be applied (since we almost certainly won't have the field // available anymore) for (Iterator iterator = executable.iterateOrderings(); iterator.hasNext();) { iterator.next(); iterator.remove(); } Projection projection = executable.getProjection(); if (projection != null && projection.isGrouped()) { // We have a projection that alters the grouping of the query. We need to rebuild the // projection such that it gets our row count and properly applies the group by // statement. // The logic for this block is largely derived from this Stack Overflow posting: // http://stackoverflow.com/ // questions/32498229/hibernate-row-count-on-criteria-with-already-set-projection // // A safer alternative may be to generate a query that uses the given criteria as a // subquery (SELECT count(*) FROM (<criteria SQL>)), but is probably less performant // than this hack. CriteriaQueryTranslator translator = new CriteriaQueryTranslator( (SessionFactoryImplementor) this.session.getSessionFactory(), executable, executable.getEntityOrClassName(), CriteriaQueryTranslator.ROOT_SQL_ALIAS); executable.setProjection( Projections.projectionList().add(Projections.rowCount()).add(Projections.sqlGroupProjection( "count(count(1))", translator.getGroupBy(), new String[] {}, new Type[] {}))); } else { executable.setProjection(Projections.rowCount()); } Long count = (Long) executable.uniqueResult(); return count != null ? count.intValue() : 0; }