Example usage for org.hibernate.criterion Projections distinct

List of usage examples for org.hibernate.criterion Projections distinct

Introduction

In this page you can find the example usage for org.hibernate.criterion Projections distinct.

Prototype

public static Projection distinct(Projection projection) 

Source Link

Document

Create a distinct projection from a projection.

Usage

From source file:org.openhie.openempi.blocking.basicblockinghp.dao.hibernate.BlockingDaoHibernate.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
public List<NameValuePair> getDistinctKeyValuePairs(final List<String> fields) {
    return (List<NameValuePair>) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            ProjectionList projectionList = Projections.projectionList();
            for (String field : fields) {
                projectionList.add(Projections.property(field), field);
            }/*w  ww  .  j  av  a2s  .c  o  m*/
            projectionList.add(Projections.property("personId"), "personId");
            org.hibernate.Criteria criteria = session.createCriteria(Person.class, "person_")
                    .setProjection(Projections.distinct(projectionList));
            for (String field : fields) {
                String property = "person_." + field;
                criteria.add(Expression.isNotNull(property));
                criteria.addOrder(Order.asc(property));
            }
            // We don't want to load deleted values
            criteria.add(Expression.isNull("dateVoided"));
            log.debug("Blocking criteria query: " + criteria.toString());
            List list = (List<Object[]>) criteria.list();
            List<NameValuePair> pairs = new ArrayList<NameValuePair>(list.size());
            if (list.size() == 0) {
                return pairs;
            }
            List<Object[]> objectArrayValues = (List<Object[]>) list;
            for (Object[] row : objectArrayValues) {
                // The last entry is always the person ID
                Integer personId = (Integer) row[row.length - 1];
                Object[] fields = Arrays.copyOfRange(row, 0, row.length - 1);
                String blockingKeyValue = BlockingKeyValueGenerator.generateBlockingKeyValue(fields);
                NameValuePair pair = new NameValuePair(blockingKeyValue, personId);
                pairs.add(pair);
            }
            return pairs;
        }
    });
}

From source file:org.openhie.openempi.dao.hibernate.BlockingDaoHibernate.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<String> getBlockingKeyValues(final List<String> fields) {
    return (List<String>) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            List<String> values = new java.util.ArrayList<String>();
            ProjectionList projectionList = Projections.projectionList();
            for (String field : fields) {
                projectionList.add(Projections.property(field), field);
            }/*from www  .j  a va  2s.  co  m*/
            org.hibernate.Criteria criteria = session.createCriteria(Person.class, "person_")
                    .setProjection(Projections.distinct(projectionList));
            for (String field : fields) {
                criteria.add(Expression.isNotNull("person_." + field));
            }
            log.debug("Blocking criteria query: " + criteria.toString());
            @SuppressWarnings("rawtypes")
            List list = (List<Object[]>) criteria.list();
            if (list.size() == 0) {
                return values;
            }
            // Query returns either a list of Object or a list of arrays of objects depending on
            // whether one or more than one blocking fields are used.
            if (!(list.get(0) instanceof Object[])) {
                List<Object> theValues = (List<Object>) list;
                for (Object value : theValues) {
                    values.add(value.toString());
                }
                return values;
            }
            List<Object[]> objectArrayValues = (List<Object[]>) list;
            for (Object[] row : objectArrayValues) {
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < row.length; i++) {
                    sb.append(row[i].toString().trim());
                }
                values.add(sb.toString());
            }
            return values;
        }
    });
}

From source file:org.openhie.openempi.dao.hibernate.BlockingDaoHibernate.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<List<NameValuePair>> getDistinctValues(final List<String> fields) {
    return (List<List<NameValuePair>>) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            ProjectionList projectionList = Projections.projectionList();
            for (String field : fields) {
                projectionList.add(Projections.property(field), field);
            }//  ww  w .  j  av a  2s .  c  o m
            org.hibernate.Criteria criteria = session.createCriteria(Person.class, "person_")
                    .setProjection(Projections.distinct(projectionList));
            for (String field : fields) {
                criteria.add(Expression.isNotNull("person_." + field));
            }
            log.debug("Blocking criteria query: " + criteria.toString());
            @SuppressWarnings("rawtypes")
            List list = (List<Object[]>) criteria.list();
            List<List<NameValuePair>> pairs = new ArrayList<List<NameValuePair>>(list.size());
            if (list.size() == 0) {
                return pairs;
            }
            // Query returns either a list of Object or a list of arrays of objects depending on
            // whether one or more than one blocking fields are used.
            if (!(list.get(0) instanceof Object[])) {
                List<Object> theValues = (List<Object>) list;
                for (Object value : theValues) {
                    List<NameValuePair> distinctRowValues = new ArrayList<NameValuePair>(1);
                    distinctRowValues.add(new NameValuePair(fields.get(0), value));
                    pairs.add(distinctRowValues);
                }
                return pairs;
            }
            List<Object[]> objectArrayValues = (List<Object[]>) list;
            for (Object[] row : objectArrayValues) {
                List<NameValuePair> distinctRowValues = new ArrayList<NameValuePair>(row.length);
                for (int i = 0; i < row.length; i++) {
                    NameValuePair pair = new NameValuePair(fields.get(i), row[i]);
                    distinctRowValues.add(pair);
                }
                pairs.add(distinctRowValues);
            }
            return pairs;
        }
    });
}

