Example usage for org.hibernate Query setCacheMode

List of usage examples for org.hibernate Query setCacheMode

Introduction

In this page you can find the example usage for org.hibernate Query setCacheMode.

Prototype

Query<R> setCacheMode(CacheMode cacheMode);

Source Link

Document

(Re)set the current CacheMode in effect for this query.

Usage

From source file:org.openmrs.module.reporting.cohort.query.db.hibernate.HibernateCohortQueryDAO.java

License:Open Source License

/**
 * Encapsulates the common logic between getPatientsHavingRangedObs and getPatientsHavingDiscreteObs
 * /* www.j  a va2 s  .  co m*/
 * The arguments passed in fall into two types:
 * <ol>
 *     <li>arguments that limit which obs we will look at</li>
 *     <ul>
 *         <li>timeModifier</li>
 *         <li>question</li>
 *         <li>groupingConcept</li>
 *         <li>onOrAfter</li>
 *         <li>onOrBefore</li>
 *         <li>locationList</li>
 *         <li>encounterTypeList</li>
 *         <li></li>
 *         <li></li>
 *     </ul>
 *     <li>arguments that the obs values must match after being limited by the above arguments</li>
 *     <ul>
 *         <li>operator1</li>
 *         <li>value1</li>
 *         <li>operator2</li>
 *         <li>value2</li>
 *         <li>setOperator</li>
 *         <li>valueList</li>
 *     </ul>
 * </ol> 
 * 
 * @param timeModifier
 * @param question
 * @param groupingConcept
 * @param onOrAfter
 * @param onOrBefore
 * @param locationList
 * @param encounterTypeList
 * @param operator1
 * @param value1
 * @param operator2
 * @param value2
 * @param setOperator
 * @param valueList
 * @return
 */
