Example usage for org.hibernate.criterion CriteriaSpecification ROOT_ENTITY

List of usage examples for org.hibernate.criterion CriteriaSpecification ROOT_ENTITY

Introduction

In this page you can find the example usage for org.hibernate.criterion CriteriaSpecification ROOT_ENTITY.

Prototype

ResultTransformer ROOT_ENTITY

To view the source code for org.hibernate.criterion CriteriaSpecification ROOT_ENTITY.

Click Source Link

Document

Each row of results is an instance of the root entity

Usage

From source file:com.zc.orm.hibernate.HibernateDao.java

License:Apache License

/**
 * countCriteria???/* w w w . j  ava 2  s  .c o  m*/
 */
@SuppressWarnings("unchecked")
protected long countCriteriaResult(final Criteria c) {
    CriteriaImpl impl = (CriteriaImpl) c;

    // Projection?ResultTransformer?OrderBy?????Count?
    Projection projection = impl.getProjection();
    ResultTransformer transformer = impl.getResultTransformer();

    List<CriteriaImpl.OrderEntry> orderEntries = null;
    try {
        orderEntries = (List) Reflector.getFieldValue(impl, "orderEntries");
        Reflector.setFieldValue(impl, "orderEntries", new ArrayList());
    } catch (Exception e) {
        logger.error("??:{}", e.getMessage());
    }

    // Count
    Long totalCountObject = (Long) c.setProjection(Projections.rowCount()).uniqueResult();
    long totalCount = (totalCountObject != null) ? totalCountObject : 0;

    // ?Projection,ResultTransformerOrderBy???
    c.setProjection(projection);

    if (projection == null) {
        c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
    }
    if (transformer != null) {
        c.setResultTransformer(transformer);
    }
    try {
        Reflector.setFieldValue(impl, "orderEntries", orderEntries);
    } catch (Exception e) {
        logger.error("??:{}", e.getMessage());
    }

    return totalCount;
}

From source file:de.decidr.model.commands.tenant.GetAllTenantsCommand.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from w  w w. j a v a  2 s . c o  m*/
public void transactionAllowed(TransactionStartedEvent evt) throws TransactionException {

    PaginatingCriteria c = new PaginatingCriteria(TenantSummaryView.class, evt.getSession());
    Filters.apply(c, filters, paginator);

    result = c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY).list();
}

From source file:de.decidr.model.commands.tenant.GetTenantsToApproveCommand.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from  w  w w  . j a v  a  2  s  .com*/
public void transactionAllowed(TransactionStartedEvent evt) throws TransactionException {

    result = new ArrayList<TenantWithAdminView>();

    PaginatingCriteria c = new PaginatingCriteria(TenantWithAdminView.class, evt.getSession());
    c.add(Restrictions.isNull("approvedSince"));

    Filters.apply(c, filters, paginator);

    result = c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY).list();
}

From source file:de.decidr.model.commands.tenant.GetUsersOfTenantCommand.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//w w  w  . j  a  v  a2s.c om
public void transactionAllowed(TransactionStartedEvent evt) throws TransactionException {

    PaginatingCriteria c = new PaginatingCriteria(User.class, "u", evt.getSession());

    String rootAlias = c.getAlias();

    // Create criterion "user is a member of the tenant"
    DetachedCriteria memberRel = DetachedCriteria.forClass(UserIsMemberOfTenant.class, "memberRel");
    memberRel.add(Property.forName("memberRel.user.id").eqProperty(rootAlias + ".id"))
            .add(Property.forName("memberRel.tenant.id").eq(getTenantId()));

    // Create criterion "user is the administrator of the tenant"
    DetachedCriteria adminRel = DetachedCriteria.forClass(Tenant.class, "adminTenant");
    adminRel.add(Property.forName("adminTenant.id").eq(getTenantId()))
            .add(Property.forName("adminTenant.admin.id").eqProperty(rootAlias + ".id"));

    /*
     * Workaround for Hibernate issue HHH-993: Criteria subquery without
     * projection fails throwing NullPointerException.
     * 
     * Additionally, Mysql doesn't seem to like aliases in EXISTS
     * subqueries, so we have to explicitly specify "*"
     */
    Projection existsSubqueryProjection = Projections.sqlProjection("*", new String[0], new Type[0]);
    memberRel.setProjection(existsSubqueryProjection);
    adminRel.setProjection(existsSubqueryProjection);

    c.add(Restrictions.or(Subqueries.exists(memberRel), Subqueries.exists(adminRel)));

    // preload user profiles - no lazy loading desired
    c.createCriteria("userProfile", CriteriaSpecification.LEFT_JOIN);
    c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);

    if (paginator != null) {
        paginator.apply(c);
    }
    result = c.list();
}