From source file:org.openhie.openempi.dao.hibernate.PersonLinkDaoHibernate.java

License:Open Source License

@SuppressWarnings("unchecked")
public Integer getClusterId(final Set<Long> recordIds, final Integer sourceId) {
    final Set<Integer> ids = convertRecordIdsToInts(recordIds);
    return (Integer) getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            List<Integer> clusterIds = session.createCriteria(PersonLink.class)
                    .setProjection(Projections.distinct(Projections.property("clusterId")))
                    .add(Expression.and(
                            Expression.or(Expression.in("personLeft.personId", ids),
                                    Expression.in("personRight.personId", ids)),
                            Expression.eq("linkSource.linkSourceId", sourceId)))
                    .createAlias("personLeft", "pl").createAlias("personRight", "pr")
                    .add(Restrictions.isNull("pr.dateVoided")).add(Restrictions.isNull("pl.dateVoided"))
                    .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
            if (clusterIds.size() > 1) {
                log.error(/* w w  w  .  jav a2  s  . c  om*/
                        "Encountered an unexpected condition; we have a set of nodes that are not all sharing the same cluster ID: "
                                + recordIds);
                throw new RuntimeException(
                        "Unstable condition in linking module; found a set of nodes that don't share the same cluster ID");
            }
            if (clusterIds.size() == 0) {
                return null;
            }
            return clusterIds.get(0);
        }
    });
}

From source file:org.openmrs.api.db.hibernate.HibernateConceptDAO.java

License:Mozilla Public License

/**
 * @see org.openmrs.api.db.ConceptDAO#getProposedConcepts(java.lang.String)
 */// ww w .java 2s . c om
@SuppressWarnings("unchecked")
public List<Concept> getProposedConcepts(String text) throws DAOException {
    Criteria crit = sessionFactory.getCurrentSession().createCriteria(ConceptProposal.class);
    crit.add(Restrictions.ne("state", OpenmrsConstants.CONCEPT_PROPOSAL_UNMAPPED));
    crit.add(Restrictions.eq("originalText", text));
    crit.add(Restrictions.isNotNull("mappedConcept"));
    crit.setProjection(Projections.distinct(Projections.property("mappedConcept")));

    return crit.list();
}

From source file:org.openmrs.module.emr.reporting.cohort.definition.evaluator.DiagnosisCohortDefinitionEvaluator.java

License:Open Source License

