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.haitimobileclinic.service.db.HibernateHaitiMobileClinicDAO.java

License:Open Source License

public List<Integer> getPhoneticsPersonId(String firstName, String lastName) {

    List<Integer> queryResults = null;
    if (StringUtils.isBlank(firstName) || (StringUtils.isBlank(lastName))) {
        return queryResults;
    }//  ww w. j av a 2s . c  o m
    StringBuilder sql = new StringBuilder();
    sql.append("select distinct np1.personName.personNameId ");
    sql.append("from NamePhonetic np1 ");
    sql.append("where np1.renderedString like '").append(firstName).append("%' ");
    sql.append("and np1.nameField=1 ");
    sql.append("and np1.personName.personNameId in ");
    sql.append("(select np2.personName.personNameId from NamePhonetic np2 ");
    sql.append("where np2.renderedString like '").append(lastName).append("%' ");
    sql.append("and np2.nameField=3) ");
    try {
        Query query = sessionFactory.getCurrentSession().createQuery(sql.toString());
        query.setCacheMode(CacheMode.IGNORE);

        queryResults = query.list();
        if (queryResults != null && queryResults.size() > 0) {
            return queryResults;

        }

    } catch (Exception e) {
        log.error("error retrieving name phonetics", e);
    }

    return queryResults;
}

From source file:org.openmrs.module.haitimobileclinic.service.db.HibernateHaitiMobileClinicDAO.java

License:Open Source License

public List<String> getDistinctObs(Integer conceptId) {
    List<String> distinctObs = null;
    if (conceptId == null) {
        return distinctObs;
    }/*  w w  w .  j ava 2 s. com*/

    StringBuilder sql = new StringBuilder();
    sql.append("select distinct(trim(value_text)) as NonCodedDiagnoses");
    sql.append(" from Obs where voided=0 and concept_id=").append(conceptId.toString());
    sql.append(" order by value_text");
    try {
        Query query = sessionFactory.getCurrentSession().createQuery(sql.toString());
        query.setCacheMode(CacheMode.IGNORE);
        distinctObs = query.list();
        if (distinctObs != null && distinctObs.size() > 0) {
            List<String> cleanObs = new ArrayList<String>();
            for (String obs : distinctObs) {
                cleanObs.add(obs.replace("\\", " "));
            }
            return cleanObs;
        }
    } catch (Exception e) {
        log.error("error retrieving distinct obs", e);
    }
    return distinctObs;
}

From source file:org.openmrs.module.patientregistration.service.db.HibernatePatientRegistrationDAO.java

License:Open Source License

public Map<String, Integer> searchNamesByOccurence(String name, String nameField) {
    Map<String, Integer> nameOccurences = new HashMap<String, Integer>();
    if (StringUtils.isNotBlank(name)) {
        String escapedName = StringEscapeUtils.escapeSql(name);
        StringBuilder sql = new StringBuilder();
        sql.append("select distinct(n.").append(nameField).append("), count(*) ");
        sql.append("from PersonName n ");
        sql.append("where n.").append(nameField).append(" like '%").append(escapedName).append("%' ");
        sql.append("and person.personId not in (");
        sql.append("select pa.person.personId ");
        sql.append("from PersonAttribute pa ");
        sql.append("where pa.attributeType.name='");
        sql.append(PatientRegistrationConstants.UNKNOWN_PATIENT_PERSON_ATTRIBUTE_TYPE_NAME);
        sql.append("' and pa.value='true' ");
        sql.append(")");

        sql.append("group by n.").append(nameField).append(" ");
        sql.append("order by count(*) desc, n.").append(nameField).append(" ");
        try {/*from   ww  w.j a  va 2s. c  om*/
            Query query = sessionFactory.getCurrentSession().createQuery(sql.toString());
            query.setCacheMode(CacheMode.IGNORE);

            List<Object[]> queryResults = query.list();
            for (Object[] row : queryResults) {
                nameOccurences.put(row[0] == null ? "" : row[0].toString(), Integer.valueOf(row[1].toString()));
            }
        } catch (Exception e) {
            log.error("error retrieving patient names", e);
        }
    }
    return nameOccurences;
}

From source file:org.openmrs.module.patientregistration.service.db.HibernatePatientRegistrationDAO.java

