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:ca.ualberta.physics.cssdp.catalogue.dao.UrlDataProductDao.java

License:Apache License

public void process(UrlDataProductUpdateMap urlDataProductUpdateMap) {

    if (urlDataProductUpdateMap.getUrls().size() == 0) {
        return;//w ww.  j  a v  a  2 s.c om
    }

    /*
     * The size of scannedUrlDataProducts should be <= jdbc batch size
     * configured.
     */

    // we have to resort to hibernate directly because JPA does not have
    // scrolling capability
    Session session = emp.get().unwrap(Session.class).getSessionFactory().openSession();

    Transaction tx = session.beginTransaction();

    // "in" clause limit is 2^16 on Postgresql, it might be different on
    // other dbs
    String hqlString = "from UrlDataProduct urldp where urldp.url in (:urls)";

    // the fastest way to scroll through the existing data
    Query q = session.createQuery(hqlString);
    q.setParameterList("urls", urlDataProductUpdateMap.getUrls());
    q.setCacheMode(CacheMode.IGNORE);
    ScrollableResults existingData = q.scroll(ScrollMode.FORWARD_ONLY);

    while (existingData.next()) {

        UrlDataProduct existing = (UrlDataProduct) existingData.get(0);
        UrlDataProduct updated = urlDataProductUpdateMap.get(existing.getUrl());

        if (updated != null) {

            /*
             * Only bother to update the record if it's actually changed.
             * Note that the scan timestamp is ignored in the check because
             * that isn't something the provider changed. A change can also
             * mean the url was deleted, and now it's back.
             */
            if (existing.hasChanged(updated)) {
                // existing.setDataProduct(updated.getDataProduct());
                existing.setUrl(updated.getUrl());
                existing.setStartTimestamp(updated.getStartTimestamp());
                existing.setEndTimestamp(updated.getEndTimestamp());
                existing.setScanTimestamp(updated.getScanTimestamp());
                existing.setDeleted(false);
                urlDataProductUpdateMap.remove(updated.getUrl());
                session.update(existing);
            } else {
                // remove it so it's not duplicated
                urlDataProductUpdateMap.remove(existing.getUrl());
            }

        } else {

            // if we get here it means the existing url has been removed
            // from the server, set "delete" it from the catalogue
            existing.setDeleted(true);
            existing.setScanTimestamp(new LocalDateTime());

        }

    }

    // persist the new url mappings
    for (String newUrl : urlDataProductUpdateMap.getUrls()) {
        UrlDataProduct newUrlDataProduct = urlDataProductUpdateMap.get(newUrl);
        session.save(newUrlDataProduct);
        logger.debug("saved a mapping: " + newUrlDataProduct.getUrl());
    }

    session.flush();
    session.clear();

    tx.commit();
    session.close();

}

From source file:com.bluexml.side.Framework.alfresco.jbpm.CustomJBPMEngine.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  v  a2  s  .  c  o  m

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

From source file:com.bluexml.side.Framework.alfresco.jbpm.CustomJBPMEngine.java

License:Open Source License

@SuppressWarnings({ "unchecked", "cast" })
private void cacheTasksNoBatch(Session session, List<Long> taskInstanceIds, Map<Long, TaskInstance> returnMap) {
    Query query = session.getNamedQuery("org.alfresco.repo.workflow.cacheTaskInstanceProperties");
    query.setParameterList("ids", taskInstanceIds);
    query.setCacheMode(CacheMode.PUT);
    query.setFlushMode(FlushMode.MANUAL);
    query.setCacheable(true);/*  w w  w  .ja  va  2s . c o m*/

    List<TaskInstance> results = (List<TaskInstance>) query.list();
    for (TaskInstance taskInstance : results) {
        returnMap.put(taskInstance.getId(), taskInstance);
    }
}

From source file:com.ejushang.steward.common.genericdao.search.hibernate.HibernateSearchProcessor.java

License:Apache License

/**
 * ??//w w w .  ja  v a  2  s.co  m
 * @param query
 * @param search
 */
private void setQueryCache(Query query, ISearch search) {
    if (search.isCacheable()) {
        query.setCacheable(true);
    }
    if (search.getCacheMode() != null) {
        query.setCacheMode(search.getCacheMode());
    }

}