private Cohort getPatientsHavingObs(TimeModifier timeModifier, Concept question, Concept groupingConcept,
        Date onOrAfter, Date onOrBefore, List<Location> locationList, List<EncounterType> encounterTypeList,
        RangeComparator operator1, Object value1, RangeComparator operator2, Object value2,
        SetComparator setOperator, List<? extends Object> valueList) {

    Integer questionConceptId = question == null ? null : question.getId();
    Integer groupingConceptId = groupingConcept == null ? null : groupingConcept.getId();
    if (groupingConceptId != null)
        throw new RuntimeException("grouping concept not yet implemented");

    List<Integer> locationIds = SqlUtils.openmrsObjectIdListHelper(locationList);
    List<Integer> encounterTypeIds = SqlUtils.openmrsObjectIdListHelper(encounterTypeList);

    boolean joinOnEncounter = encounterTypeIds != null;
    String dateAndLocationSql = ""; // TODO rename to include encounterType
    String dateAndLocationSqlForSubquery = "";
    if (onOrAfter != null) {
        dateAndLocationSql += " and o.obs_datetime >= :onOrAfter ";
        dateAndLocationSqlForSubquery += " and obs.obs_datetime >= :onOrAfter ";
    }
    if (onOrBefore != null) {
        dateAndLocationSql += " and o.obs_datetime <= :onOrBefore ";
        dateAndLocationSqlForSubquery += " and obs.obs_datetime <= :onOrBefore ";
    }
    if (locationIds != null) {
        dateAndLocationSql += " and o.location_id in (:locationIds) ";
        dateAndLocationSqlForSubquery += " and obs.location_id in (:locationIds) ";
    }
    if (encounterTypeIds != null) {
        dateAndLocationSql += " and e.encounter_type in (:encounterTypeIds) ";
        dateAndLocationSqlForSubquery += " and encounter.encounter_type in (:encounterTypeIds) ";
    }

    boolean doSqlAggregation = timeModifier == TimeModifier.MIN || timeModifier == TimeModifier.MAX
            || timeModifier == TimeModifier.AVG;
    boolean doInvert = timeModifier == TimeModifier.NO;

    String valueSql = null;
    List<String> valueClauses = new ArrayList<String>();
    List<Object> valueListForQuery = null;

    if (value1 != null || value2 != null) {
        valueSql = (value1 != null && value1 instanceof Number) ? " o.value_numeric " : " o.value_datetime ";
    } else if (valueList != null && valueList.size() > 0) {
        valueListForQuery = new ArrayList<Object>();
        if (valueList.get(0) instanceof String) {
            valueSql = " o.value_text ";
            for (Object o : valueList)
                valueListForQuery.add(o);
        } else {
            valueSql = " o.value_coded ";
            for (Object o : valueList) {
                if (o instanceof Concept)
                    valueListForQuery.add(((Concept) o).getConceptId());
                else if (o instanceof Number)
                    valueListForQuery.add(((Number) o).intValue());
                else
                    throw new IllegalArgumentException(
                            "Don't know how to handle " + o.getClass() + " in valueList");
            }
        }
    }

    if (doSqlAggregation) {
        valueSql = " " + timeModifier.toString() + "(" + valueSql + ") ";
    }

    if (value1 != null || value2 != null) {
        if (value1 != null) {
            valueClauses.add(valueSql + operator1.getSqlRepresentation() + " :value1 ");
        }
        if (value2 != null) {
            valueClauses.add(valueSql + operator2.getSqlRepresentation() + " :value2 ");
        }
    } else if (valueList != null && valueList.size() > 0) {
        valueClauses.add(valueSql + setOperator.getSqlRepresentation() + " (:valueList) ");
    }

    StringBuilder sql = new StringBuilder();
    sql.append(" select o.person_id from obs o ");
    sql.append(" inner join patient p on o.person_id = p.patient_id ");
    if (joinOnEncounter) {
        sql.append(" inner join encounter e on o.encounter_id = e.encounter_id ");
    }

    if (timeModifier == TimeModifier.ANY || timeModifier == TimeModifier.NO) {
        sql.append(" where o.voided = false and p.voided = false ");
        if (questionConceptId != null) {
            sql.append(" and concept_id = :questionConceptId ");
        }
        sql.append(dateAndLocationSql);
    } else if (timeModifier == TimeModifier.FIRST || timeModifier == TimeModifier.LAST) {
        boolean isFirst = timeModifier == PatientSetService.TimeModifier.FIRST;
        sql.append(" inner join ( ");
        sql.append("    select person_id, " + (isFirst ? "MIN" : "MAX") + "(obs_datetime) as odt ");
        sql.append("    from obs ");
        if (joinOnEncounter) {
            sql.append(" inner join encounter on obs.encounter_id = encounter.encounter_id ");
        }
        sql.append("             where obs.voided = false and obs.concept_id = :questionConceptId "
                + dateAndLocationSqlForSubquery + " group by person_id ");
        sql.append(" ) subq on o.person_id = subq.person_id and o.obs_datetime = subq.odt ");
        sql.append(" where o.voided = false and p.voided = false and o.concept_id = :questionConceptId ");
        sql.append(dateAndLocationSql);
    } else if (doSqlAggregation) {
        sql.append(" where o.voided = false and p.voided = false and concept_id = :questionConceptId "
                + dateAndLocationSql);
        sql.append(" group by o.person_id ");
    } else {
        throw new IllegalArgumentException("TimeModifier '" + timeModifier + "' not recognized");
    }

    if (valueClauses.size() > 0) {
        sql.append(doSqlAggregation ? " having " : " and ");
        for (Iterator<String> i = valueClauses.iterator(); i.hasNext();) {
            sql.append(i.next());
            if (i.hasNext())
                sql.append(" and ");
        }
    }

    log.debug("sql: " + sql);
    Query query = sessionFactory.getCurrentSession().createSQLQuery(sql.toString());
    query.setCacheMode(CacheMode.IGNORE);

    if (questionConceptId != null)
        query.setInteger("questionConceptId", questionConceptId);
    if (value1 != null) {
        if (value1 instanceof Number)
            query.setDouble("value1", ((Number) value1).doubleValue());
        else
            query.setDate("value1", (Date) value1);
    }
    if (value2 != null) {
        if (value2 instanceof Number)
            query.setDouble("value2", ((Number) value2).doubleValue());
        else
            query.setDate("value2", (Date) value2);
    }
    if (valueListForQuery != null) {
        query.setParameterList("valueList", valueListForQuery);
    }
    if (onOrAfter != null)
        query.setTimestamp("onOrAfter", onOrAfter);
    if (onOrBefore != null)
        query.setTimestamp("onOrBefore", DateUtil.getEndOfDayIfTimeExcluded(onOrBefore));
    if (locationIds != null)
        query.setParameterList("locationIds", locationIds);
    if (encounterTypeIds != null)
        query.setParameterList("encounterTypeIds", encounterTypeIds);

    Cohort ret;
    if (doInvert) {
        ret = Cohorts.allPatients(null);
        ret.getMemberIds().removeAll(query.list());
    } else {
        ret = new Cohort(query.list());
    }
    return ret;
}

