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:de.fhdo.gui.admin.modules.terminology.Codesystems.java

License:Apache License

private void initList() {
    logger.debug("initList()");

    try {//from w w w.  j  a  v  a2 s.  c  o  m
        West title = (West) getFellow("titleItem");
        int selectedIndex = -1;

        // header information for list view
        List<GenericListHeaderType> header = new LinkedList<GenericListHeaderType>();
        header.add(new GenericListHeaderType("ID", 60, "", true, "String", true, true, false, false));
        header.add(new GenericListHeaderType(Labels.getLabel("name"), 0, "", true, "String", true, true, false,
                false));

        // load data from db
        SessionFactory sf = HibernateUtil.getNewSessionFactory();
        Session hb_session = sf.openSession();
        //Session hb_session = HibernateUtil.getSessionFactory().openSession();

        List<GenericListRowType> dataList = new LinkedList<GenericListRowType>();
        try {
            if (mode == Mode.VALUESET) {
                ValueSet selectedVS = null;

                if (selectedItem instanceof ValueSet)
                    selectedVS = (ValueSet) selectedItem;

                String hql = "from ValueSet order by name";

                Query q = hb_session.createQuery(hql);
                q.setCacheable(false);
                q.setCacheMode(CacheMode.IGNORE);

                hb_session.setCacheMode(CacheMode.IGNORE);
                hb_session.clear();
                hb_session.flush();

                logger.debug("hql: " + hql);

                List<ValueSet> vsList = q.list();

                for (int i = 0; i < vsList.size(); ++i) {
                    ValueSet vs = vsList.get(i);
                    GenericListRowType row = createRowFromValueSet(vs);

                    dataList.add(row);

                    if (selectedVS != null) {
                        if (vs.getId().longValue() == selectedVS.getId())
                            selectedIndex = i;
                    }
                }

                // set title
                title.setTitle(Labels.getLabel("valuesets"));
            } else {
                CodeSystem selectedCS = null;

                if (selectedItem instanceof CodeSystem)
                    selectedCS = (CodeSystem) selectedItem;

                String hql = "from CodeSystem order by name";
                Query q = hb_session.createQuery(hql);
                q.setCacheable(false);
                q.setCacheMode(CacheMode.IGNORE);

                hb_session.setCacheMode(CacheMode.IGNORE);
                hb_session.clear();
                hb_session.flush();

                logger.debug("hql: " + hql);
                List<CodeSystem> csList = q.list();

                for (int i = 0; i < csList.size(); ++i) {
                    CodeSystem cs = csList.get(i);
                    GenericListRowType row = createRowFromCodesystem(cs);

                    dataList.add(row);

                    if (selectedCS != null) {
                        if (cs.getId().longValue() == selectedCS.getId())
                            selectedIndex = i;
                    }
                }

                // set title
                title.setTitle(Labels.getLabel("codesystems"));
            }
        } catch (Exception e) {
            LoggingOutput.outputException(e, this);
        } finally {
            hb_session.close();
        }

        // initialize list
        Include inc = (Include) getFellow("incList");
        Window winGenericList = (Window) inc.getFellow("winGenericList");
        genericList = (GenericList) winGenericList;
        genericList.setListId("list");

        genericList.setListActions(this);
        genericList.setButton_new(true);
        genericList.setButton_edit(false);
        genericList.setButton_delete(true);
        genericList.setListHeader(header);
        genericList.setDataList(dataList);

        if (selectedIndex >= 0)
            genericList.setSelectedIndex(selectedIndex);
    } catch (Exception ex) {
        LoggingOutput.outputException(ex, this);
    }

    initListVersion();
}

From source file:de.fhdo.gui.admin.modules.terminology.Codesystems.java

License:Apache License

