Example usage for org.hibernate.criterion CriteriaSpecification DISTINCT_ROOT_ENTITY

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

Introduction

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

Prototype

ResultTransformer DISTINCT_ROOT_ENTITY

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

Click Source Link

Document

Each row of results is a distinct instance of the root entity

Usage

From source file:gov.nih.nci.cananolab.service.sample.helper.SampleServiceHelper.java

License:BSD License

public Organization findOrganizationByName(String orgName) throws Exception {
    CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
            .getApplicationService();/* w  w w  .j  av a 2 s  .co  m*/
    DetachedCriteria crit = DetachedCriteria.forClass(Organization.class);
    crit.add(Restrictions.eq("name", orgName).ignoreCase());
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    List results = appService.query(crit);
    Organization org = null;
    for (int i = 0; i < results.size(); i++) {
        org = (Organization) results.get(i);
    }
    return org;
}

From source file:gov.nih.nci.cananolab.service.sample.helper.SampleServiceHelper.java

License:BSD License

public List<PointOfContact> findPointOfContactsBySampleId(String sampleId) throws Exception {
    if (!springSecurityAclService.currentUserHasReadPermission(Long.valueOf(sampleId),
            SecureClassesEnum.SAMPLE.getClazz())
            && !springSecurityAclService.currentUserHasWritePermission(Long.valueOf(sampleId),
                    SecureClassesEnum.SAMPLE.getClazz())) {
        throw new NoAccessException("User has no access to the sample " + sampleId);
    }/*from   w ww.j a va  2  s . co  m*/
    CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
            .getApplicationService();
    DetachedCriteria crit = DetachedCriteria.forClass(Sample.class)
            .add(Property.forName("id").eq(new Long(sampleId)));
    crit.setFetchMode("primaryPointOfContact", FetchMode.JOIN);
    crit.setFetchMode("primaryPointOfContact.organization", FetchMode.JOIN);
    crit.setFetchMode("otherPointOfContactCollection", FetchMode.JOIN);
    crit.setFetchMode("otherPointOfContactCollection.organization", FetchMode.JOIN);
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    List results = appService.query(crit);
    List<PointOfContact> pointOfContacts = new ArrayList<PointOfContact>();
    for (int i = 0; i < results.size(); i++) {
        Sample sample = (Sample) results.get(i);
        PointOfContact primaryPOC = sample.getPrimaryPointOfContact();
        pointOfContacts.add(primaryPOC);
        Collection<PointOfContact> otherPOCs = sample.getOtherPointOfContactCollection();
        pointOfContacts.addAll(otherPOCs);
    }
    return pointOfContacts;
}

From source file:gov.nih.nci.cananolab.service.sample.helper.SampleServiceHelper.java

License:BSD License

public PointOfContact findPointOfContactByNameAndOrg(String firstName, String lastName, String orgName)
        throws Exception {
    PointOfContact poc = null;/*from   w w  w . ja  v  a  2 s.co  m*/

    CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
            .getApplicationService();
    DetachedCriteria crit = DetachedCriteria.forClass(PointOfContact.class);
    crit.createAlias("organization", "organization");
    if (!StringUtils.isEmpty(lastName))
        crit.add(Restrictions.eq("lastName", lastName));
    if (!StringUtils.isEmpty(firstName))
        crit.add(Restrictions.eq("firstName", firstName));
    if (!StringUtils.isEmpty(orgName))
        crit.add(Restrictions.eq("organization.name", orgName));
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    List results = appService.query(crit);
    for (int i = 0; i < results.size(); i++) {
        poc = (PointOfContact) results.get(i);
    }
    return poc;
}

From source file:gov.nih.nci.cananolab.service.sample.impl.SampleServiceLocalImpl.java

License:BSD License

private Sample findFullyLoadedSampleByName(String sampleName) throws Exception {
    CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
            .getApplicationService();//  w w w . ja  va2s. co m
    // load composition and characterization separate because of Hibernate
    // join limitation
    DetachedCriteria crit = DetachedCriteria.forClass(Sample.class)
            .add(Property.forName("name").eq(sampleName).ignoreCase());
    Sample sample = null;

    // load composition and characterization separate because of
    // Hibernate join limitation
    crit.setFetchMode("primaryPointOfContact", FetchMode.JOIN);
    crit.setFetchMode("primaryPointOfContact.organization", FetchMode.JOIN);
    crit.setFetchMode("otherPointOfContactCollection", FetchMode.JOIN);
    crit.setFetchMode("otherPointOfContactCollection.organization", FetchMode.JOIN);
    crit.setFetchMode("keywordCollection", FetchMode.JOIN);
    crit.setFetchMode("publicationCollection", FetchMode.JOIN);
    crit.setFetchMode("publicationCollection.authorCollection", FetchMode.JOIN);
    crit.setFetchMode("publicationCollection.keywordCollection", FetchMode.JOIN);
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    List result = appService.query(crit);
    if (!result.isEmpty()) {
        sample = (Sample) result.get(0);
    }
    if (sample == null) {
        throw new NotExistException("Sample doesn't exist in the database");
    }

    // fully load composition
    SampleComposition comp = this.loadComposition(sample.getId().toString());
    sample.setSampleComposition(comp);

    // fully load characterizations
    List<Characterization> chars = this.loadCharacterizations(sample.getId().toString());
    if (chars != null && !chars.isEmpty()) {
        sample.setCharacterizationCollection(new HashSet<Characterization>(chars));
    } else {
        sample.setCharacterizationCollection(null);
    }
    return sample;
}

