Example usage for org.hibernate Query setCacheRegion

List of usage examples for org.hibernate Query setCacheRegion

Introduction

In this page you can find the example usage for org.hibernate Query setCacheRegion.

Prototype

Query<R> setCacheRegion(String cacheRegion);

Source Link

Document

Set the name of the cache region where query results should be cached (if cached at all).

Usage

From source file:com.liusoft.dlog4j.dao.TagDAO.java

License:Open Source License

/**
 * //www.j av  a2 s.c om
 * 
 * @param site
 * @param fromIdx
 * @param count
 * @return
 */
public static List listTags(SiteBean site, int fromIdx, int count) {
    StringBuffer hql = new StringBuffer("SELECT t.name,COUNT(*) FROM TagBean t");
    if (site != null)
        hql.append(" WHERE t.site.id = ?");
    hql.append(" GROUP BY t.name ORDER BY 2 DESC");
    Query query = getSession().createQuery(hql.toString());
    query.setCacheable(true);
    query.setCacheRegion(CACHE_KEY);
    if (site != null)
        query.setInteger(0, site.getId());
    if (fromIdx > 0)
        query.setFirstResult(fromIdx);
    if (count > 0)
        query.setMaxResults(count);
    List<String> tags = new ArrayList<String>();
    List results = query.list();
    for (int i = 0; results != null && i < results.size(); i++) {
        tags.add((String) ((Object[]) results.get(i))[0]);
    }
    return tags;
}

From source file:com.mg.framework.support.orm.OrmTemplateHibernateImpl.java

License:Open Source License

@Override
protected void prepareQuery(Query queryObject) {
    if (isCacheQueries()) {
        queryObject.setCacheable(true);/*from  w ww .ja v  a  2s .com*/
        if (getQueryCacheRegion() != null) {
            queryObject.setCacheRegion(getQueryCacheRegion());
        }
    }
    if (getFetchSize() > 0) {
        queryObject.setFetchSize(getFetchSize());
    }
    if (getMaxResults() > 0) {
        queryObject.setMaxResults(getMaxResults());
    }
    if (getFlushMode() != null) {
        queryObject.setFlushMode(CriteriaHibernateImpl.convertFlushModeToHibernate(getFlushMode()));
    }
    //SessionFactoryUtils.applyTransactionTimeout(queryObject, getSessionFactory());
}

From source file:com.mysema.query.jpa.hibernate.AbstractHibernateQuery.java

License:Apache License

private Query createQuery(String queryString, @Nullable QueryModifiers modifiers, boolean forCount) {
    Query query = session.createQuery(queryString);
    HibernateUtil.setConstants(query, getConstants(), getMetadata().getParams());
    if (fetchSize > 0) {
        query.setFetchSize(fetchSize);// ww w. j  a v a  2s . c o m
    }
    if (timeout > 0) {
        query.setTimeout(timeout);
    }
    if (cacheable != null) {
        query.setCacheable(cacheable);
    }
    if (cacheRegion != null) {
        query.setCacheRegion(cacheRegion);
    }
    if (comment != null) {
        query.setComment(comment);
    }
    if (readOnly != null) {
        query.setReadOnly(readOnly);
    }
    for (Map.Entry<Path<?>, LockMode> entry : lockModes.entrySet()) {
        query.setLockMode(entry.getKey().toString(), entry.getValue());
    }
    if (flushMode != null) {
        query.setFlushMode(flushMode);
    }

    if (modifiers != null && modifiers.isRestricting()) {
        if (modifiers.getLimit() != null) {
            query.setMaxResults(modifiers.getLimit().intValue());
        }
        if (modifiers.getOffset() != null) {
            query.setFirstResult(modifiers.getOffset().intValue());
        }
    }

    // set transformer, if necessary
    List<? extends Expression<?>> projection = getMetadata().getProjection();
    if (projection.size() == 1 && !forCount) {
        Expression<?> expr = projection.get(0);
        if (expr instanceof FactoryExpression<?>) {
            query.setResultTransformer(
                    new FactoryExpressionTransformer((FactoryExpression<?>) projection.get(0)));
        }
    } else if (!forCount) {
        FactoryExpression<?> proj = FactoryExpressionUtils.wrap(projection);
        if (proj != null) {
            query.setResultTransformer(new FactoryExpressionTransformer(proj));
        }
    }
    return query;
}