From source file:de.decidr.model.commands.tenant.GetWorkflowInstancesCommand.java

License:Apache License

@SuppressWarnings("unchecked")
@Override// www .j ava  2 s .c o m
public void transactionAllowed(TransactionStartedEvent evt) throws TransactionException {

    String hql = "select t.id from Tenant t where t.id  = :tenantId";
    Boolean tenantExists = evt.getSession().createQuery(hql).setLong("tenantId", getTenantId())
            .uniqueResult() != null;

    if (!tenantExists) {
        throw new EntityNotFoundException(Tenant.class, getTenantId());
    }

    PaginatingCriteria c = new PaginatingCriteria(WorkflowInstance.class, evt.getSession());

    Criteria c2;

    // create criteria 2nd level and project to name
    c2 = c.createCriteria("deployedWorkflowModel", CriteriaSpecification.INNER_JOIN);

    // create criteria 3rd level and project to name
    c2.createCriteria("tenant", CriteriaSpecification.INNER_JOIN).add(Restrictions.idEq(getTenantId()));

    if (paginator != null) {
        paginator.apply(c);
    }

    c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);

    result = c.list();
}

From source file:de.decidr.model.commands.tenant.GetWorkflowModelsCommand.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from  w  ww .j a  v a 2s  .co m*/
public void transactionAllowed(TransactionStartedEvent evt) throws TransactionException {

    Tenant tenant = fetchTenant(evt.getSession());

    PaginatingCriteria criteria = new PaginatingCriteria(ExecutableWorkflowModelView.class, evt.getSession());

    criteria.add(Restrictions.eq("tenantId", tenant.getId()));

    Filters.apply(criteria, filters, paginator);

    result = criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY).list();
}

From source file:de.decidr.model.commands.user.GetAdministratedWorkflowModelsCommand.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*w ww .j  a v  a2  s .  co m*/
public void transactionAllowed(TransactionStartedEvent evt) throws TransactionException {
    result = null;

    // does the user exist? returning an empty list might be ambigous.
    String hql = "select u.id from User u where u.id = :userId";
    Object id = evt.getSession().createQuery(hql).setLong("userId", getUserId()).setMaxResults(1)
            .uniqueResult();

    if (id == null) {
        throw new EntityNotFoundException(User.class, getUserId());
    }

    /*
     * Criteria that represent the following query:
     * 
     * "from WorkflowModel w where w.tenant.id = DEFAULT_TENANT_ID or
     * (exists(from UserAdministratesWorkflowModel rel where
     * rel.workflowModel = w and rel.user.id = :userId) or w.tenant.admin.id
     * = :userId) or exists (from SystemSettings s where s.admin.id =
     * :userId))"
     */
    PaginatingCriteria criteria = new PaginatingCriteria(WorkflowModel.class, "m", evt.getSession());

    /*
     * A user administers a workflow model if there's an explicit
     * relationship.
     */
    DetachedCriteria explicitWorkflowAdminCriteria = DetachedCriteria
            .forClass(UserAdministratesWorkflowModel.class, "rel");
    explicitWorkflowAdminCriteria
            .add(Restrictions.conjunction().add(Restrictions.eqProperty("rel.workflowModel.id", "m.id"))
                    .add(Restrictions.eq("rel.user.id", getUserId())));

    /*
     * A user administers *any* workflow model if he is the super admin.
     */
    DetachedCriteria superAdminCriteria = DetachedCriteria.forClass(SystemSettings.class, "s");
    superAdminCriteria.add(Restrictions.eq("s.superAdmin.id", getUserId()));

    /*
     * Workaround for Hibernate issue HHH-993: Criteria subquery without
     * projection fails throwing NullPointerException.
     * 
     * Additionally, Mysql doesn't seem to like aliases in EXISTS
     * subqueries, so we have to explicitly specify "*"
     */
    explicitWorkflowAdminCriteria.setProjection(Projections.sqlProjection("*", new String[0], new Type[0]));
    superAdminCriteria.setProjection(Projections.sqlProjection("*", new String[0], new Type[0]));

    /*
     * Finally, a user administers a workflow model if he is the tenant
     * admin of the tenant that owns the model. We now add each criterion to
     * a disjuncion.
     */
    criteria.createAlias("tenant", "t");
    Disjunction allAdministrationCriteria = Restrictions.disjunction();
    allAdministrationCriteria.add(Subqueries.exists(superAdminCriteria));
    allAdministrationCriteria.add(Subqueries.exists(explicitWorkflowAdminCriteria));
    allAdministrationCriteria.add(Restrictions.eq("t.admin.id", getUserId()));

    /*
     * Everyone is a workflow admin for models within the default tenant.
     */
    criteria.add(Restrictions.disjunction().add(allAdministrationCriteria)
            .add(Restrictions.eq("m.tenant.id", DecidrGlobals.DEFAULT_TENANT_ID)));

    Filters.apply(criteria, filters, paginator);

    criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);

    result = criteria.list();
}

