Example usage for org.hibernate Criteria setCacheMode

List of usage examples for org.hibernate Criteria setCacheMode

Introduction

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

Prototype

public Criteria setCacheMode(CacheMode cacheMode);

Source Link

Document

Override the cache mode for this particular query.

Usage

From source file:org.eurekastreams.server.persistence.mappers.cache.DomainGroupCacheLoader.java

License:Apache License

/**
 * Query all domain groups, loading them in the cache.
 *//*from  www.  j a v  a2  s  .c om*/
private void queryAllDomainGroups() {
    long start = System.currentTimeMillis();
    log.info("Loading up all domain groups with a single query");

    Criteria criteria = domainGroupQueryStrategy.getCriteria(getHibernateSession());

    // page the data
    criteria.setFetchSize(FETCH_SIZE);
    criteria.setCacheMode(CacheMode.IGNORE);
    ScrollableResults scroll = criteria.scroll(ScrollMode.FORWARD_ONLY);

    // loop through the results and store in cache
    long recordCounter = 0;
    while (scroll.next()) {
        if (++recordCounter % FETCH_SIZE == 0) {
            log.info("Loading " + recordCounter + "th domainGroup record, clearing session.");
            getHibernateSession().clear();
        }

        DomainGroupModelView result = (DomainGroupModelView) scroll.get(0);
        getCache().set(CacheKeys.GROUP_BY_ID + result.getEntityId(), result);
        getCache().set(CacheKeys.GROUP_BY_SHORT_NAME + result.getShortName(), result.getEntityId());
    }

    log.info("Completed loading all domain groups in " + (System.currentTimeMillis() - start)
            + " milliseconds.");
}

From source file:org.eurekastreams.server.persistence.mappers.cache.PersonCacheLoader.java

License:Apache License

/**
 * Query the database for all people, only requesting the fields that we're caching, paging for effeciency.
 */// w ww  .ja  va 2 s.c  o  m
private void queryAllPeople() {
    Criteria criteria = personQueryStrategy.getCriteria(getHibernateSession());

    // page the data
    criteria.setFetchSize(FETCH_SIZE);
    criteria.setCacheMode(CacheMode.IGNORE);
    ScrollableResults scroll = criteria.scroll(ScrollMode.FORWARD_ONLY);

    // loop through the results and store in cache
    long recordCounter = 0;
    while (scroll.next()) {
        if (++recordCounter % FETCH_SIZE == 0) {
            log.info("Loading " + recordCounter + "th person record, clearing session.");
            getHibernateSession().clear();
        }

        PersonModelView result = (PersonModelView) scroll.get(0);

        getCache().set(CacheKeys.PERSON_BY_ID + result.getEntityId(), result);
        getCache().set(CacheKeys.PERSON_BY_ACCOUNT_ID + result.getAccountId(), result.getEntityId());
        getCache().set(CacheKeys.PERSON_BY_OPEN_SOCIAL_ID + result.getOpenSocialId(), result.getEntityId());
    }
}

From source file:org.goobi.production.chart.HibernateProjectTaskList.java

License:Open Source License

private synchronized void calculate(Project inProject, List<IProjectTask> myTaskList, Boolean countImages,
        Integer inMax) {// w w w.j a  v  a2s. c o  m
    Session session = Helper.getHibernateSession();
    Criteria crit = session.createCriteria(Task.class);
    crit.addOrder(Order.asc("ordering"));
    crit.createCriteria("process", "proz");
    crit.add(Restrictions.eq("proz.template", Boolean.FALSE));
    crit.add(Restrictions.eq("proz.project", inProject));

    ScrollableResults list = crit.setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY);

    while (list.next()) {
        Task step = (Task) list.get(0);
        String shorttitle = (step.getTitle().length() > 60 ? step.getTitle().substring(0, 60) + "..."
                : step.getTitle());

        IProjectTask pt = null;
        for (IProjectTask task : myTaskList) {
            if (task.getTitle().equals(shorttitle)) {
                pt = task;
                break;
            }
        }
        if (pt == null) {
            pt = new ProjectTask(shorttitle, 0, 0);
            myTaskList.add(pt);
        }

        if (step.getProcessingStatusEnum() == TaskStatus.DONE) {
            if (countImages) {
                pt.setStepsCompleted(pt.getStepsCompleted() + step.getProcess().getSortHelperImages());
            } else {
                pt.setStepsCompleted(pt.getStepsCompleted() + 1);
            }
        }

        if (countImages) {
            pt.setStepsMax(pt.getStepsMax() + step.getProcess().getSortHelperImages());
        } else {
            pt.setStepsMax(pt.getStepsMax() + 1);
        }
    }
}

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