From source file:com.openkm.dao.NodeBaseDAO.java

License:Open Source License

/**
 * Get parent node permissions/*  w  ww .j  ava2 s .c  o m*/
 */
@SuppressWarnings("unchecked")
public NodeBase getParentNodePermissions(Session session, String uuid) throws HibernateException {
    log.debug("getParentNodePermissions({}, {})", session, uuid);
    String qs = "select nb1.uuid, index(userPermissions), userPermissions, index(rolePermissions), rolePermissions "
            + "from NodeBase nb1 join nb1.userPermissions userPermissions join nb1.rolePermissions rolePermissions "
            + "where nb1.uuid = (select nb2.parent from NodeBase nb2 where nb2.uuid=:uuid)";
    Query q = session.createQuery(qs).setCacheable(true);
    q.setCacheRegion(CACHE_PARENT_NODE_PERMISSIONS);
    q.setString("uuid", uuid);
    List<Object[]> perms = (List<Object[]>) q.list();
    NodeBase nBase = null;

    if (!perms.isEmpty()) {
        nBase = new NodeBase();

        for (Object[] tupla : (List<Object[]>) q.list()) {
            if (nBase.getUuid() == null) {
                nBase.setUuid((String) tupla[0]);
            }

            if (!nBase.getUserPermissions().containsKey((String) tupla[1])) {
                nBase.getUserPermissions().put((String) tupla[1], (Integer) tupla[2]);
            }

            if (!nBase.getRolePermissions().containsKey((String) tupla[3])) {
                nBase.getRolePermissions().put((String) tupla[3], (Integer) tupla[4]);
            }
        }
    }

    log.debug("getParentNodePermissions: {}", nBase);
    return nBase;
}

From source file:com.querydsl.jpa.hibernate.AbstractHibernateQuery.java

License:Apache License

private Query createQuery(@Nullable QueryModifiers modifiers, boolean forCount) {
    JPQLSerializer serializer = serialize(forCount);
    String queryString = serializer.toString();
    logQuery(queryString, serializer.getConstantToLabel());
    Query query = session.createQuery(queryString);
    HibernateUtil.setConstants(query, serializer.getConstantToLabel(), getMetadata().getParams());
    if (fetchSize > 0) {
        query.setFetchSize(fetchSize);/*from   w  w  w.j  a v a 2 s .  c o m*/
    }
    if (timeout > 0) {
        query.setTimeout(timeout);
    }
    if (cacheable != null) {
        query.setCacheable(cacheable);
    }
    if (cacheRegion != null) {
        query.setCacheRegion(cacheRegion);
    }
    if (comment != null) {
        query.setComment(comment);
    }
    if (readOnly != null) {
        query.setReadOnly(readOnly);
    }
    for (Map.Entry<Path<?>, LockMode> entry : lockModes.entrySet()) {
        query.setLockMode(entry.getKey().toString(), entry.getValue());
    }
    if (flushMode != null) {
        query.setFlushMode(flushMode);
    }

    if (modifiers != null && modifiers.isRestricting()) {
        Integer limit = modifiers.getLimitAsInteger();
        Integer offset = modifiers.getOffsetAsInteger();
        if (limit != null) {
            query.setMaxResults(limit);
        }
        if (offset != null) {
            query.setFirstResult(offset);
        }
    }

    // set transformer, if necessary
    Expression<?> projection = getMetadata().getProjection();
    if (!forCount && projection instanceof FactoryExpression) {
        query.setResultTransformer(new FactoryExpressionTransformer((FactoryExpression<?>) projection));
    }
    return query;
}

From source file:com.tracer.dao.persistence.impl.BaseDAOHibernate.java

License:Apache License

/**
 * Executes find using <code>org.springframework.orm.hibernate3.HibernateCallback</code>
  * with additional query info; with arguments and their types
 *
 * @param hql         Query to execute/*from   w w  w.ja  va2 s .c o  m*/
 * @param queryInfo   Object with additional information for query, currently offset and limit
 * @param args        Arguments to add to query. If <code>null</code>, nothing will be added.
 * @param types       Types of arguments. If <code>null</code>, Hibernate will determine types by itself.
 * @param cacheable   <code>true</code> if the query is cacheable
 * @param cacheRegion region of cache. E.g. one that used in configuration file of EHCahce (ehcache.xml)
 * @return List of found entities
 * @see org.springframework.orm.hibernate3.HibernateCallback
  * @see com.blandware.atleap.common.util.QueryInfo
 */