@Override
public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context)
        throws EvaluationException {
    DiagnosisMetadata dmd = emrApiProperties.getDiagnosisMetadata();

    DiagnosisCohortDefinition cd = (DiagnosisCohortDefinition) cohortDefinition;

    if (cd.isIncludeAllCodedDiagnoses() && cd.getCodedDiagnoses() != null) {
        throw new IllegalArgumentException(
                "Cannot specify both includeAllCodedDiagnoses, and specific coded diagnoses");
    }/*from  www.  j  a  v a 2 s  .co  m*/

    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Obs.class, "obsgroup");
    crit.setProjection(Projections.distinct(Projections.property("person.id")));

    crit.add(Restrictions.eq("voided", false));
    crit.createCriteria("person").add(Restrictions.eq("voided", false));

    // we're looking for an obs group whose grouping concept is VISIT DIAGNOSES (or the equivalent)
    crit.add(Restrictions.eq("concept", dmd.getDiagnosisSetConcept()));

    if (cd.getOnOrAfter() != null) {
        crit.add(Restrictions.ge("obsDatetime", cd.getOnOrAfter()));
    }
    if (cd.getOnOrBefore() != null) {
        crit.add(Restrictions.le("obsDatetime", DateUtil.getEndOfDayIfTimeExcluded(cd.getOnOrBefore())));
    }

    if (cd.getDiagnosisOrder() != null) {
        DetachedCriteria orderClause = DetachedCriteria.forClass(Obs.class, "orderObs");
        orderClause.add(Restrictions.eq("voided", false));
        orderClause.add(Restrictions.eq("concept", dmd.getDiagnosisOrderConcept()));
        orderClause.add(Restrictions.eq("valueCoded", dmd.getConceptFor(cd.getDiagnosisOrder())));
        orderClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
        orderClause.setProjection(Projections.property("id"));
        crit.add(Subqueries.exists(orderClause));
    }

    if (cd.getCertainty() != null) {
        DetachedCriteria certaintyClause = DetachedCriteria.forClass(Obs.class, "certaintyObs");
        certaintyClause.add(Restrictions.eq("voided", false));
        certaintyClause.add(Restrictions.eq("concept", dmd.getDiagnosisCertaintyConcept()));
        certaintyClause.add(Restrictions.eq("valueCoded", dmd.getConceptFor(cd.getCertainty())));
        certaintyClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
        certaintyClause.setProjection(Projections.property("id"));
        crit.add(Subqueries.exists(certaintyClause));
    }

    if (cd.isIncludeAllCodedDiagnoses()) {
        // Note: since every diagnosis is either coded or non-coded if they want to include all coded *and* non-coded
        // diagnoses, we can just ignore both clauses
        if (!cd.isIncludeAllNonCodedDiagnoses()) {
            DetachedCriteria anyCodedClause = DetachedCriteria.forClass(Obs.class, "codedDiagnosisObs");
            anyCodedClause.add(Restrictions.eq("voided", false));
            anyCodedClause.add(Restrictions.eq("concept", dmd.getCodedDiagnosisConcept()));
            anyCodedClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
            anyCodedClause.setProjection(Projections.property("id"));
            crit.add(Subqueries.exists(anyCodedClause));
        }
    } else if (cd.getCodedDiagnoses() != null || cd.getExcludeCodedDiagnoses() != null) {
        if (cd.isIncludeAllNonCodedDiagnoses()) {
            throw new IllegalArgumentException(
                    "Not Yet Implemented: handling both all-non-coded and specific coded diagnoses together");
        }
        if (!cd.isIncludeAllNonCodedDiagnoses()) {
            DetachedCriteria specificCodedClause = DetachedCriteria.forClass(Obs.class, "codedDiagnosisObs");
            specificCodedClause.add(Restrictions.eq("voided", false));
            specificCodedClause.add(Restrictions.eq("concept", dmd.getCodedDiagnosisConcept()));
            if (cd.getCodedDiagnoses() != null) {
                specificCodedClause.add(Restrictions.in("valueCoded", cd.getCodedDiagnoses()));
            }
            if (cd.getExcludeCodedDiagnoses() != null) {
                specificCodedClause
                        .add(Restrictions.not(Restrictions.in("valueCoded", cd.getExcludeCodedDiagnoses())));
            }
            specificCodedClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
            specificCodedClause.setProjection(Projections.property("id"));
            crit.add(Subqueries.exists(specificCodedClause));
        }
    } else if (cd.isIncludeAllNonCodedDiagnoses()) {
        DetachedCriteria anyNonCodedClause = DetachedCriteria.forClass(Obs.class, "nonCodedDiagnosisObs");
        anyNonCodedClause.add(Restrictions.eq("voided", false));
        anyNonCodedClause.add(Restrictions.eq("concept", dmd.getNonCodedDiagnosisConcept()));
        anyNonCodedClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
        anyNonCodedClause.setProjection(Projections.property("id"));
        crit.add(Subqueries.exists(anyNonCodedClause));
    }

    Cohort c = new Cohort();
    for (Integer i : (List<Integer>) crit.list()) {
        c.addMember(i);
    }
    return new EvaluatedCohort(c, cohortDefinition, context);
}

From source file:org.openmrs.module.emr.reporting.cohort.definition.evaluator.VisitCohortDefinitionEvaluator.java

License:Open Source License