License:Mozilla Public License

/**
 * Create the criteria for fetching all encounters based on cohort
 *
 * @param patients/*from   ww w  .j a  va  2 s  .  co  m*/
 * @return a map of patient with their encounters
 */
private Criteria createEncounterCriteria(Cohort patients) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Encounter.class);
    criteria.setCacheMode(org.hibernate.CacheMode.IGNORE);

    // only include this where clause if patients were passed in
    if (patients != null) {
        criteria.add(Restrictions.in("patient.personId", patients.getMemberIds()));
    }

    criteria.add(Restrictions.eq("voided", false));

    criteria.addOrder(org.hibernate.criterion.Order.desc("patient.personId"));
    criteria.addOrder(org.hibernate.criterion.Order.desc("encounterDatetime"));
    return criteria;
}

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

License:Mozilla Public License

@SuppressWarnings("unchecked")
/**//from   w w w. j  a v  a 2 s  .  co  m
 * fromDate and toDate are both inclusive
 */
public Map<Integer, List<Obs>> getObservations(Cohort patients, Concept concept, Date fromDate, Date toDate)
        throws DAOException {
    Map<Integer, List<Obs>> ret = new HashMap<Integer, List<Obs>>();

    /*
    Query query = sessionFactory.getCurrentSession().createQuery("select obs, obs.patientId " +
                        "from Obs obs where obs.conceptId = :conceptId " +
                        " and obs.patientId in :ids " +
                        "order by obs.obsDatetime asc");
    query.setInteger("conceptId", conceptId);
    query.set
            
    List<Object[]> temp = query.list();
    for (Object[] holder : temp) {
       Obs obs = (Obs) holder[0];
       Integer ptId = (Integer) holder[1];
       List<Obs> forPatient = ret.get(ptId);
       if (forPatient == null) {
    forPatient = new ArrayList<Obs>();
    ret.put(ptId, forPatient);
       }
       forPatient.add(obs);
    }
     */
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Obs.class);
    criteria.setCacheMode(CacheMode.IGNORE);

    criteria.add(Restrictions.eq("concept", concept));

    // only add this where clause if patients were passed in
    if (patients != null) {
        criteria.add(Restrictions.in("person.personId", patients.getMemberIds()));
    }

    criteria.add(Restrictions.eq("voided", false));
    criteria.addOrder(org.hibernate.criterion.Order.desc("obsDatetime"));
    log.debug("criteria: " + criteria);
    List<Obs> temp = criteria.list();
    for (Obs obs : temp) {
        Integer ptId = obs.getPersonId();
        List<Obs> forPatient = ret.get(ptId);
        if (forPatient == null) {
            forPatient = new ArrayList<Obs>();
            ret.put(ptId, forPatient);
        }
        forPatient.add(obs);
    }

    return ret;
}

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

License:Mozilla Public License