private void initListVersion() {
    logger.debug("initListVersion()");

    logger.debug("selectedItem: " + selectedItem);

    Include incVersions = (Include) getFellow("incListVersions");
    West title = (West) getFellow("titleVersion");

    if (selectedItem == null) {
        logger.debug("show empty message");
        if (mode == Mode.VALUESET)
            title.setTitle(Labels.getLabel("valuesetVersion"));
        else//w  w w .j a v  a2 s  .c o  m
            title.setTitle(Labels.getLabel("codesystemVersion"));

        incVersions.setSrc(null);
        incVersions.setSrc("/gui/templates/MessageInclude.zul?msg=" + Labels.getLabel("noSelection"));
    } else {
        logger.debug("show version list");

        int selectedIndex = -1;

        incVersions.setSrc(null);
        incVersions.setSrc("/gui/templates/GenericList.zul");

        try {
            // header information for list view
            List<GenericListHeaderType> header = new LinkedList<GenericListHeaderType>();
            header.add(new GenericListHeaderType("ID", 60, "", true, "String", true, true, false, false));
            header.add(new GenericListHeaderType(Labels.getLabel("name"), 0, "", true, "String", true, true,
                    false, false));
            header.add(new GenericListHeaderType(Labels.getLabel("status"), 80, "", true, "String", true, true,
                    false, false));

            // load data from db
            Session hb_session = HibernateUtil.getSessionFactory().openSession();
            hb_session.setCacheMode(org.hibernate.CacheMode.IGNORE);
            hb_session.clear();

            List<GenericListRowType> dataList = new LinkedList<GenericListRowType>();
            try {
                if (mode == Mode.VALUESET) {
                    // fill version list with value set versions
                    ValueSet selectedVS = (ValueSet) selectedItem;
                    ValueSetVersion selectedVSV = (ValueSetVersion) selectedItemVersion;

                    String hql = "from ValueSetVersion where valueSetId=:vs_id order by name";
                    Query q = hb_session.createQuery(hql);
                    q.setParameter("vs_id", selectedVS.getId());

                    q.setCacheable(false);
                    q.setCacheMode(CacheMode.IGNORE);

                    hb_session.setCacheMode(CacheMode.IGNORE);
                    hb_session.clear();
                    hb_session.flush();

                    List<ValueSetVersion> vsList = q.list();

                    for (int i = 0; i < vsList.size(); ++i) {
                        ValueSetVersion vsv = vsList.get(i);
                        GenericListRowType row = createRowFromValueSetVersion(vsv);

                        dataList.add(row);

                        if (selectedVSV != null) {
                            if (vsv.getVersionId().longValue() == selectedVSV.getVersionId())
                                selectedIndex = i;
                        }
                    }

                    // set title
                    title.setTitle(Labels.getLabel("valuesetVersion") + " - " + selectedVS.getName());
                } else {
                    // fill version list with code system versions
                    CodeSystem selectedCS = (CodeSystem) selectedItem;
                    CodeSystemVersion selectedCSV = (CodeSystemVersion) selectedItemVersion;

                    String hql = "from CodeSystemVersion where codeSystemId=:cs_id order by name";
                    Query q = hb_session.createQuery(hql);
                    q.setParameter("cs_id", selectedCS.getId());

                    q.setCacheable(false);
                    q.setCacheMode(CacheMode.IGNORE);

                    hb_session.setCacheMode(CacheMode.IGNORE);
                    hb_session.clear();
                    hb_session.flush();

                    List<CodeSystemVersion> csList = q.list();

                    for (int i = 0; i < csList.size(); ++i) {
                        CodeSystemVersion csv = csList.get(i);
                        GenericListRowType row = createRowFromCodesystemVersion(csv);

                        dataList.add(row);

                        if (selectedCSV != null) {
                            if (csv.getVersionId().longValue() == selectedCSV.getVersionId())
                                selectedIndex = i;
                        }
                    }

                    // set title
                    title.setTitle(Labels.getLabel("codesystemVersion") + " - " + selectedCS.getName());
                }
            } catch (Exception e) {
                LoggingOutput.outputException(e, this);
            } finally {
                hb_session.close();
            }

            // initialize list
            Window winGenericList = (Window) incVersions.getFellow("winGenericList");
            genericListVersion = (GenericList) winGenericList;
            genericListVersion.setListId("listVersion");

            genericListVersion.setListActions(this);
            genericListVersion.setButton_new(true);
            genericListVersion.setButton_edit(false);
            genericListVersion.setButton_delete(true);
            genericListVersion.setListHeader(header);
            genericListVersion.setDataList(dataList);

            if (selectedIndex >= 0)
                genericListVersion.setSelectedIndex(selectedIndex);

            Button button = new Button(Labels.getLabel("changeStatus") + "...");
            button.addEventListener(Events.ON_CLICK, new EventListener<Event>() {
                public void onEvent(Event t) throws Exception {
                    changeStatus();
                }
            });

            genericListVersion.removeCustomButtons();
            genericListVersion.addCustomButton(button);
        } catch (Exception ex) {
            LoggingOutput.outputException(ex, this);
        }
    }

    initDetails();
}

From source file:magoffin.matt.dao.hbm.GenericHibernateDao.java

License:Open Source License