From source file:org.openmrs.module.reporting.cohort.query.db.hibernate.HibernateCohortQueryDAO.java

License:Open Source License

/**
 * @see org.openmrs.module.reporting.cohort.query.db.CohortQueryDAO#getPatientsHavingBirthAndDeath(java.util.Date, java.util.Date, java.util.Date, java.util.Date)
 *///  w  ww  .  j  a  v  a 2  s .c om
public Cohort getPatientsHavingBirthAndDeath(Date bornOnOrAfter, Date bornOnOrBefore, Date diedOnOrAfter,
        Date diedOnOrBefore) {
    StringBuilder sql = new StringBuilder();
    sql.append(" select patient_id ");
    sql.append(" from patient pat ");
    sql.append(" inner join person per on pat.patient_id = per.person_id ");
    sql.append(" where pat.voided = false and per.voided = false ");
    if (bornOnOrAfter != null)
        sql.append(" and birthdate >= :bornOnOrAfter ");
    if (bornOnOrBefore != null)
        sql.append(" and birthdate <= :bornOnOrBefore ");
    if (diedOnOrAfter != null)
        sql.append(" and death_date >= :diedOnOrAfter ");
    if (diedOnOrBefore != null)
        sql.append(" and death_date <= :diedOnOrBefore ");

    Query q = sessionFactory.getCurrentSession().createSQLQuery(sql.toString());
    q.setCacheMode(CacheMode.IGNORE);

    if (bornOnOrAfter != null)
        q.setTimestamp("bornOnOrAfter", bornOnOrAfter);
    if (bornOnOrBefore != null)
        q.setTimestamp("bornOnOrBefore", DateUtil.getEndOfDayIfTimeExcluded(bornOnOrBefore));
    if (diedOnOrAfter != null)
        q.setTimestamp("diedOnOrAfter", diedOnOrAfter);
    if (diedOnOrBefore != null)
        q.setTimestamp("diedOnOrBefore", DateUtil.getEndOfDayIfTimeExcluded(diedOnOrBefore));

    return new Cohort(q.list());
}

From source file:org.openmrs.module.reportingcompatibility.service.db.HibernateReportingCompatibilityDAO.java

License:Open Source License

/**
 * TODO: Don't return voided patients Returns the set of patients that were ever in enrolled in
 * a given program. If fromDate != null, then only those patients who were in the program at any
 * time after that date if toDate != null, then only those patients who were in the program at
 * any time before that date/*from   w  ww  .  j  ava  2  s. c  o m*/
 */
public Cohort getPatientsInProgram(Integer programId, Date fromDate, Date toDate) {
    String sql = "select pp.patient_id from patient_program pp ";
    sql += " inner join patient p on pp.patient_id = p.patient_id and p.voided = false ";
    sql += " where pp.voided = false and pp.program_id = :programId ";
    if (fromDate != null)
        sql += " and (date_completed is null or date_completed >= :fromDate) ";
    if (toDate != null)
        sql += " and (date_enrolled is null or date_enrolled <= :toDate) ";
    log.debug("sql: " + sql);

    Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);
    query.setCacheMode(CacheMode.IGNORE);

    query.setInteger("programId", programId);
    if (fromDate != null)
        query.setDate("fromDate", fromDate);
    if (toDate != null)
        query.setDate("toDate", toDate);

    return new Cohort(query.list());
}

From source file:org.openmrs.module.reportingcompatibility.service.db.HibernateReportingCompatibilityDAO.java