From source file:com.googlecode.osde.internal.shindig.AppDataService.java

License:Apache License

public Map<String, String> getApplicationDataMap(Person person, ApplicationImpl application) {
    Query query = session.createQuery(
            "select a from ApplicationDataMapImpl a where a.person = :person and a.application = :application");
    query.setCacheMode(CacheMode.GET);
    query.setParameter("person", person);
    query.setParameter("application", application);
    ApplicationDataMapImpl applicationDataMap = (ApplicationDataMapImpl) query.uniqueResult();
    if (applicationDataMap != null) {
        Map<String, String> result = new HashMap<String, String>();
        result.putAll(applicationDataMap.getDataMap());
        session.evict(applicationDataMap);
        return result;
    } else {/*from   w  w  w. j a  va 2s .com*/
        return null;
    }
}

From source file:com.googlecode.osde.internal.shindig.AppDataService.java

License:Apache License

public void removeApplicationData(Person person, ApplicationImpl application, String key) {
    Transaction tx = session.beginTransaction();
    Query query = session.createQuery(
            "select a from ApplicationDataMapImpl a where a.person = :person and a.application = :application");
    query.setCacheMode(CacheMode.GET);
    query.setParameter("person", person);
    query.setParameter("application", application);
    ApplicationDataMapImpl applicationDataMap = (ApplicationDataMapImpl) query.uniqueResult();
    if (applicationDataMap != null) {
        Map<String, String> dataMap = applicationDataMap.getDataMap();
        dataMap.remove(key);/*from  www. j a v a 2  s.  c  o  m*/
        session.update(applicationDataMap);
    }
    tx.commit();
}

From source file:com.googlecode.osde.internal.shindig.AppDataService.java

License:Apache License

public void addApplicationData(Person person, ApplicationImpl application, String key, String value) {
    Transaction tx = session.beginTransaction();
    Query query = session.createQuery(
            "select a from ApplicationDataMapImpl a where a.person = :person and a.application = :application");
    query.setCacheMode(CacheMode.GET);
    query.setParameter("person", person);
    query.setParameter("application", application);
    ApplicationDataMapImpl applicationDataMap = (ApplicationDataMapImpl) query.uniqueResult();
    if (applicationDataMap == null) {
        applicationDataMap = new ApplicationDataMapImpl();
        applicationDataMap.setPerson(person);
        applicationDataMap.setApplication(application);
    }//from  w w  w. j a v a2  s  .  c  o m
    Map<String, String> dataMap = applicationDataMap.getDataMap();
    dataMap.put(key, value);
    session.saveOrUpdate(applicationDataMap);
    tx.commit();
}

From source file:com.heimaide.server.common.persistence.BaseDao.java

License:Open Source License

public <E> Page<E> queryBySqlFromDB(Page<E> page, String sqlString, Class<?> resultClass, List param) {
    // get count/*from  w w w  .  j a v a 2 s . c o m*/
    if (!page.isDisabled() && !page.isNotCount()) {
        String countSqlString = "select count(*) from ( " + sqlString + ") k";// ?????
        // page.setCount(Long.valueOf(createSqlQuery(countSqlString,
        // parameter).uniqueResult().toString()));
        Query query = createSqlQuery(countSqlString, param);
        query.setCacheMode(CacheMode.REFRESH);
        List<Object> list = query.list();
        if (list.size() > 0) {
            page.setCount(Long.valueOf(list.get(0).toString()));
        } else {
            page.setCount(list.size());
        }
        if (page.getCount() < 1) {
            return page;
        }
    }
    // order by
    String sql = sqlString;
    if (StringUtils.isNotBlank(page.getOrderBy())) {
        sql += " order by " + page.getOrderBy();
    }
    SQLQuery query = createSqlQuery(sql, param);
    query.setCacheMode(CacheMode.REFRESH);
    // set page
    if (!page.isDisabled()) {
        query.setFirstResult(page.getFirstResult());
        query.setMaxResults(page.getMaxResults());
    }
    /*
     * Field[] fields = resultClass.getFields(); for (Field f : fields) {
    * query.addScalar(f.getName());// }
    */
    query.setResultTransformer(Transformers.aliasToBean(resultClass));
    page.setList(query.list());
    return page;
}

