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.api.db.hibernate.HibernatePatientSetDAO.java

License:Mozilla Public 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();
    }//from www. j a  va 2  s  .  c o m

    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");
    }
    if (deadOnly != null && deadOnly) {
        clauses.add("patient.dead = true");
    }

    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.api.db.hibernate.HibernatePatientSetDAO.java

License:Mozilla Public License

@SuppressWarnings("unchecked")
public Map<Integer, String> getShortPatientDescriptions(Collection<Integer> patientIds) throws DAOException {
    Map<Integer, String> ret = new HashMap<Integer, String>();

    Query query = sessionFactory.getCurrentSession().createQuery(
            "select patient.personId, patient.gender, patient.birthdate from Patient patient where voided = false");
    query.setCacheMode(CacheMode.IGNORE);

    List<Object[]> temp = query.list();

    long now = System.currentTimeMillis();
    for (Object[] results : temp) {
        if (!patientIds.contains(results[0])) {
            continue;
        }/*  w  w w  .  j  ava 2  s  . c om*/
        StringBuffer sb = new StringBuffer();
        if ("M".equals(results[1])) {
            sb.append("Male");
        } else {
            sb.append("Female");
        }
        Date bd = (Date) results[2];
        if (bd != null) {
            int age = (int) ((now - bd.getTime()) / MS_PER_YEAR);
            sb.append(", ").append(age).append(" years old");
        }
        ret.put((Integer) results[0], sb.toString());
    }

    return ret;
}

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

License:Mozilla Public License

@SuppressWarnings("unchecked")
public Map<Integer, Map<String, Object>> getCharacteristics(Cohort patients) throws DAOException {
    Map<Integer, Map<String, Object>> ret = new HashMap<Integer, Map<String, Object>>();
    Collection<Integer> ids = patients.getMemberIds();
    Query query = sessionFactory.getCurrentSession().createQuery(
            "select patient.personId, patient.gender, patient.birthdate from Patient patient where patient.voided = false");
    query.setCacheMode(CacheMode.IGNORE);

    List<Object[]> temp = query.list();

    long now = System.currentTimeMillis();
    for (Object[] results : temp) {
        Integer patientId = (Integer) results[0];
        if (!ids.contains(patientId)) {
            continue;
        }// ww w. ja v a2  s. c  o m
        Map<String, Object> holder = new HashMap<String, Object>();
        holder.put("gender", results[1]);
        Date bd = (Date) results[2];
        if (bd != null) {
            int age = (int) ((now - bd.getTime()) / MS_PER_YEAR);
            holder.put("age_years", age);
            holder.put("birthdate", bd);
        }
        ret.put(patientId, holder);
    }

    return ret;
}

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

License:Mozilla Public License