License:Open Source License

public Cohort getPatientsHavingObs(Integer conceptId, PatientSetService.TimeModifier timeModifier,
        PatientSetService.Modifier modifier, Object value, Date fromDate, Date toDate) {
    if (conceptId == null && value == null)
        throw new IllegalArgumentException("Can't have conceptId == null and value == null");
    if (conceptId == null && (timeModifier != TimeModifier.ANY && timeModifier != TimeModifier.NO))
        throw new IllegalArgumentException("If conceptId == null, timeModifier must be ANY or NO");
    if (conceptId == null && modifier != Modifier.EQUAL) {
        throw new IllegalArgumentException("If conceptId == null, modifier must be EQUAL");
    }//from  w  w  w.  j a  v a2  s  .c o  m
    Concept concept = null;
    if (conceptId != null)
        concept = Context.getConceptService().getConcept(conceptId);
    Number numericValue = null;
    String stringValue = null;
    Concept codedValue = null;
    Date dateValue = null;
    Boolean booleanValue = null;
    String valueSql = null;
    if (value != null) {
        if (concept == null) {
            if (value instanceof Concept)
                codedValue = (Concept) value;
            else
                codedValue = Context.getConceptService().getConceptByName(value.toString());
            valueSql = "o.value_coded";
        } else if (concept.getDatatype().isNumeric()) {
            if (value instanceof Number)
                numericValue = (Number) value;
            else
                numericValue = new Double(value.toString());
            valueSql = "o.value_numeric";
        } else if (concept.getDatatype().isText()) {
            stringValue = value.toString();
            valueSql = "o.value_text";
            if (modifier == null)
                modifier = Modifier.EQUAL;
        } else if (concept.getDatatype().isCoded()) {
            if (value instanceof Concept)
                codedValue = (Concept) value;
            else
                codedValue = Context.getConceptService().getConceptByName(value.toString());
            valueSql = "o.value_coded";
        } else if (concept.getDatatype().isDate()) {
            if (value instanceof Date) {
                dateValue = (Date) value;
            } else {
                try {
                    dateValue = Context.getDateFormat().parse(value.toString());
                } catch (ParseException ex) {
                    throw new IllegalArgumentException("Cannot interpret " + dateValue
                            + " as a date in the format " + Context.getDateFormat());
                }
            }
            valueSql = "o.value_datetime";
        } else if (concept.getDatatype().isBoolean()) {
            if (value instanceof Boolean)
                booleanValue = (Boolean) value;
            else
                booleanValue = Boolean.valueOf(value.toString());
            valueSql = "o.value_numeric";
        }
    }

    StringBuilder sb = new StringBuilder();
    boolean useValue = value != null;
    boolean doSqlAggregation = timeModifier == TimeModifier.MIN || timeModifier == TimeModifier.MAX
            || timeModifier == TimeModifier.AVG;
    boolean doInvert = false;

    String dateSql = "";
    String dateSqlForSubquery = "";
    if (fromDate != null) {
        dateSql += " and o.obs_datetime >= :fromDate ";
        dateSqlForSubquery += " and obs_datetime >= :fromDate ";
    }
    if (toDate != null) {
        dateSql += " and o.obs_datetime <= :toDate ";
        dateSqlForSubquery += " and obs_datetime <= :toDate ";
    }

    if (timeModifier == TimeModifier.ANY || timeModifier == TimeModifier.NO) {
        if (timeModifier == TimeModifier.NO)
            doInvert = true;
        sb.append("select o.person_id from obs o "
                + "inner join patient p on o.person_id = p.patient_id and p.voided = false "
                + "where o.voided = false ");
        if (conceptId != null)
            sb.append("and concept_id = :concept_id ");
        sb.append(dateSql);

    } else if (timeModifier == TimeModifier.FIRST || timeModifier == TimeModifier.LAST) {
        boolean isFirst = timeModifier == PatientSetService.TimeModifier.FIRST;
        sb.append("select o.person_id " + "from obs o inner join (" + "    select person_id, "
                + (isFirst ? "min" : "max") + "(obs_datetime) as obs_datetime" + "    from obs"
                + "    where voided = false and concept_id = :concept_id " + dateSqlForSubquery
                + "    group by person_id"
                + ") subq on o.person_id = subq.person_id and o.obs_datetime = subq.obs_datetime "
                + " inner join patient p on o.person_id = p.patient_id and p.voided = false "
                + "where o.voided = false and o.concept_id = :concept_id ");

    } else if (doSqlAggregation) {
        String sqlAggregator = timeModifier.toString();
        valueSql = sqlAggregator + "(" + valueSql + ")";
        sb.append("select o.person_id " + "from obs o "
                + "inner join patient p on o.person_id = p.patient_id and p.voided = false "
                + "where o.voided = false and concept_id = :concept_id " + dateSql + "group by o.person_id ");

    } else {
        throw new IllegalArgumentException("TimeModifier '" + timeModifier + "' not recognized");
    }

    if (useValue) {
        sb.append(doSqlAggregation ? " having " : " and ");
        sb.append(valueSql + " ");
        sb.append(modifier.getSqlRepresentation() + " :value");
    }
    if (!doSqlAggregation)
        sb.append(" group by o.person_id ");

    log.debug("query: " + sb);
    Query query = sessionFactory.getCurrentSession().createSQLQuery(sb.toString());
    query.setCacheMode(CacheMode.IGNORE);

    if (conceptId != null)
        query.setInteger("concept_id", conceptId);
    if (useValue) {
        if (numericValue != null)
            query.setDouble("value", numericValue.doubleValue());
        else if (codedValue != null)
            query.setInteger("value", codedValue.getConceptId());
        else if (stringValue != null)
            query.setString("value", stringValue);
        else if (dateValue != null)
            query.setDate("value", dateValue);
        else if (booleanValue != null)
            query.setDouble("value", booleanValue ? 1.0 : 0.0);
        else
            throw new IllegalArgumentException(
                    "useValue is true, but numeric, coded, string, boolean, and date values are all null");
    }
    if (fromDate != null)
        query.setDate("fromDate", fromDate);
    if (toDate != null)
        query.setDate("toDate", toDate);

    Cohort ret;
    if (doInvert) {
        ret = getAllPatients();
        ret.getMemberIds().removeAll(query.list());
    } else {
        ret = new Cohort(query.list());
    }

    return ret;
}