@SuppressWarnings("unchecked")
public Map<Integer, List<List<Object>>> getObservationsValues(Cohort patients, Concept c,
        List<String> attributes, Integer limit, boolean showMostRecentFirst) {
    Map<Integer, List<List<Object>>> ret = new HashMap<Integer, List<List<Object>>>();

    List<String> aliases = new Vector<String>();
    Boolean conditional = false;//from ww  w  .ja va2 s .c o  m

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria("org.openmrs.Obs", "obs");
    criteria.setCacheMode(CacheMode.IGNORE);

    List<String> columns = new Vector<String>();

    for (String attribute : attributes) {
        List<String> classNames = new Vector<String>();
        if (attribute == null) {
            columns = findObsValueColumnName(c);
            if (columns.size() > 1) {
                conditional = true;
            }
            continue;
            //log.debug("c: " + c.getConceptId() + " attribute: " + attribute);
        } else if ("valueDate".equals(attribute)) {
            // pass -- same column name
        } else if ("valueTime".equals(attribute)) {
            // pass -- same column name
        } else if ("valueDatetime".equals(attribute)) {
            // pass -- same column name
        } else if ("obsDatetime".equals(attribute)) {
            // pass -- same column name
        } else if ("location".equals(attribute)) {
            // pass -- same column name
            classNames.add("obs.location");
            attribute = "location.name";
        } else if ("comment".equals(attribute)) {
            // pass -- same column name
        } else if ("encouterType".equals(attribute)) {
            classNames.add("obs.encounter");
            classNames.add("encounter.encounterType");
            attribute = "encounterType.name";
        } else if ("provider".equals(attribute)) {
            classNames.add("obs.encounter");
            attribute = "encounter.provider";
        } else {
            throw new DAOException("Attribute: " + attribute + " is not recognized. Please add reference in "
                    + this.getClass());
        }

        for (String className : classNames) { // if aliasing is necessary
            if (!aliases.contains(className)) { // if we haven't aliased this already
                criteria.createAlias(className, className.split("\\.")[1]);
                aliases.add(className);
            }
        }

        columns.add(attribute);
    }

    String aliasName = "obs";

    // set up the query
    ProjectionList projections = Projections.projectionList();
    projections.add(Projections.property("obs.personId"));
    for (String col : columns) {
        if (col.contains(".")) {
            projections.add(Projections.property(col));
        } else {
            projections.add(Projections.property(aliasName + "." + col));
        }
    }
    criteria.setProjection(projections);

    // only restrict on patient ids if some were passed in
    if (patients != null) {
        criteria.add(Restrictions.in("obs.personId", patients.getMemberIds()));
    }

    criteria.add(Restrictions.eq("obs.concept", c));
    criteria.add(Restrictions.eq("obs.voided", false));

    if (showMostRecentFirst) {
        criteria.addOrder(org.hibernate.criterion.Order.desc("obs.obsDatetime"));
    } else {
        criteria.addOrder(org.hibernate.criterion.Order.asc("obs.obsDatetime"));
    }

    long start = System.currentTimeMillis();
    List<Object[]> rows = criteria.list();
    log.debug("Took: " + (System.currentTimeMillis() - start) + " ms to run the patient/obs query");

    // set up the return map
    for (Object[] rowArray : rows) {
        //log.debug("row[0]: " + row[0] + " row[1]: " + row[1] + (row.length > 2 ? " row[2]: " + row[2] : ""));
        Integer ptId = (Integer) rowArray[0];

        List<List<Object>> oldArr = ret.get(ptId);

        // if we have already fetched all of the results the user wants 
        if (limit != null && limit > 0 && oldArr != null && oldArr.size() >= limit) {
            // the user provided a limit value and this patient already has more than
            // that number of values.
            // do nothing with this row
        } else {
            Boolean tmpConditional = conditional.booleanValue();

            // get all columns
            int index = 1;
            List<Object> row = new Vector<Object>();
            while (index < rowArray.length) {
                Object value = rowArray[index++];
                if (tmpConditional) {
                    if (index == 2 && value != null) {
                        // skip null first value if we must
                        row.add(value);
                    } else {
                        row.add(rowArray[index]);
                    }
                    tmpConditional = false;
                    index++; // increment counter for next column.  (Skips over value_concept)
                } else {
                    row.add(value == null ? "" : value);
                }
            }

            // if we haven't seen a different row for this patient already:
            if (oldArr == null) {
                List<List<Object>> arr = new Vector<List<Object>>();
                arr.add(row);
                ret.put(ptId, arr);
            }
            // if we have seen a row for this patient already
            else {
                oldArr.add(row);
                ret.put(ptId, oldArr);
            }
        }
    }

    return ret;

}

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

License:Mozilla Public License