@Override
public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context)
        throws EvaluationException {
    VisitCohortDefinition cd = (VisitCohortDefinition) cohortDefinition;

    // TODO need to exclude voided patients (just in case there are non-voided visits for voided patients)

    if (cd.getTimeQualifier() != TimeQualifier.ANY) {
        throw new IllegalArgumentException("Currently only timeQualifier=ANY is implemented");
    }/* w  w w  .j a  v  a  2s  . c  o  m*/

    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Visit.class);
    crit.add(Restrictions.eq("voided", false));
    if (cd.getStartedOnOrAfter() != null) {
        crit.add(Restrictions.ge("startDatetime", cd.getStartedOnOrAfter()));
    }
    if (cd.getStartedOnOrBefore() != null) {
        crit.add(Restrictions.le("startDatetime",
                DateUtil.getEndOfDayIfTimeExcluded(cd.getStartedOnOrBefore())));
    }
    if (cd.getStoppedOnOrAfter() != null) {
        crit.add(Restrictions.ge("stopDatetime", cd.getStoppedOnOrAfter()));
    }
    if (cd.getStoppedOnOrBefore() != null) {
        crit.add(
                Restrictions.le("stopDatetime", DateUtil.getEndOfDayIfTimeExcluded(cd.getStoppedOnOrBefore())));
    }
    if (cd.getVisitTypeList() != null) {
        crit.add(Restrictions.in("visitType", cd.getVisitTypeList()));
    }
    if (cd.getLocationList() != null) {
        crit.add(Restrictions.in("location", cd.getLocationList()));
    }
    if (cd.getIndicationList() != null) {
        crit.add(Restrictions.in("indication", cd.getIndicationList()));
    }
    if (cd.getCreatedBy() != null) {
        crit.add(Restrictions.eq("creator", cd.getCreatedBy()));
    }
    if (cd.getCreatedOnOrAfter() != null) {
        crit.add(Restrictions.ge("dateCreated", cd.getCreatedOnOrAfter()));
    }
    if (cd.getCreatedOnOrBefore() != null) {
        crit.add(Restrictions.le("dateCreated", DateUtil.getEndOfDayIfTimeExcluded(cd.getCreatedOnOrBefore())));
    }
    if (cd.isActive() != null) {
        if (cd.isActive()) {
            crit.add(Restrictions.isNull("stopDatetime"));
        }
    }
    crit.setProjection(Projections.distinct(Projections.property("patient.id")));

    Cohort c = new Cohort();
    for (Integer i : (List<Integer>) crit.list()) {
        c.addMember(i);
    }

    if (cd.getReturnInverse()) {
        Cohort baseCohort = context.getBaseCohort();
        if (baseCohort == null) {
            baseCohort = Context.getPatientSetService().getAllPatients();
        }
        c = Cohort.subtract(baseCohort, c);
    }

    return new EvaluatedCohort(c, cohortDefinition, context);
}

From source file:org.openmrs.module.metadatasharing.api.db.hibernate.HibernateCompatibility1_9.java

License:Open Source License

@Override
public List<Concept> getConcepts(boolean includeRetired, String filter, Integer firstResult,
        Integer maxResults) {// w w w . j  a v  a2 s.c  om

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(ConceptWord.class, "conceptWord");

    filterConceptWords(criteria, includeRetired, filter);

    criteria.addOrder(Order.asc("concept"));
    criteria.setProjection(Projections.distinct(Projections.property("concept")));

    if (firstResult != null) {
        criteria.setFirstResult(firstResult);
    }

    if (maxResults != null) {
        criteria.setMaxResults(maxResults);
    }

    return criteria.list();
}

From source file:org.openmrs.module.metadatasharing.api.db.hibernate.HibernateMetadataDAO.java

License:Open Source License

/**
 * @see org.openmrs.module.metadatasharing.api.db.MetadataDAO#getConcepts(boolean,
 *      java.lang.String, java.lang.Integer, java.lang.Integer)
 *///from w  w w.j ava 2 s .c o  m