From source file:org.openmrs.module.reportingcompatibility.service.db.HibernateReportingCompatibilityDAO.java

License:Open Source License

/**
 * TODO: don't return voided patients Gets all patients with an obs's value_date column value
 * within <code>startTime</code> and <code>endTime</code>
 * /*from  ww w.  j  a  v  a2s.com*/
 * @param conceptId
 * @param startTime
 * @param endTime
 * @return PatientSet
 */
public Cohort getPatientsHavingDateObs(Integer conceptId, Date startTime, Date endTime) {
    StringBuffer sb = new StringBuffer();
    sb.append("select o.person_id from obs o " + "where concept_id = :concept_id ");
    sb.append(" and o.value_datetime between :startValue and :endValue");
    sb.append(" and o.voided = 0");

    Query query = sessionFactory.getCurrentSession().createSQLQuery(sb.toString());
    query.setCacheMode(CacheMode.IGNORE);

    query.setInteger("concept_id", conceptId);
    query.setDate("startValue", startTime);
    query.setDate("endValue", endTime);

    return new Cohort(query.list());
}

From source file:org.openmrs.module.reportingcompatibility.service.db.HibernateReportingCompatibilityDAO.java

License:Open Source License

public Cohort getPatientsHavingNumericObs(Integer conceptId, PatientSetService.TimeModifier timeModifier,
        PatientSetService.Modifier modifier, Number value, Date fromDate, Date toDate) {

    Concept concept = Context.getConceptService().getConcept(conceptId);
    if (!concept.isNumeric()) {
        // throw new IllegalArgumentException(concept + " is not numeric");
    }/*from  w w w  .ja v  a 2 s  .  com*/

    StringBuffer sb = new StringBuffer();
    boolean useValue = modifier != null && value != null;
    boolean doSqlAggregation = timeModifier == TimeModifier.MIN || timeModifier == TimeModifier.MAX
            || timeModifier == TimeModifier.AVG;
    String valueSql = "o.value_numeric";
    boolean doInvert = false;

    String dateSql = "";
    if (fromDate != null)
        dateSql += " and o.obs_datetime >= :fromDate ";
    if (toDate != null)
        dateSql += " and o.obs_datetime <= :toDate ";

    if (timeModifier == TimeModifier.ANY || timeModifier == TimeModifier.NO) {
        if (timeModifier == TimeModifier.NO)
            doInvert = true;
        sb.append("select o.person_id from obs o " + "where voided = false and concept_id = :concept_id ");
        sb.append(dateSql);
    } else if (timeModifier == TimeModifier.FIRST || timeModifier == TimeModifier.LAST) {
        boolean isFirst = timeModifier == PatientSetService.TimeModifier.FIRST;
        sb.append("select o.person_id " + "from obs o inner join (" + "    select person_id, "
                + (isFirst ? "min" : "max") + "(obs_datetime) as obs_datetime" + "    from obs"
                + "    where voided = false and concept_id = :concept_id " + dateSql + "    group by person_id"
                + ") subq on o.person_id = subq.person_id and o.obs_datetime = subq.obs_datetime "
                + "where o.voided = false and o.concept_id = :concept_id ");
    } else if (doSqlAggregation) {
        String sqlAggregator = timeModifier.toString();
        valueSql = sqlAggregator + "(o.value_numeric)";
        sb.append("select o.person_id " + "from obs o where o.voided = false and concept_id = :concept_id "
                + dateSql + "group by o.person_id ");
    } else {
        throw new IllegalArgumentException("TimeModifier '" + timeModifier + "' not recognized");
    }

    if (useValue) {
        sb.append(doSqlAggregation ? "having " : " and ");
        sb.append(valueSql + " ");
        sb.append(modifier.getSqlRepresentation() + " :value");
    }
    if (!doSqlAggregation)
        sb.append(" group by o.person_id ");

    log.debug("query: " + sb);
    Query query = sessionFactory.getCurrentSession().createSQLQuery(sb.toString());
    query.setCacheMode(CacheMode.IGNORE);

    query.setInteger("concept_id", conceptId);
    if (useValue) {
        query.setDouble("value", value.doubleValue());
    }
    if (fromDate != null)
        query.setDate("fromDate", fromDate);
    if (toDate != null)
        query.setDate("toDate", fromDate);

    Cohort ret;
    if (doInvert) {
        ret = getAllPatients();
        ret.getMemberIds().removeAll(query.list());
    } else {
        ret = new Cohort(query.list());
    }

    return ret;
}