@SuppressWarnings("unchecked")
public Map<Integer, Encounter> getEncountersByType(Cohort patients, List<EncounterType> encTypes) {
    Map<Integer, Encounter> ret = new HashMap<Integer, Encounter>();

    // default query
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Encounter.class);
    criteria.setCacheMode(CacheMode.IGNORE);

    // this "where clause" is only necessary if patients were passed in
    if (patients != null && patients.size() > 0) {
        criteria.add(Restrictions.in("patient.personId", patients.getMemberIds()));
    }/*from www.  j  av  a  2 s .  c  om*/

    criteria.add(Restrictions.eq("voided", false));

    if (encTypes != null && encTypes.size() > 0) {
        criteria.add(Restrictions.in("encounterType", encTypes));
    }

    criteria.addOrder(org.hibernate.criterion.Order.desc("patient.personId"));
    criteria.addOrder(org.hibernate.criterion.Order.desc("encounterDatetime"));

    List<Encounter> encounters = criteria.list();

    // set up the return map
    for (Encounter enc : encounters) {
        Integer ptId = enc.getPatientId();
        if (!ret.containsKey(ptId)) {
            ret.put(ptId, enc);
        }
    }

    return ret;
}

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

License:Mozilla Public License

/**
 * Gets a list of encounters associated with the given form, filtered by the given patient set.
 * /*from  w  w  w .  j av  a 2s.c  om*/
 * @param patients the patients to filter by (null will return all encounters for all patients)
 * @param forms the forms to filter by
 */
@SuppressWarnings("unchecked")
public List<Encounter> getEncountersByForm(Cohort patients, List<Form> forms) {

    // default query
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Encounter.class);
    criteria.setCacheMode(CacheMode.IGNORE);

    // this "where clause" is only necessary if patients were passed in
    if (patients != null && patients.size() > 0) {
        criteria.add(Restrictions.in("patient.personId", patients.getMemberIds()));
    }

    criteria.add(Restrictions.eq("voided", false));

    if (forms != null && forms.size() > 0) {
        criteria.add(Restrictions.in("form", forms));
    }

    criteria.addOrder(org.hibernate.criterion.Order.desc("patient.personId"));
    criteria.addOrder(org.hibernate.criterion.Order.desc("encounterDatetime"));

    return criteria.list();

}

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

License:Mozilla Public License

@SuppressWarnings("unchecked")
public Map<Integer, Object> getEncounterAttrsByType(Cohort patients, List<EncounterType> encTypes, String attr,
        Boolean earliestFirst) {//  w ww  .  j a va  2s .  c  om
    Map<Integer, Object> ret = new HashMap<Integer, Object>();

    // default query
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Encounter.class);
    criteria.setCacheMode(CacheMode.IGNORE);

    // this "where clause" is only necessary if patients were specified
    if (patients != null) {
        criteria.add(Restrictions.in("patient.personId", patients.getMemberIds()));
    }

    criteria.add(Restrictions.eq("voided", false));

    if (encTypes != null && encTypes.size() > 0) {
        criteria.add(Restrictions.in("encounterType", encTypes));
    }

    criteria.setProjection(Projections.projectionList().add(Projections.property("patient.personId"))
            .add(Projections.property(attr)));

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

    if (earliestFirst) {
        criteria.addOrder(org.hibernate.criterion.Order.asc("encounterDatetime"));
    } else {
        criteria.addOrder(org.hibernate.criterion.Order.desc("encounterDatetime"));
    }

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

    // set up the return map
    for (Object[] row : attrs) {
        Integer ptId = (Integer) row[0];
        if (!ret.containsKey(ptId)) {
            ret.put(ptId, row[1]);
        }
    }

    return ret;
}

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

License:Mozilla Public License

@SuppressWarnings("unchecked")
public Map<Integer, Encounter> getEncounters(Cohort patients) {
    Map<Integer, Encounter> ret = new HashMap<Integer, Encounter>();

    // default query
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Encounter.class);
    criteria.setCacheMode(CacheMode.IGNORE);

    // only include this where clause if patients were passed in
    if (patients != null) {
        criteria.add(Restrictions.in("patient.personId", patients.getMemberIds()));
    }//  w  ww.ja  v  a 2  s.c o  m

    criteria.add(Restrictions.eq("voided", false));

    criteria.addOrder(org.hibernate.criterion.Order.desc("patient.personId"));
    criteria.addOrder(org.hibernate.criterion.Order.desc("encounterDatetime"));

    List<Encounter> encounters = criteria.list();

    // set up the return map
    for (Encounter enc : encounters) {
        Integer ptId = enc.getPatientId();
        if (!ret.containsKey(ptId)) {
            ret.put(ptId, enc);
        }
    }

    return ret;
}