public Cohort getPatientsHavingTextObs(Integer conceptId, String value, TimeModifier timeModifier)
        throws DAOException {
    Query query;
    StringBuffer sb = new StringBuffer();
    sb.append("select o.person_id from obs o ");

    if (timeModifier != null) {
        if (timeModifier.equals(TimeModifier.LAST)) {
            log.debug("timeModifier is NOT NULL, and appears to be LAST, so we'll try to add a subquery");
            sb.append("inner join (select person_id, max(obs_datetime) as obs_datetime from obs where ");
            sb.append(//from  w  w w .j  a  v  a  2s  .  com
                    "concept_id = :concept_id group by person_id) sub on o.person_id = sub.person_id and o.obs_datetime = sub.obs_datetime ");
        } else {
            log.debug("timeModifier is NOT NULL, and appears to not be LAST, so we won't do anything");
        }
    } else {
        log.debug("timeModifier is NULL, skipping to full query");
    }

    sb.append("where o.concept_id = :concept_id ");
    boolean useVal = false;
    if (value != null) {
        sb.append("and o.value_text = :value ");
        useVal = true;
    } else {
        sb.append("and o.value_text is not null ");
    }
    sb.append("group by o.person_id ");

    query = sessionFactory.getCurrentSession().createSQLQuery(sb.toString());
    query.setCacheMode(CacheMode.IGNORE);
    query.setInteger("concept_id", conceptId);
    if (useVal) {
        query.setString("value", value);
    }

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

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

License:Mozilla Public License

public Cohort convertPatientIdentifier(List<String> identifiers) throws DAOException {

    StringBuffer sb = new StringBuffer();
    sb.append("select distinct(patient_id) from patient_identifier p ");
    sb.append("where identifier in (:identifiers)");
    Query query = sessionFactory.getCurrentSession().createSQLQuery(sb.toString());
    query.setCacheMode(CacheMode.IGNORE);
    query.setParameterList("identifiers", identifiers, new StringType());
    return new Cohort(query.list());
}

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

License:Mozilla Public License

/**
 * Returns a Map from patientId to a Collection of drugIds for drugs active for the patients on
 * that date If patientIds is null then do this for all patients Does not return anything for
 * voided patients//from w ww .  java  2  s .c om
 * 
 * @throws DAOException
 */
@SuppressWarnings("unchecked")
public Map<Integer, Collection<Integer>> getActiveDrugIds(Collection<Integer> patientIds, Date fromDate,
        Date toDate) throws DAOException {
    Set<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.date_activated <= :toDate");
    }
    if (fromDate != null) {
        whereClauses.add("(o.auto_expire_date is null or o.auto_expire_date > :fromDate)");
        whereClauses.add("(o.date_stopped is null or o.date_stopped > :fromDate)");
    }

    StringBuilder sql = new StringBuilder("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.append((i.nextIndex() == 0 ? " where " : " and ")).append(i.next());
    }

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

    Query query = sessionFactory.getCurrentSession().createSQLQuery(sql.toString());
    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.haitimobileclinic.service.db.HibernateHaitiMobileClinicDAO.java

License:Open Source License

/**
 * @return the relevant person address value for each patient in the passed cohort if they have a person address, limited by the
 * passed filter criteria/*w w  w  .ja  va  2s.  com*/
 */
@SuppressWarnings("unchecked")
public Map<Integer, String> getAddressValuesForCohort(Cohort c, String addressField,
        Map<String, String> filterCriteria) {
    Map<Integer, String> ret = new HashMap<Integer, String>();
    if (!c.isEmpty()) {
        StringBuilder sql = new StringBuilder();
        sql.append("select p.personId, a." + addressField + " from Person p, PersonAddress a ");
        sql.append("where p.personId = a.person.personId and p.voided = false and a.voided = false ");
        // NOTE: Removed 'and a.preferred = true ' since many/most addresses didn't have this set properly (MS)
        sql.append("and p.personId in (" + c.getCommaSeparatedPatientIds() + ") ");
        for (String filterKey : filterCriteria.keySet()) {
            sql.append("and a." + filterKey + " = :" + filterKey + " ");
        }
        Query query = sessionFactory.getCurrentSession().createQuery(sql.toString());
        for (String filterKey : filterCriteria.keySet()) {
            query.setParameter(filterKey, filterCriteria.get(filterKey));
        }
        query.setCacheMode(CacheMode.IGNORE);
        List<Object[]> queryResults = query.list();
        for (Object[] row : queryResults) {
            ret.put(Integer.valueOf(row[0].toString()), row[1] == null ? "" : row[1].toString());
        }
    }
    return ret;
}

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

License:Open Source License

public Set<String> searchNames(String name, String nameField) {
    Set<String> firstNames = null;
    if (StringUtils.isNotBlank(name)) {
        StringBuilder sql = new StringBuilder();
        sql.append("select distinct(n.").append(nameField).append(") ");
        sql.append("from PersonName n ");
        sql.append("where n.").append(nameField).append(" like '%").append(name).append("%' ");
        sql.append("group by n.").append(nameField).append(" ");
        sql.append("order by n.").append(nameField).append(" ");
        try {/*from   w ww.j a  v  a2 s .c o m*/
            Query query = sessionFactory.getCurrentSession().createQuery(sql.toString());
            query.setCacheMode(CacheMode.IGNORE);
            List<String> queryResults = (List<String>) query.list();
            if (queryResults != null && queryResults.size() > 0) {
                firstNames = new HashSet<String>();
                for (String personName : queryResults) {
                    firstNames.add(personName);
                }
            }
        } catch (Exception e) {
            log.error("error retrieving patient names", e);
        }
    }
    return firstNames;
}

From source file:org.openmrs.module.haitimobileclinic.service.db.HibernateHaitiMobileClinicDAO.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)) {
        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(name).append("%' ");
        sql.append("group by n.").append(nameField).append(" ");
        sql.append("order by count(*) desc, n.").append(nameField).append(" ");
        try {/*  w ww  .j  a v a 2s  . c  o m*/
            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.haitimobileclinic.service.db.HibernateHaitiMobileClinicDAO.java

License:Open Source License

public List<Patient> getPatientsByNameId(List<Integer> nameIds) {
    List<Patient> patients = null;
    if (nameIds == null || (nameIds != null && nameIds.size() < 1)) {
        return null;
    }/* w  w w . j  av a 2  s.  co  m*/
    try {
        Query query = sessionFactory.getCurrentSession()
                .createQuery("from Patient as p where p.personId in (:nameIds)");
        query.setParameterList("nameIds", nameIds);
        query.setCacheMode(CacheMode.IGNORE);
        patients = query.list();
        if (patients != null && patients.size() > 0) {
            return patients;

        }

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

}