From source file:de.decidr.model.commands.workflowmodel.GetPublishedWorkflowModelsCommand.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//w  ww. j av  a2 s.  c  o  m
public void transactionAllowed(TransactionStartedEvent evt) throws TransactionException {

    PaginatingCriteria crit = new PaginatingCriteria(WorkflowModel.class, evt.getSession());

    /*
     * We only want published workflow models.
     */
    new EqualsFilter(true, "published", true).apply(crit);

    /*
     * Make the "tenant" property available even after the session has been
     * closed.
     */
    crit.setFetchMode("tenant", FetchMode.JOIN);

    Filters.apply(crit, filters, paginator);

    result = crit.setResultTransformer(CriteriaSpecification.ROOT_ENTITY).list();
}

From source file:de.decidr.model.commands.workflowmodel.WorkflowModelCommand.java

License:Apache License

/**
 * Fetches the current deployed version of the workflow model.
 * /*  w w  w . j a v  a2  s .c o m*/
 * @param session
 *            current Hibernate Session
 * @return the current deployed version of the workflow model or null if
 *         there is no current deplyoed version.
 */
public DeployedWorkflowModel fetchCurrentDeployedWorkflowModel(Session session) {
    Criteria crit = session.createCriteria(DeployedWorkflowModel.class, "dwm");

    crit.createCriteria("originalWorkflowModel", "owm")
            .add(Restrictions.eqProperty("owm.version", "dwm.version"));

    crit.add(Restrictions.eq("originalWorkflowModel.id", getWorkflowModelId()));

    return (DeployedWorkflowModel) crit.setResultTransformer(CriteriaSpecification.ROOT_ENTITY).uniqueResult();
}