/**
 * Execute a batch callback using a named query.
 * //from ww  w  .  j  a v a 2s  .  co  m
 * @param queryName the named query name
 * @param parameters the named parameters to pass to the query
 * @param callback the callback
 * @return the number of items processed
 */
protected Integer executeNamedQueryBatchCallback(final String queryName, final Map<String, Object> parameters,
        final BatchCallback<T> callback) {
    return getHibernateTemplate().execute(new HibernateCallback<Integer>() {
        @SuppressWarnings("unchecked")
        @Override
        public Integer doInHibernate(Session session) throws HibernateException, SQLException {
            Query q = session.getNamedQuery(queryName);
            if (parameters != null) {
                for (String paramName : parameters.keySet()) {
                    q.setParameter(paramName, parameters.get(paramName));
                }
            }
            q.setCacheMode(CacheMode.IGNORE);
            ScrollableResults items = q.scroll(ScrollMode.FORWARD_ONLY);
            int count = 0;

            OUTER: while (items.next()) {
                T item = (T) items.get(0);
                BatchCallbackResult action = callback.handle(item);
                switch (action) {
                case DELETE:
                    session.delete(item);
                    break;

                case UPDATE:
                case UPDATE_STOP:
                    store(item);
                    if (action == BatchCallbackResult.UPDATE_STOP) {
                        break OUTER;
                    }
                    break;

                case STOP:
                    break OUTER;

                case CONTINUE:
                    // nothing to do
                    break;
                }
                if (++count % batchFlushCount == 0) {
                    session.flush();
                    session.clear();
                }
            }

            return count;
        }
    });
}

From source file:org.alfresco.repo.workflow.jbpm.JBPMEngine.java

License:Open Source License

@SuppressWarnings({ "unchecked", "cast" })
private void cacheVariablesNoBatch(Session session, List<Long> contextInstanceIds,
        Map<Long, TokenVariableMap> variablesCache) {
    Query query = session.getNamedQuery("org.alfresco.repo.workflow.cacheInstanceVariables");
    query.setParameterList("ids", contextInstanceIds);
    query.setCacheMode(CacheMode.PUT);
    query.setFlushMode(FlushMode.MANUAL);
    query.setCacheable(true);//from  w w w. j  a va 2 s.c o m

    List<TokenVariableMap> results = (List<TokenVariableMap>) query.list();
    for (TokenVariableMap tokenVariableMap : results) {
        variablesCache.put(tokenVariableMap.getToken().getId(), tokenVariableMap);
    }
}

From source file:org.devproof.portal.core.module.common.repository.DataProviderRepositoryImpl.java

License:Apache License

private void handleCacheConfiguration(Query q, CacheQuery cacheAnnotation) {
    q.setCacheable(cacheAnnotation.enabled());
    if (!"".equals(cacheAnnotation.region())) {
        q.setCacheMode(CacheMode.parse(cacheAnnotation.cacheMode()));
    }//from  w  w  w  .  j a va2  s  . c om
    if (!"".equals(cacheAnnotation.region())) {
        q.setCacheRegion(cacheAnnotation.region());
    }
}

From source file:org.glite.security.voms.admin.persistence.dao.VOMSUserDAO.java

License:Apache License

public ScrollableResults findAllWithCursor() {

    Query q = HibernateFactory.getSession().createQuery("select u from VOMSUser u order by u.surname asc");

    q.setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY);

    return q.scroll();

}

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

License:Mozilla Public License

/**
 * 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//w  w  w. j a va 2s.  com
 */
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.api.db.hibernate.HibernatePatientSetDAO.java

License:Mozilla Public 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");
    }/*from w w w . ja va  2s. com*/
    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);
    }
    Number numericValue = null;
    String stringValue = null;
    Concept codedValue = null;
    Date dateValue = 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 Concept) {
                codedValue = (Concept) value;
            } else {
                boolean asBoolean = false;
                if (value instanceof Boolean) {
                    asBoolean = ((Boolean) value).booleanValue();
                } else {
                    asBoolean = Boolean.valueOf(value.toString());
                }
                codedValue = asBoolean ? Context.getConceptService().getTrueConcept()
                        : Context.getConceptService().getFalseConcept();
            }
            valueSql = "o.value_coded";
        }
    }

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

License:Mozilla Public License

/**
 * within <code>startTime</code> and <code>endTime</code>
 * /*from ww w .  j  a va2  s .c  o m*/
 * @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.api.db.hibernate.HibernatePatientSetDAO.java

License:Mozilla Public 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  .j  a  v  a 2  s.c om

    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;
}