From source file:org.openmrs.module.reportingcompatibility.service.db.HibernateReportingCompatibilityDAO.java

License:Open Source License

public Cohort getPatientsByCharacteristics(String gender, Date minBirthdate, Date maxBirthdate, Integer minAge,
        Integer maxAge, Boolean aliveOnly, Boolean deadOnly, Date effectiveDate) throws DAOException {

    if (effectiveDate == null) {
        effectiveDate = new Date();
    }// ww w . j  a  v a 2 s .  c om

    StringBuffer queryString = new StringBuffer("select patientId from Patient patient");
    List<String> clauses = new ArrayList<String>();

    clauses.add("patient.voided = false");

    if (gender != null) {
        gender = gender.toUpperCase();
        clauses.add("patient.gender = :gender");
    }
    if (minBirthdate != null) {
        clauses.add("patient.birthdate >= :minBirthdate");
    }
    if (maxBirthdate != null) {
        clauses.add("patient.birthdate <= :maxBirthdate");
    }
    if (aliveOnly != null && aliveOnly) {
        clauses.add("patient.dead = false"); // TODO: Should this use effectiveDate?  What if deathDate is null?
    }
    if (deadOnly != null && deadOnly) {
        clauses.add("patient.dead = true"); // TODO: Should this use effectiveDate?  What if deathDate is null?
    }

    Date maxBirthFromAge = null;
    if (minAge != null) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(effectiveDate);
        cal.add(Calendar.YEAR, -minAge);
        maxBirthFromAge = cal.getTime();
        clauses.add("patient.birthdate <= :maxBirthFromAge");
    }
    Date minBirthFromAge = null;
    if (maxAge != null) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(effectiveDate);
        cal.add(Calendar.YEAR, -(maxAge + 1));
        minBirthFromAge = cal.getTime();
        clauses.add("patient.birthdate > :minBirthFromAge");
    }

    clauses.add("(patient.birthdate is null or patient.birthdate <= :effectiveDate)");

    boolean first = true;
    for (String clause : clauses) {
        if (first) {
            queryString.append(" where ").append(clause);
            first = false;
        } else {
            queryString.append(" and ").append(clause);
        }
    }
    Query query = sessionFactory.getCurrentSession().createQuery(queryString.toString());
    query.setCacheMode(CacheMode.IGNORE);
    if (gender != null) {
        query.setString("gender", gender);
    }
    if (minBirthdate != null) {
        query.setDate("minBirthdate", minBirthdate);
    }
    if (maxBirthdate != null) {
        query.setDate("maxBirthdate", maxBirthdate);
    }
    if (minAge != null) {
        query.setDate("maxBirthFromAge", maxBirthFromAge);
    }
    if (maxAge != null) {
        query.setDate("minBirthFromAge", minBirthFromAge);
    }
    query.setDate("effectiveDate", effectiveDate);

    return new Cohort(query.list());
}