From source file:grails.orm.HibernateCriteriaBuilder.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override//from w  ww .jav  a2 s. c om
public Object invokeMethod(String name, Object obj) {
    Object[] args = obj.getClass().isArray() ? (Object[]) obj : new Object[] { obj };

    if (paginationEnabledList && SET_RESULT_TRANSFORMER_CALL.equals(name) && args.length == 1
            && args[0] instanceof ResultTransformer) {
        resultTransformer = (ResultTransformer) args[0];
        return null;
    }

    if (isCriteriaConstructionMethod(name, args)) {
        if (criteria != null) {
            throwRuntimeException(new IllegalArgumentException("call to [" + name + "] not supported here"));
        }

        if (name.equals(GET_CALL)) {
            uniqueResult = true;
        } else if (name.equals(SCROLL_CALL)) {
            scroll = true;
        } else if (name.equals(COUNT_CALL)) {
            count = true;
        } else if (name.equals(LIST_DISTINCT_CALL)) {
            resultTransformer = CriteriaSpecification.DISTINCT_ROOT_ENTITY;
        }

        createCriteriaInstance();

        // Check for pagination params
        if (name.equals(LIST_CALL) && args.length == 2) {
            paginationEnabledList = true;
            orderEntries = new ArrayList<Order>();
            invokeClosureNode(args[1]);
        } else {
            invokeClosureNode(args[0]);
        }

        if (resultTransformer != null) {
            criteria.setResultTransformer(resultTransformer);
        }
        Object result;
        if (!uniqueResult) {
            if (scroll) {
                result = criteria.scroll();
            } else if (count) {
                criteria.setProjection(Projections.rowCount());
                result = criteria.uniqueResult();
            } else if (paginationEnabledList) {
                // Calculate how many results there are in total. This has been
                // moved to before the 'list()' invocation to avoid any "ORDER
                // BY" clause added by 'populateArgumentsForCriteria()', otherwise
                // an exception is thrown for non-string sort fields (GRAILS-2690).
                criteria.setFirstResult(0);
                criteria.setMaxResults(Integer.MAX_VALUE);
                criteria.setProjection(Projections.rowCount());
                int totalCount = ((Number) criteria.uniqueResult()).intValue();

                // Restore the previous projection, add settings for the pagination parameters,
                // and then execute the query.
                if (projectionList != null && projectionList.getLength() > 0) {
                    criteria.setProjection(projectionList);
                } else {
                    criteria.setProjection(null);
                }
                for (Order orderEntry : orderEntries) {
                    criteria.addOrder(orderEntry);
                }
                if (resultTransformer == null) {
                    criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
                } else if (paginationEnabledList) {
                    // relevant to GRAILS-5692
                    criteria.setResultTransformer(resultTransformer);
                }
                // GRAILS-7324 look if we already have association to sort by
                Map argMap = (Map) args[0];
                final String sort = (String) argMap.get(GrailsHibernateUtil.ARGUMENT_SORT);
                if (sort != null) {
                    boolean ignoreCase = true;
                    Object caseArg = argMap.get(GrailsHibernateUtil.ARGUMENT_IGNORE_CASE);
                    if (caseArg instanceof Boolean) {
                        ignoreCase = (Boolean) caseArg;
                    }
                    final String orderParam = (String) argMap.get(GrailsHibernateUtil.ARGUMENT_ORDER);
                    final String order = GrailsHibernateUtil.ORDER_DESC.equalsIgnoreCase(orderParam)
                            ? GrailsHibernateUtil.ORDER_DESC
                            : GrailsHibernateUtil.ORDER_ASC;
                    int lastPropertyPos = sort.lastIndexOf('.');
                    String associationForOrdering = lastPropertyPos >= 0 ? sort.substring(0, lastPropertyPos)
                            : null;
                    if (associationForOrdering != null && aliasMap.containsKey(associationForOrdering)) {
                        addOrder(criteria, aliasMap.get(associationForOrdering) + "."
                                + sort.substring(lastPropertyPos + 1), order, ignoreCase);
                        // remove sort from arguments map to exclude from default processing.
                        @SuppressWarnings("unchecked")
                        Map argMap2 = new HashMap(argMap);
                        argMap2.remove(GrailsHibernateUtil.ARGUMENT_SORT);
                        argMap = argMap2;
                    }
                }
                GrailsHibernateUtil.populateArgumentsForCriteria(grailsApplication, targetClass, criteria,
                        argMap);
                PagedResultList pagedRes = new PagedResultList(criteria.list());

                // Updated the paged results with the total number of records calculated previously.
                pagedRes.setTotalCount(totalCount);
                result = pagedRes;
            } else {
                result = criteria.list();
            }
        } else {
            result = GrailsHibernateUtil.unwrapIfProxy(criteria.uniqueResult());
        }
        if (!participate) {
            hibernateSession.close();
        }
        return result;
    }

    if (criteria == null)
        createCriteriaInstance();

    MetaMethod metaMethod = getMetaClass().getMetaMethod(name, args);
    if (metaMethod != null) {
        return metaMethod.invoke(this, args);
    }

    metaMethod = criteriaMetaClass.getMetaMethod(name, args);
    if (metaMethod != null) {
        return metaMethod.invoke(criteria, args);
    }
    metaMethod = criteriaMetaClass.getMetaMethod(GrailsClassUtils.getSetterName(name), args);
    if (metaMethod != null) {
        return metaMethod.invoke(criteria, args);
    }

    if (isAssociationQueryMethod(args) || isAssociationQueryWithJoinSpecificationMethod(args)) {
        final boolean hasMoreThanOneArg = args.length > 1;
        Object callable = hasMoreThanOneArg ? args[1] : args[0];
        int joinType = hasMoreThanOneArg ? (Integer) args[0] : CriteriaSpecification.INNER_JOIN;

        if (name.equals(AND) || name.equals(OR) || name.equals(NOT)) {
            if (criteria == null) {
                throwRuntimeException(
                        new IllegalArgumentException("call to [" + name + "] not supported here"));
            }

            logicalExpressionStack.add(new LogicalExpression(name));
            invokeClosureNode(callable);

            LogicalExpression logicalExpression = logicalExpressionStack
                    .remove(logicalExpressionStack.size() - 1);
            addToCriteria(logicalExpression.toCriterion());

            return name;
        }

        if (name.equals(PROJECTIONS) && args.length == 1 && (args[0] instanceof Closure)) {
            if (criteria == null) {
                throwRuntimeException(
                        new IllegalArgumentException("call to [" + name + "] not supported here"));
            }

            projectionList = Projections.projectionList();
            invokeClosureNode(callable);

            if (projectionList != null && projectionList.getLength() > 0) {
                criteria.setProjection(projectionList);
            }

            return name;
        }

        final PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(targetClass, name);
        if (pd != null && pd.getReadMethod() != null) {
            ClassMetadata meta = sessionFactory.getClassMetadata(targetClass);
            Type type = meta.getPropertyType(name);
            if (type.isAssociationType()) {
                String otherSideEntityName = ((AssociationType) type)
                        .getAssociatedEntityName((SessionFactoryImplementor) sessionFactory);
                Class oldTargetClass = targetClass;
                targetClass = sessionFactory.getClassMetadata(otherSideEntityName)
                        .getMappedClass(EntityMode.POJO);
                if (targetClass.equals(oldTargetClass) && !hasMoreThanOneArg) {
                    joinType = CriteriaSpecification.LEFT_JOIN; // default to left join if joining on the same table
                }
                associationStack.add(name);
                final String associationPath = getAssociationPath();
                createAliasIfNeccessary(name, associationPath, joinType);
                // the criteria within an association node are grouped with an implicit AND
                logicalExpressionStack.add(new LogicalExpression(AND));
                invokeClosureNode(callable);
                aliasStack.remove(aliasStack.size() - 1);
                if (!aliasInstanceStack.isEmpty()) {
                    aliasInstanceStack.remove(aliasInstanceStack.size() - 1);
                }
                LogicalExpression logicalExpression = logicalExpressionStack
                        .remove(logicalExpressionStack.size() - 1);
                if (!logicalExpression.args.isEmpty()) {
                    addToCriteria(logicalExpression.toCriterion());
                }
                associationStack.remove(associationStack.size() - 1);
                targetClass = oldTargetClass;

                return name;
            }
        }
    } else if (args.length == 1 && args[0] != null) {
        if (criteria == null) {
            throwRuntimeException(new IllegalArgumentException("call to [" + name + "] not supported here"));
        }

        Object value = args[0];
        Criterion c = null;
        if (name.equals(ID_EQUALS)) {
            return eq("id", value);
        }

        if (name.equals(IS_NULL) || name.equals(IS_NOT_NULL) || name.equals(IS_EMPTY)
                || name.equals(IS_NOT_EMPTY)) {
            if (!(value instanceof String)) {
                throwRuntimeException(new IllegalArgumentException(
                        "call to [" + name + "] with value [" + value + "] requires a String value."));
            }
            String propertyName = calculatePropertyName((String) value);
            if (name.equals(IS_NULL)) {
                c = Restrictions.isNull(propertyName);
            } else if (name.equals(IS_NOT_NULL)) {
                c = Restrictions.isNotNull(propertyName);
            } else if (name.equals(IS_EMPTY)) {
                c = Restrictions.isEmpty(propertyName);
            } else if (name.equals(IS_NOT_EMPTY)) {
                c = Restrictions.isNotEmpty(propertyName);
            }
        }

        if (c != null) {
            return addToCriteria(c);
        }
    }

    throw new MissingMethodException(name, getClass(), args);
}