@Override
public List<Concept> getConcepts(boolean includeRetired, String filter, Integer firstResult,
        Integer maxResults) {
    List<Concept> result = new ArrayList<Concept>();
    if (!StringUtils.isEmpty(filter)) {
        Concept concept = Context.getConceptService().getConceptByUuid(filter);
        if (concept != null) {
            return Arrays.asList(concept);
        }
        concept = filterById(filter);
        if (concept != null) {
            // if the first page with concepts was requested, we just add found concept 
            if (firstResult == 0) {
                result.add(concept);
                maxResults -= 1;
            } else {
                // otherwise, we need to shift down the lower bound of concepts
                firstResult -= 1;
            }
        }
    }

    Criteria criteria = null;
    if (StringUtils.isEmpty(filter)) {
        criteria = sessionFactory.getCurrentSession().createCriteria(Concept.class);

        if (!includeRetired) {
            criteria.add(Restrictions.eq("retired", includeRetired));
        }

        criteria.addOrder(Order.asc("conceptId"));
    } else {
        criteria = sessionFactory.getCurrentSession().createCriteria(ConceptWord.class, "conceptWord");

        filterConceptWords(criteria, includeRetired, filter);

        criteria.addOrder(Order.asc("concept"));
        criteria.setProjection(Projections.distinct(Projections.property("concept")));
    }

    if (firstResult != null) {
        criteria.setFirstResult(firstResult);
    }

    if (maxResults != null) {
        criteria.setMaxResults(maxResults);
    }

    @SuppressWarnings("unchecked")
    List<Concept> concepts = criteria.list();

    if (concepts != null && !concepts.isEmpty()) {
        result.addAll(concepts);
    }

    return result;
}

From source file:org.openmrs.module.mirebalaisreports.cohort.definition.evaluator.VisitCohortDefinitionEvaluator.java

License:Open Source License

@Override
public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context)
        throws EvaluationException {
    VisitCohortDefinition cd = (VisitCohortDefinition) cohortDefinition;

    // TODO need to exclude voided patients (just in case there are non-voided visits for voided patients)

    if (cd.getTimeQualifier() != TimeQualifier.ANY) {
        throw new IllegalArgumentException("Currently only timeQualifier=ANY is implemented");
    }//from  w ww  . j  ava2  s.c  o  m

    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Visit.class);
    crit.add(Restrictions.eq("voided", false));
    if (cd.getStartedOnOrAfter() != null) {
        crit.add(Restrictions.ge("startDatetime", cd.getStartedOnOrAfter()));
    }
    if (cd.getStartedOnOrBefore() != null) {
        crit.add(Restrictions.le("startDatetime",
                DateUtil.getEndOfDayIfTimeExcluded(cd.getStartedOnOrBefore())));
    }
    if (cd.getStoppedOnOrAfter() != null) {
        crit.add(Restrictions.ge("stopDatetime", cd.getStoppedOnOrAfter()));
    }
    if (cd.getStoppedOnOrBefore() != null) {
        crit.add(
                Restrictions.le("stopDatetime", DateUtil.getEndOfDayIfTimeExcluded(cd.getStoppedOnOrBefore())));
    }
    if (cd.getActiveOnOrAfter() != null) {
        crit.add(Restrictions.or(Restrictions.ge("stopDatetime", cd.getActiveOnOrAfter()),
                Restrictions.isNull("stopDatetime")));
    }
    if (cd.getActiveOnOrBefore() != null) {
        crit.add(
                Restrictions.le("startDatetime", DateUtil.getEndOfDayIfTimeExcluded(cd.getActiveOnOrBefore())));
    }
    if (cd.getVisitTypeList() != null) {
        crit.add(Restrictions.in("visitType", cd.getVisitTypeList()));
    }
    if (cd.getLocationList() != null) {
        crit.add(Restrictions.in("location", cd.getLocationList()));
    }
    if (cd.getIndicationList() != null) {
        crit.add(Restrictions.in("indication", cd.getIndicationList()));
    }
    if (cd.getCreatedBy() != null) {
        crit.add(Restrictions.eq("creator", cd.getCreatedBy()));
    }
    if (cd.getCreatedOnOrAfter() != null) {
        crit.add(Restrictions.ge("dateCreated", cd.getCreatedOnOrAfter()));
    }
    if (cd.getCreatedOnOrBefore() != null) {
        crit.add(Restrictions.le("dateCreated", DateUtil.getEndOfDayIfTimeExcluded(cd.getCreatedOnOrBefore())));
    }
    if (cd.isActive() != null) {
        if (cd.isActive()) {
            crit.add(Restrictions.isNull("stopDatetime"));
        }
    }
    crit.setProjection(Projections.distinct(Projections.property("patient.id")));

    Cohort c = new Cohort();
    for (Integer i : (List<Integer>) crit.list()) {
        c.addMember(i);
    }

    if (cd.getReturnInverse()) {
        Cohort baseCohort = context.getBaseCohort();
        if (baseCohort == null) {
            baseCohort = Context.getPatientSetService().getAllPatients();
        }
        c = Cohort.subtract(baseCohort, c);
    }

    return new EvaluatedCohort(c, cohortDefinition, context);
}