From source file:org.openmrs.module.reportingcompatibility.service.db.HibernateReportingCompatibilityDAO.java

License:Open Source License

/**
 * Returns a Map from patientId to a Collection of drugIds for drugs active for the patients on
 * that date//from   w  ww  . jav  a  2  s  .co m
 * If patientIds is null then do this for all patients
 * Does not return anything for voided patients
 * 
 * @throws DAOException
 */
@SuppressWarnings("unchecked")
public Map<Integer, Collection<Integer>> getActiveDrugIds(Collection<Integer> patientIds, Date fromDate,
        Date toDate) throws DAOException {
    HashSet<Integer> idsLookup = patientIds == null ? null
            : (patientIds instanceof HashSet ? (HashSet<Integer>) patientIds
                    : new HashSet<Integer>(patientIds));

    Map<Integer, Collection<Integer>> ret = new HashMap<Integer, Collection<Integer>>();

    List<String> whereClauses = new ArrayList<String>();
    whereClauses.add("o.voided = false");
    if (toDate != null)
        whereClauses.add("o.start_date <= :toDate");
    if (fromDate != null) {
        whereClauses.add("(o.auto_expire_date is null or o.auto_expire_date > :fromDate)");
        whereClauses.add("(o.discontinued_date is null or o.discontinued_date > :fromDate)");
    }

    String sql = "select o.patient_id, d.drug_inventory_id " + "from orders o "
            + "    inner join patient p on o.patient_id = p.patient_id and p.voided = false "
            + "    inner join drug_order d on o.order_id = d.order_id ";
    for (ListIterator<String> i = whereClauses.listIterator(); i.hasNext();) {
        sql += (i.nextIndex() == 0 ? " where " : " and ");
        sql += i.next();
    }

    log.debug("sql= " + sql);

    Query query = sessionFactory.getCurrentSession().createSQLQuery(sql);
    query.setCacheMode(CacheMode.IGNORE);

    if (toDate != null)
        query.setDate("toDate", toDate);
    if (fromDate != null)
        query.setDate("fromDate", fromDate);

    List<Object[]> results = (List<Object[]>) query.list();
    for (Object[] row : results) {
        Integer patientId = (Integer) row[0];
        if (idsLookup == null || idsLookup.contains(patientId)) {
            Integer drugId = (Integer) row[1];
            Collection<Integer> drugIds = ret.get(patientId);
            if (drugIds == null) {
                drugIds = new HashSet<Integer>();
                ret.put(patientId, drugIds);
            }
            drugIds.add(drugId);
        }
    }
    return ret;
}

From source file:org.openmrs.module.reportingcompatibility.service.db.HibernateReportingCompatibilityDAO.java

License:Open Source License