License:Open Source License

@Override
public List<Patient> getPatientsByName(PersonName personName) {
    List<Patient> patients = null;
    if (personName != null) {
        String firstName = personName.getGivenName();
        String lastName = personName.getFamilyName();
        if (StringUtils.isNotBlank(firstName) && StringUtils.isNotBlank(lastName)) {
            try {
                Query query = sessionFactory.getCurrentSession()
                        .createQuery("from Patient as p" + " left outer join p.names as n"
                                + " where (n.givenName= :firstName and n.familyName= :lastName) or"
                                + " (n.givenName= :lastName and n.familyName= :firstName)");

                query.setParameter("firstName", firstName);
                query.setParameter("lastName", lastName);

                query.setCacheMode(CacheMode.IGNORE);
                List<Object[]> results = query.list();
                if (results != null && results.size() > 0) {
                    patients = new ArrayList<Patient>();
                    for (Object[] result : results) {
                        Patient patient = (Patient) result[0];
                        patients.add(patient);
                    }//from ww  w . j  av  a  2 s .  co m
                    return patients;
                }
            } catch (Exception e) {
                log.error("error finding patients", e);
            }
        }
    }
    return new ArrayList<Patient>();
}

From source file:org.openmrs.module.patientregistration.service.db.HibernatePatientRegistrationDAO.java

License:Open Source License

public List<Integer> getUnknownPersonId() {
    List<Integer> queryResults = null;
    StringBuilder sql = new StringBuilder();
    sql.append("select distinct pa.person.personId ");
    sql.append("from PersonAttribute pa ");
    sql.append("where pa.attributeType.name='");
    sql.append(PatientRegistrationConstants.UNKNOWN_PATIENT_PERSON_ATTRIBUTE_TYPE_NAME);
    sql.append("' and pa.value='true' ");
    try {/*from   ww w.  j a  va  2s.  c  o  m*/
        Query query = sessionFactory.getCurrentSession().createQuery(sql.toString());
        query.setCacheMode(CacheMode.IGNORE);
        queryResults = query.list();
        if (queryResults != null && queryResults.size() > 0) {
            return queryResults;
        }

    } catch (Exception e) {
        log.error("error retrieving the IDs of the unknown persons", e);
    }
    return queryResults;
}

From source file:org.openmrs.module.patientregistration.service.db.HibernatePatientRegistrationDAO.java

License:Open Source License

public List<Integer> getPhoneticsPersonId(String firstName, String lastName) {

    List<Integer> queryResults = null;
    if (StringUtils.isBlank(firstName) || (StringUtils.isBlank(lastName))) {
        return queryResults;
    }//  w  w  w. ja  va  2s  .c om
    StringBuilder sql = new StringBuilder();
    sql.append("select distinct np1.personName.person.personId ");
    sql.append("from NamePhonetic np1 ");
    sql.append("where np1.renderedString like '").append(firstName).append("%' ");
    sql.append("and np1.nameField=1 ");
    sql.append("and np1.personName.personNameId in ");
    sql.append("(select np2.personName.personNameId from NamePhonetic np2 ");
    sql.append("where np2.renderedString like '").append(lastName).append("%' ");
    sql.append("and np2.nameField=3) ");
    try {
        Query query = sessionFactory.getCurrentSession().createQuery(sql.toString());
        query.setCacheMode(CacheMode.IGNORE);

        queryResults = query.list();
        if (queryResults != null && queryResults.size() > 0) {
            return queryResults;

        }

    } catch (Exception e) {
        log.error("error retrieving name phonetics", e);
    }

    return queryResults;
}

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

License:Open Source License

public Cohort getPatientsWithGender(boolean includeMales, boolean includeFemales,
        boolean includeUnknownGender) {

    if (!includeMales && !includeFemales && !includeUnknownGender) {
        return new Cohort();
    }//  www  .  j  av  a  2s .  c o m

    String prefixTerm = "";
    StringBuilder query = new StringBuilder(
            "select patientId from Patient patient where patient.voided = false and ( ");
    if (includeMales) {
        query.append(" patient.gender = 'M' ");
        prefixTerm = " or";
    }
    if (includeFemales) {
        query.append(prefixTerm + " patient.gender = 'F'");
        prefixTerm = " or";
    }
    if (includeUnknownGender) {
        query.append(
                prefixTerm + " patient.gender is null or (patient.gender != 'M' and patient.gender != 'F')");
    }
    query.append(")");
    Query q = sessionFactory.getCurrentSession().createQuery(query.toString());
    q.setCacheMode(CacheMode.IGNORE);
    return new Cohort(q.list());
}

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