From source file:com.oracle.coherence.hibernate.cachestore.HibernateCacheLoader.java

License:CDDL license

/**
 * Load a collection of Hibernate entities given a set of ids (keys)
 *
 * @param keys  the cache keys; specifically, the entity ids
 *
 * @return      the corresponding Hibernate entity instances
 *///from   w ww  . j a  va 2  s .  c  o  m
public Map loadAll(Collection keys) {
    ensureInitialized();

    Map results = new HashMap();

    Transaction tx = null;

    Session session = openSession();
    SessionImplementor sessionImplementor = (SessionImplementor) session;

    try {
        tx = session.beginTransaction();

        // Create the query
        String sQuery = getLoadAllQuery();
        Query query = session.createQuery(sQuery);

        // Prevent Hibernate from caching the results
        query.setCacheMode(CacheMode.IGNORE);
        query.setCacheable(false);
        query.setReadOnly(true);

        // Parameterize the query (where :keys = keys)
        query.setParameterList(PARAM_IDS, keys);

        // Need a way to extract the key from an entity that we know
        // nothing about.
        ClassMetadata classMetaData = getEntityClassMetadata();

        // Iterate through the results and place into the return map
        for (Iterator iter = query.list().iterator(); iter.hasNext();) {
            Object entity = iter.next();
            Object id = classMetaData.getIdentifier(entity, sessionImplementor);
            results.put(id, entity);
        }

        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.rollback();
        }

        throw ensureRuntimeException(e);
    } finally {
        closeSession(session);
    }

    return results;
}

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

License:Apache License

private void initList() {
    logger.debug("initList()");
    // Header/*w ww .j av  a2 s.co m*/
    List<GenericListHeaderType> header = new LinkedList<GenericListHeaderType>();
    header.add(new GenericListHeaderType("ID", 90, "", true, "String", true, true, false, false));
    header.add(new GenericListHeaderType("Name vorwrts", 250, "", true, "String", true, true, false, false));
    header.add(
            new GenericListHeaderType("Name rckwrts", 250, "", true, "String", true, true, false, false));
    header.add(new GenericListHeaderType("Codesystem", 350, "", true, "String", true, true, false, false));

    //CacheManager.getInstance().clearAll();
    //clearHibernateCache();
    // Daten laden
    //SessionFactory sf = HibernateUtil.getSessionFactory();
    SessionFactory sf = HibernateUtil.getNewSessionFactory();

    //sf.evictQueries();
    //sf.getCurrentSession().clear();
    /*Cache cache = sf.getCache();
            
    cache.evictEntityRegions();
    cache.evictCollectionRegions();
    cache.evictDefaultQueryRegion();
    cache.evictQueryRegions();
    //cache.evictNaturalIdRegions();
    //cache.evictAllRegions();
            
    cache.evictAllRegions(); // Evict data from all query regions.*/

    Session hb_session = sf.openSession();

    //hb_session.getTransaction().begin();

    List<GenericListRowType> dataList = new LinkedList<GenericListRowType>();
    try {
        String hql = "select distinct at from AssociationType at"
                + " join fetch at.codeSystemEntityVersion csev" + " join csev.codeSystemEntity cse"
                + " left join cse.codeSystemVersionEntityMemberships csvem";
        //+ " left join fetch csvem.codeSystemVersion csv"
        //+ " left join fetch csv.codeSystem";

        Query q = hb_session.createQuery(hql);
        q.setCacheable(false);
        q.setCacheMode(CacheMode.IGNORE);
        //q.setHint("toplink.refresh", "true");

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

        List<de.fhdo.terminologie.db.hibernate.AssociationType> list = q.list();

        logger.debug("Anzahl: " + list.size());

        for (int i = 0; i < list.size(); ++i) {
            de.fhdo.terminologie.db.hibernate.AssociationType association = list.get(i);
            GenericListRowType row = createRowFromAssociation(association);

            dataList.add(row);
        }
    } catch (Exception e) {
        LoggingOutput.outputException(e, this);
    } finally {
        hb_session.close();
    }

    // Liste initialisieren
    Include inc = (Include) getFellow("incList");
    Window winGenericList = (Window) inc.getFellow("winGenericList");
    genericList = (GenericList) winGenericList;

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