Example usage for org.hibernate CacheMode IGNORE

List of usage examples for org.hibernate CacheMode IGNORE

Introduction

In this page you can find the example usage for org.hibernate CacheMode IGNORE.

Prototype

CacheMode IGNORE

To view the source code for org.hibernate CacheMode IGNORE.

Click Source Link

Document

The session will never interact with the cache, except to invalidate cache items when updates occur.

Usage

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

License:Mozilla Public License

/**
 * @param patients//from   w ww. j  a v  a 2 s. c o m
 * @param types List<PatientIdentifierTypes> of types to get
 * @return Map of {@link PatientIdentifier}s
 */
@SuppressWarnings("unchecked")
public Map<Integer, String> getPatientIdentifierByType(Cohort patients, List<PatientIdentifierType> types) {
    Map<Integer, String> patientIdentifiers = new HashMap<Integer, String>();

    // default query
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(PatientIdentifier.class);

    // only get the "identifier" and "patientId" columns
    ProjectionList projections = Projections.projectionList();
    projections.add(Projections.property("identifier"));
    projections.add(Projections.property("patient.personId"));
    criteria.setProjection(projections);

    criteria.setCacheMode(CacheMode.IGNORE);

    // Add patient restriction if necessary
    if (patients != null) {
        criteria.add(Restrictions.in("patient.personId", patients.getMemberIds()));
    }

    // all identifiers must be non-voided
    criteria.add(Restrictions.eq("voided", false));

    // Add identifier type filter
    if (types != null && types.size() > 0) {
        criteria.add(Restrictions.in("identifierType", types));
    }

    // Order by ID
    criteria.addOrder(org.hibernate.criterion.Order.desc("patient.personId"));

    List<Object[]> rows = criteria.list();

    // set up the return map
    for (Object[] row : rows) {
        String identifier = (String) row[0];
        Integer patientId = (Integer) row[1];
        if (!patientIdentifiers.containsKey(patientId)) {
            patientIdentifiers.put(patientId, identifier);
        }
    }

    return patientIdentifiers;
}

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.jav a 2 s .  co  m
 */
@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  w  w  . j  av a2  s .co 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 {/*from   w  w w.  ja  v  a2 s. com*/
            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 ava2  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;

}

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;
    }//from  w w w .  ja  v  a  2 s .c  om
    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  a  va 2  s .  c  o m

    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.idcards.db.hibernate.HibernateIdcardsDAO.java

License:Open Source License

/**
 * @see org.openmrs.module.idcards.db.IdcardsDAO#generateIdentifiers(int, int)
 */// ww w.  ja v a 2s .c  o  m
public void generateIdentifiers(int identifierStartValue, int quantityToGenerate) throws DAOException {
    Date generatedDate = new Date();
    String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(generatedDate);
    Integer currentUserId = Context.getAuthenticatedUser().getUserId();

    Session currentSession = sessionFactory.getCurrentSession();
    currentSession.setCacheMode(CacheMode.IGNORE);

    String insertPrefix = "insert into idcards_generated_identifier (id, generator, date_generated) values ";
    String valuesPrefix = "(";
    String valuesSuffix = ", " + currentUserId + ", '" + date + "')";

    // if we're in mysql, do extended inserts to speed things up
    SessionFactoryImplementor implementor = (SessionFactoryImplementor) sessionFactory;
    Dialect dialect = implementor.getDialect();
    boolean isMySQLDialect = MySQLDialect.class.getName().equals(dialect.getClass().getName());

    if (isMySQLDialect) {
        String sql = null;
        // loop over the list of numbers and get/insert the string identifier
        for (int x = identifierStartValue; x < identifierStartValue + quantityToGenerate; x++) {
            if (sql == null) // if its not the first element, add a comma
                sql = insertPrefix;
            else
                sql += ",";

            sql += valuesPrefix + x + valuesSuffix;

            // send to the database every 1001 entries or at the end 
            if (x % 100 == 0 || x == (identifierStartValue + quantityToGenerate - 1)) {
                try {
                    SQLQuery query = currentSession.createSQLQuery(sql);
                    query.executeUpdate();
                    sql = null; // reset the sql string
                    currentSession.flush();
                } catch (ConstraintViolationException cve) {
                    log.error("Sql: " + sql);
                    throw new DAOException("Error creating an identifier between " + x + " and " + (x - 1001)
                            + " because it already exists in the system", cve);
                }
            }
        }

    } else {
        for (int x = identifierStartValue; x < identifierStartValue + quantityToGenerate; x++) {
            String sql = insertPrefix + valuesPrefix + x + valuesSuffix;

            try {
                SQLQuery query = currentSession.createSQLQuery(sql);
                query.executeUpdate();
            } catch (ConstraintViolationException cve) {
                throw new DAOException(
                        "Unable to create identifier: " + x + " because it already exists in the system", cve);
            }

            // control the number of objects in memory
            if (x % 500 == 0 || x == (identifierStartValue + quantityToGenerate - 1)) {
                currentSession.flush();
                currentSession.clear();
            }
        }
    }

}

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  v a  2s.  com*/
            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 w w  w .  j ava2  s . co  m*/
                    return patients;
                }
            } catch (Exception e) {
                log.error("error finding patients", e);
            }
        }
    }
    return new ArrayList<Patient>();
}