@SuppressWarnings("rawtypes")
protected List executeFind(final String hql, final QueryInfo queryInfo, final Object[] args, final Type[] types,
        final boolean cacheable, final String cacheRegion) {
    return getHibernateTemplate().executeFind(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            Query query = session.createQuery(hql);
            query.setCacheable(cacheable);
            if (cacheRegion != null) {
                query.setCacheRegion(cacheRegion);
            }
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    Object arg = args[i];
                    Type type = null;
                    if (types != null && i < types.length) {
                        type = types[i];
                    }
                    if (type == null) {
                        query.setParameter(i, arg);
                    } else {
                        query.setParameter(i, arg, type);
                    }
                }
            }
            if (queryInfo != null) {
                if (queryInfo.getLimit() != null) {
                    query.setMaxResults(queryInfo.getLimit().intValue());
                }
                if (queryInfo.getOffset() != null) {
                    query.setFirstResult(queryInfo.getOffset().intValue());
                }
            }
            return query.list();
        }
    });
}

From source file:com.tracer.dao.persistence.impl.BaseDAOHibernate.java

License:Apache License

/**
 * Returns unique result matching specified query using <code>org.springframework.orm.hibernate3.HibernateCallback</code>
  * with arguments and their types/* w  w  w .  jav a 2 s  . c  om*/
 *
 * @param hql         Query to execute
 * @param args        Arguments to set
 * @param types       Types of arguments
 * @param cacheable   <code>true</code> if the query is cacheable
 * @param cacheRegion region of cache. E.g. one that used in configuration file of EHCahce (ehcache.xml)
 * @return Unique result matching specified query
 */
public Object findUniqueResult(final String hql, final Object[] args, final Type[] types,
        final boolean cacheable, final String cacheRegion) {
    return getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
            Query query = session.createQuery(hql);
            query.setCacheable(cacheable);
            if (cacheRegion != null) {
                query.setCacheRegion(cacheRegion);
            }
            if (args != null) {
                for (int i = 0; i < args.length; i++) {
                    Object arg = args[i];
                    Type type = null;
                    if (types != null && i < types.length) {
                        type = types[i];
                    }
                    if (type == null) {
                        query.setParameter(i, arg);
                    } else {
                        query.setParameter(i, arg, type);
                    }
                }
            }
            return query.uniqueResult();
        }
    });
}

From source file:gov.nih.nci.firebird.service.lookup.StateLookupServiceBean.java

License:Open Source License

@Override
@SuppressWarnings("unchecked") // Query.list() method returns generic List
public List<State> getAll() {
    Query query = getSession().createQuery("from " + State.class.getName() + " order by name");
    query.setCacheRegion("org.hibernate.cache.StateQueryCache");
    return query.list();
}

From source file:nl.strohalm.cyclos.dao.BaseDAOImpl.java

License:Open Source License

private void process(final Query query, final Object namedParameters) {
    hibernateQueryHandler.setQueryParameters(query, namedParameters);
    if (queryCacheRegion != null) {
        query.setCacheable(true);/*from w w  w  . j  a v  a2  s.  c o  m*/
        query.setCacheRegion(queryCacheRegion);
    }
}

From source file:nl.strohalm.cyclos.utils.hibernate.HibernateQueryHandler.java

License:Open Source License

/**
 * List the query with hibernate//from  w w w .j a  v  a  2 s .co m
 */
@SuppressWarnings("unchecked")
public <E> List<E> simpleList(final String cacheRegion, final String hql, final Object namedParameters,
        final PageParameters pageParameters, final Relationship... fetch) {
    final List<E> list = getHibernateTemplate().execute(new HibernateCallback<List<E>>() {
        //@Override
        public List<E> doInHibernate(final Session session) throws HibernateException {
            final Query query = session.createQuery(hql);
            setQueryParameters(query, namedParameters);
            applyPageParameters(pageParameters, query);
            if (cacheRegion != null) {
                query.setCacheable(true);
                query.setCacheRegion(cacheRegion);
            }
            return query.list();
        }
    });
    if (fetch != null && fetch.length > 0) {
        for (int i = 0; i < list.size(); i++) {
            final Entity entity = (Entity) list.get(i);
            list.set(i, (E) fetchDao.fetch(entity, fetch));
        }
    }
    return list;
}