License:Open Source License

/**
 * //from  w  w w  .ja va2  s. com
 */
public Cohort getPatientsHavingBirthDateBetweenDates(Date bornOnOrAfter, Date bornOnOrBefore)
        throws DAOException {

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

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

    if (bornOnOrAfter != null) {
        clauses.add("patient.birthdate >= :bornOnOrAfter");
    }
    if (bornOnOrBefore != null) {
        clauses.add("patient.birthdate <= :bornOnOrBefore");
    }

    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());

    log.debug("Patients having birthdate between dates: " + query.getQueryString());

    query.setCacheMode(CacheMode.IGNORE);
    if (bornOnOrAfter != null) {
        query.setDate("bornOnOrAfter", bornOnOrAfter);
    }
    if (bornOnOrBefore != null) {
        query.setDate("bornOnOrBefore", bornOnOrBefore);
    }
    return new Cohort(query.list());

}

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

License:Open Source License

/**
 * /*from www. j  a  va2  s  .c  om*/
 */
public Cohort getPatientsHavingDiedBetweenDates(Date diedOnOrAfter, Date diedOnOrBefore) throws DAOException {

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

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

    if (diedOnOrAfter != null) {
        clauses.add("patient.deathDate >= :diedOnOrAfter");
    }
    if (diedOnOrBefore != null) {
        clauses.add("patient.deathDate <= :diedOnOrBefore");
    }

    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 (diedOnOrAfter != null) {
        query.setDate("diedOnOrAfter", diedOnOrAfter);
    }
    if (diedOnOrBefore != null) {
        query.setDate("diedOnOrBefore", diedOnOrBefore);
    }
    log.debug("Patients having died between dates query: " + query.getQueryString());

    return new Cohort(query.list());

}

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

License:Open Source License

/**
 * //from  w w  w .j  a  v  a  2s.com
 */
public Cohort getPatientsHavingObs(Integer conceptId, TimeModifier timeModifier, Modifier modifier,
        Object value, Date fromDate, Date toDate, List<User> providers, EncounterType encounterType) {

    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");
    }
    Concept concept = null;
    if (conceptId != null)
        concept = Context.getConceptService().getConcept(conceptId);

    // TODO This should be refactored out
    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 if (value instanceof Number) {
                numericValue = (Number) value;
                booleanValue = (numericValue.doubleValue() != 0.0) ? Boolean.TRUE : Boolean.FALSE;
            } 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 ";
    }

    String encounterSql = "";
    String encounterSqlTable = "";
    String encounterJoin = "";
    String encounterSqlForSubquery = "";
    if (encounterType != null) {
        encounterSqlTable = ", encounter e ";
        encounterJoin = " and e.encounter_id = o.encounter_id ";
        encounterSql += " and e.encounter_type = :encounterType ";
        encounterSqlForSubquery = " inner join encounter e on e.encounter_id = o.encounter_id ";
    }

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

        sb.append(encounterJoin);
        sb.append(encounterSql);
        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 o"
                + "    where o.voided = false and o.concept_id = :concept_id " + dateSqlForSubquery
                + "    group by person_id"
                + ") subq on o.person_id = subq.person_id and o.obs_datetime = subq.obs_datetime "
                + encounterSqlForSubquery + "where o.voided = false and o.concept_id = :concept_id "
                + encounterSql);

    } else if (doSqlAggregation) {
        String sqlAggregator = timeModifier.toString();
        valueSql = sqlAggregator + "(" + valueSql + ")";
        sb.append("select o.person_id " + "from obs o " + encounterSqlTable
                + " where o.voided = false and o.concept_id = :concept_id " + dateSql + encounterJoin
                + encounterSql + "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);
    if (encounterType != null)
        query.setInteger("encounterType", encounterType.getEncounterTypeId());

    log.debug("Patients having obs query: " + query.getQueryString());

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

    return ret;
}