/**
 * This method assumes the patient is not simultaneously enrolled in the program more than once.
 * if (includeVoided == true) then include voided programs if (includePast == true) then include
 * program which are already complete In all cases this only returns the latest program
 * enrollment for each patient./*w w  w.ja  v  a2  s  .  c o  m*/
 */
@SuppressWarnings("unchecked")
public Map<Integer, PatientProgram> getPatientPrograms(Cohort ps, Program program, boolean includeVoided,
        boolean includePast) throws DAOException {
    Map<Integer, PatientProgram> ret = new HashMap<Integer, PatientProgram>();

    Date now = new Date();

    // First get Map of patientId to patientProgramId for efficiency
    Map<Integer, Integer> programIdToPatient = new HashMap<Integer, Integer>();
    String sql = "select patient_program_id, patient_id from patient_program";
    Query q = sessionFactory.getCurrentSession().createSQLQuery(sql);
    q.setCacheMode(CacheMode.IGNORE);
    List<Object[]> l = q.list();
    for (Object[] row : l) {
        programIdToPatient.put((Integer) row[0], (Integer) row[1]);
    }

    // Next get all PatientPrograms from the DB
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(PatientProgram.class);
    criteria.setCacheMode(CacheMode.IGNORE);
    criteria.add(Restrictions.eq("program", program));
    if (!includeVoided) {
        criteria.add(Restrictions.eq("voided", false));
    }
    criteria.add(Restrictions.or(Restrictions.isNull("dateEnrolled"), Restrictions.le("dateEnrolled", now)));
    if (!includePast) {
        criteria.add(
                Restrictions.or(Restrictions.isNull("dateCompleted"), Restrictions.ge("dateCompleted", now)));
    }
    log.debug("criteria: " + criteria);
    List<PatientProgram> temp = criteria.list();

    // Finally, construct return list based on input Cohort      
    for (PatientProgram prog : temp) {
        Integer patientProgramId = prog.getPatientProgramId();
        Integer patientId = programIdToPatient.get(patientProgramId);
        if (ps == null || ps.contains(patientId)) {
            ret.put(patientId, prog);
        }
    }
    return ret;
}

From source file:org.openmrs.module.reportingcompatibility.service.db.HibernateReportingCompatibilityDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
public Map<Integer, List<DrugOrder>> getDrugOrders(Cohort patients, List<Concept> drugConcepts)
        throws DAOException {

    Map<Integer, List<DrugOrder>> ret = new HashMap<Integer, List<DrugOrder>>();
    if (patients != null && patients.size() == 0) {
        return ret;
    }/*from w ww  .  j  a  va2 s  .c o  m*/

    // First get Map of patientId to orderId for efficiency
    Map<Integer, Integer> orderIdToPatient = new HashMap<Integer, Integer>();
    String sql = "select o.order_id, o.patient_id from orders o, drug_order d where o.order_id = d.order_id";
    Query q = sessionFactory.getCurrentSession().createSQLQuery(sql);
    q.setCacheMode(CacheMode.IGNORE);
    List<Object[]> l = q.list();
    for (Object[] row : l) {
        orderIdToPatient.put((Integer) row[0], (Integer) row[1]);
    }

    // Next get all DrugOrders from the DB
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(DrugOrder.class);
    criteria.setCacheMode(CacheMode.IGNORE);
    if (drugConcepts != null) {
        criteria.add(Restrictions.in("concept", drugConcepts));
    }
    criteria.add(Restrictions.eq("voided", false));
    criteria.addOrder(org.hibernate.criterion.Order.asc("startDate"));
    log.debug("criteria: " + criteria);
    List<DrugOrder> temp = criteria.list();

    // Finally, construct return list based on input Cohort      
    for (DrugOrder regimen : temp) {
        Integer orderId = regimen.getOrderId();
        Integer patientId = orderIdToPatient.get(orderId);
        if (patients == null || patients.contains(patientId)) {
            List<DrugOrder> list = ret.get(patientId);
            if (list == null) {
                list = new ArrayList<DrugOrder>();
                ret.put(patientId, list);
            }
            list.add(regimen);
        }
    }
    return ret;
}