Example usage for org.hibernate.internal CriteriaImpl setProjection

List of usage examples for org.hibernate.internal CriteriaImpl setProjection

Introduction

In this page you can find the example usage for org.hibernate.internal CriteriaImpl setProjection.

Prototype

@Override
    public Criteria setProjection(Projection projection) 

Source Link

Usage

From source file:org.babyfish.hibernate.model.loader.HibernateObjectModelScalarLoader.java

License:Open Source License

@SuppressWarnings("unchecked")
private void loadScalarsImpl(Collection<ObjectModel> objectModels, int[] scalarPropertyIds) {
    boolean batch = objectModels.size() > 1;
    ObjectModel firstObjectModel = objectModels.iterator().next();
    JPAObjectModelMetadata jpaObjectModelMetadata = (JPAObjectModelMetadata) firstObjectModel
            .getObjectModelMetadata();// w  ww  . j  ava2 s.  c om
    JPAScalarProperty entityIdProperty = jpaObjectModelMetadata.getEntityIdProperty();
    Map<Object, ObjectModel> idMap = new LinkedHashMap<>();
    for (ObjectModel objectModel : objectModels) {
        idMap.put(objectModel.getScalar(entityIdProperty.getId()), objectModel);
    }

    CriteriaImpl criteria = new CriteriaImpl(jpaObjectModelMetadata.getOwnerClass().getName(), session);
    ProjectionList projectionList = Projections.projectionList();
    if (batch) {
        String ownerIdPropertyName = entityIdProperty.getOwnerProperty().getName();
        projectionList.add(Projections.property(ownerIdPropertyName));
    }
    for (int scalarPropertyId : scalarPropertyIds) {
        String ownerPropertyName = jpaObjectModelMetadata.getScalarProperty(scalarPropertyId).getOwnerProperty()
                .getName();
        projectionList.add(Projections.property(ownerPropertyName));
    }
    if (batch) {
        criteria.add(Restrictions.in(entityIdProperty.getOwnerProperty().getName(), idMap.keySet()));
    } else {
        criteria.add(Restrictions.eq(entityIdProperty.getOwnerProperty().getName(),
                idMap.keySet().iterator().next()));
    }
    criteria.setProjection(projectionList).setResultTransformer(new ResultTransformer() {

        private static final long serialVersionUID = -1387181124646452221L;

        @Override
        public Object transformTuple(Object[] tuple, String[] aliases) {
            return tuple;
        }

        @SuppressWarnings("rawtypes")
        @Override
        public List transformList(List collection) {
            return collection;
        }
    });
    List<Object[]> tuples;
    FlushMode oldFlushMode = session.getFlushMode();
    session.setFlushMode(FlushMode.MANUAL);
    try {
        tuples = (List<Object[]>) criteria.list();
    } finally {
        session.setFlushMode(oldFlushMode);
    }
    if (batch) {
        for (Object[] tuple : tuples) {
            ObjectModel objectModel = idMap.get(tuple[0]);
            for (int i = scalarPropertyIds.length - 1; i >= 0; i--) {
                objectModel.setScalar(scalarPropertyIds[i], tuple[i + 1]);
            }
        }
    } else {
        Object[] firstTuple = tuples.get(0);
        for (int i = scalarPropertyIds.length - 1; i >= 0; i--) {
            firstObjectModel.setScalar(scalarPropertyIds[i], firstTuple[i]);
        }
    }
}

From source file:org.candlepin.model.DetachedCandlepinQuery.java

License:Open Source License

/**
 * {@inheritDoc}/*from www. j  a va2 s .co  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;
}