From source file:gov.nih.nci.cananolab.service.sample.impl.SampleServiceLocalImpl.java

License:BSD License

public List<PointOfContactBean> findPointOfContactsBySampleId(String sampleId) throws PointOfContactException {
    try {/*from  www . jav a 2 s.c o m*/
        CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
                .getApplicationService();
        DetachedCriteria crit = DetachedCriteria.forClass(Sample.class)
                .add(Property.forName("id").eq(new Long(sampleId)));
        crit.setFetchMode("primaryPointOfContact", FetchMode.JOIN);
        crit.setFetchMode("primaryPointOfContact.organization", FetchMode.JOIN);
        crit.setFetchMode("otherPointOfContactCollection", FetchMode.JOIN);
        crit.setFetchMode("otherPointOfContactCollection.organization", FetchMode.JOIN);
        crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        List results = appService.query(crit);
        List<PointOfContactBean> pointOfContactCollection = new ArrayList<PointOfContactBean>();
        for (int i = 0; i < results.size(); i++) {
            Sample particle = (Sample) results.get(i);
            PointOfContact primaryPOC = particle.getPrimaryPointOfContact();
            Collection<PointOfContact> otherPOCs = particle.getOtherPointOfContactCollection();
            pointOfContactCollection.add(new PointOfContactBean(primaryPOC));
            for (PointOfContact poc : otherPOCs) {
                pointOfContactCollection.add(new PointOfContactBean(poc));
            }
        }
        return pointOfContactCollection;
    } catch (Exception e) {
        String err = "Problem finding all PointOfContact collections with the given sample ID.";
        logger.error(err, e);
        throw new PointOfContactException(err, e);
    }
}

From source file:gov.nih.nci.cananolab.service.sample.impl.SampleServiceLocalImpl.java

License:BSD License

public void updatePOCAssociatedWithCharacterizations(String sampleName, Long oldPOCId, Long newPOCId)
        throws SampleException {
    try {//from  w w w .j av a2 s .  co  m
        CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
                .getApplicationService();
        DetachedCriteria crit = DetachedCriteria.forClass(Characterization.class);
        crit.createAlias("sample", "sample");
        crit.createAlias("pointOfContact", "poc");
        crit.add(Property.forName("poc.id").eq(oldPOCId));
        crit.add(Property.forName("sample.name").eq(sampleName));
        crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        List results = appService.query(crit);
        for (int i = 0; i < results.size(); i++) {
            Characterization achar = (Characterization) results.get(i);
            // update POC to the new ID
            achar.getPointOfContact().setId(newPOCId);
            appService.saveOrUpdate(achar);
        }
    } catch (Exception e) {
        String err = "Error in updating POC associated sample characterizations " + sampleName + ". "
                + e.getMessage();
        logger.error(err, e);
        throw new SampleException(err, e);
    }
}

From source file:grails.orm.HibernateCriteriaBuilder.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override/*  w  w  w .j  a v a2 s  .com*/
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);
}

From source file:net.jforum.core.hibernate.ForumDAO.java

License:Open Source License

/**
 * @see net.jforum.repository.ForumRepository#getTopicsPendingModeration(net.jforum.entities.Forum)
 *//*w  ww  .  j ava2 s .c  om*/
@SuppressWarnings("unchecked")
public List<Topic> getTopicsPendingModeration(Forum forum) {
    return this.session()
            .createQuery("select t from Topic t left join fetch t.posts post" + " where post.moderate = true"
                    + " or t.pendingModeration = true" + " and t.forum = :forum" + " order by t.id, post.id")
            .setEntity("forum", forum).setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
            .setComment("forumDAO.getTopicsPendingModeration").list();
}

From source file:net.jforum.repository.ForumDao.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<Topic> getTopicsPendingModeration(Forum forum) {
    return session
            .createQuery("select t from Topic t left join fetch t.posts post" + " where post.moderate = true"
                    + " or t.pendingModeration = true" + " and t.forum = :forum" + " order by t.id, post.id")
            .setEntity("forum", forum).setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
            .setComment("forumDAO.getTopicsPendingModeration").list();
}

From source file:net.purnama.pureff.dao.AdjustmentDao.java

public List<AdjustmentEntity> getAdjustmentList() {
    Session session = this.sessionFactory.getCurrentSession();
    Criteria c = session.createCriteria(AdjustmentEntity.class);
    c.addOrder(Order.desc("date"));
    c.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return c.list();
}