Java Code Examples for org.hibernate.Criteria#setCacheable()

The following examples show how to use org.hibernate.Criteria#setCacheable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HibernateTemplate.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Prepare the given Criteria object, applying cache settings and/or
 * a transaction timeout.
 * @param criteria the Criteria object to prepare
 * @see #setCacheQueries
 * @see #setQueryCacheRegion
 */
protected void prepareCriteria(Criteria criteria) {
	if (isCacheQueries()) {
		criteria.setCacheable(true);
		if (getQueryCacheRegion() != null) {
			criteria.setCacheRegion(getQueryCacheRegion());
		}
	}
	if (getFetchSize() > 0) {
		criteria.setFetchSize(getFetchSize());
	}
	if (getMaxResults() > 0) {
		criteria.setMaxResults(getMaxResults());
	}

	ResourceHolderSupport sessionHolder =
			(ResourceHolderSupport) TransactionSynchronizationManager.getResource(obtainSessionFactory());
	if (sessionHolder != null && sessionHolder.hasTimeout()) {
		criteria.setTimeout(sessionHolder.getTimeToLiveInSeconds());
	}
}
 
Example 2
Source File: HibernateTemplate.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Prepare the given Criteria object, applying cache settings and/or
 * a transaction timeout.
 * @param criteria the Criteria object to prepare
 * @see #setCacheQueries
 * @see #setQueryCacheRegion
 */
protected void prepareCriteria(Criteria criteria) {
	if (isCacheQueries()) {
		criteria.setCacheable(true);
		if (getQueryCacheRegion() != null) {
			criteria.setCacheRegion(getQueryCacheRegion());
		}
	}
	if (getFetchSize() > 0) {
		criteria.setFetchSize(getFetchSize());
	}
	if (getMaxResults() > 0) {
		criteria.setMaxResults(getMaxResults());
	}

	ResourceHolderSupport sessionHolder =
			(ResourceHolderSupport) TransactionSynchronizationManager.getResource(obtainSessionFactory());
	if (sessionHolder != null && sessionHolder.hasTimeout()) {
		criteria.setTimeout(sessionHolder.getTimeToLiveInSeconds());
	}
}
 
Example 3
Source File: MessageBundleServiceImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Transactional(readOnly = true)
public List<MessageBundleProperty> getAllProperties(String locale, String basename, String module) {

    Criteria query = sessionFactory.getCurrentSession().createCriteria(MessageBundleProperty.class);
    query.setCacheable(true);

    if (StringUtils.isNotEmpty(locale)) {
        query.add(Restrictions.eq("locale", locale));
    }
    if (StringUtils.isNotEmpty(basename)) {
        query.add(Restrictions.eq("baseName", basename));
    }
    if (StringUtils.isNotEmpty(module)) {
        query.add(Restrictions.eq("moduleName", module));
    }

    return (List<MessageBundleProperty>) query.list();
}
 
Example 4
Source File: HibernateDataOperation.java    From MiniWeChat-Server with MIT License 6 votes vote down vote up
/**
 * 重载query方法 增加Session参数 当需要使用延迟加载的时候 Session不能提前关闭
 * 
 * @param str
 * @param obj
 * @param cls
 * @param code
 * @param session
 * @return List
 * @author WangFei
 */
public static List query(String paramName, Object paramValue, Class outputClass, ResultCode resultCode, Session session) {
	logger.info("Hibernate:start query from database");
	logger.info("Hibernate:query parameters:" + paramName + " , " + paramValue.toString());
	try {
		Criteria criteria = session.createCriteria(outputClass);
		// 使用缓存
		criteria.setCacheable(true);
		criteria.add(Restrictions.eq(paramName, paramValue));
		List list = criteria.list();

		logger.info("Hibernate:query from database success");
		logger.info("Hibernate:query result list size:" + list.size());
		resultCode.setCode(ResultCode.SUCCESS);

		return list;
	} catch (Exception e) {
		e.printStackTrace();
		resultCode.setCode(ResultCode.FAIL);
		logger.error("Hibernate:query from database fail");
		logger.error("Hibernate error:" + e.getStackTrace());
		logger.error("Hibernate error:" + e.getMessage());
		return null;
	}
}
 
Example 5
Source File: HibernateTemplate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Prepare the given Criteria object, applying cache settings and/or
 * a transaction timeout.
 * @param criteria the Criteria object to prepare
 * @see #setCacheQueries
 * @see #setQueryCacheRegion
 */
protected void prepareCriteria(Criteria criteria) {
	if (isCacheQueries()) {
		criteria.setCacheable(true);
		if (getQueryCacheRegion() != null) {
			criteria.setCacheRegion(getQueryCacheRegion());
		}
	}
	if (getFetchSize() > 0) {
		criteria.setFetchSize(getFetchSize());
	}
	if (getMaxResults() > 0) {
		criteria.setMaxResults(getMaxResults());
	}

	SessionHolder sessionHolder =
			(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
	if (sessionHolder != null && sessionHolder.hasTimeout()) {
		criteria.setTimeout(sessionHolder.getTimeToLiveInSeconds());
	}
}
 
Example 6
Source File: HibernateTemplate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Prepare the given Criteria object, applying cache settings and/or
 * a transaction timeout.
 * @param criteria the Criteria object to prepare
 * @see #setCacheQueries
 * @see #setQueryCacheRegion
 */
protected void prepareCriteria(Criteria criteria) {
	if (isCacheQueries()) {
		criteria.setCacheable(true);
		if (getQueryCacheRegion() != null) {
			criteria.setCacheRegion(getQueryCacheRegion());
		}
	}
	if (getFetchSize() > 0) {
		criteria.setFetchSize(getFetchSize());
	}
	if (getMaxResults() > 0) {
		criteria.setMaxResults(getMaxResults());
	}

	SessionHolder sessionHolder =
			(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
	if (sessionHolder != null && sessionHolder.hasTimeout()) {
		criteria.setTimeout(sessionHolder.getTimeToLiveInSeconds());
	}
}
 
Example 7
Source File: HibernateTemplate.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Prepare the given Criteria object, applying cache settings and/or
 * a transaction timeout.
 * @param criteria the Criteria object to prepare
 * @see #setCacheQueries
 * @see #setQueryCacheRegion
 * @see SessionFactoryUtils#applyTransactionTimeout
 */
protected void prepareCriteria(Criteria criteria) {
	if (isCacheQueries()) {
		criteria.setCacheable(true);
		if (getQueryCacheRegion() != null) {
			criteria.setCacheRegion(getQueryCacheRegion());
		}
	}
	if (getFetchSize() > 0) {
		criteria.setFetchSize(getFetchSize());
	}
	if (getMaxResults() > 0) {
		criteria.setMaxResults(getMaxResults());
	}
	SessionFactoryUtils.applyTransactionTimeout(criteria, getSessionFactory());
}
 
Example 8
Source File: HibernateTemplate.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Prepare the given Criteria object, applying cache settings and/or
 * a transaction timeout.
 * @param criteria the Criteria object to prepare
 * @see #setCacheQueries
 * @see #setQueryCacheRegion
 * @see SessionFactoryUtils#applyTransactionTimeout
 */
protected void prepareCriteria(Criteria criteria) {
	if (isCacheQueries()) {
		criteria.setCacheable(true);
		if (getQueryCacheRegion() != null) {
			criteria.setCacheRegion(getQueryCacheRegion());
		}
	}
	if (getFetchSize() > 0) {
		criteria.setFetchSize(getFetchSize());
	}
	if (getMaxResults() > 0) {
		criteria.setMaxResults(getMaxResults());
	}
	SessionFactoryUtils.applyTransactionTimeout(criteria, getSessionFactory());
}
 
Example 9
Source File: HibernateDataOperation.java    From MiniWeChat-Server with MIT License 6 votes vote down vote up
public static List query(String paramName, Object paramValue, Class outputClass, ResultCode resultCode) {
	logger.info("Hibernate:start query from database");
	logger.info("Hibernate:query parameters:" + paramName + " , " + paramValue.toString());
	try {
		Session session = HibernateSessionFactory.getSession();
		Criteria criteria = session.createCriteria(outputClass);
		// 使用缓存
		criteria.setCacheable(true);
		criteria.add(Restrictions.eq(paramName, paramValue));
		List list = criteria.list();
		session.close();

		logger.info("Hibernate:query from database success");
		logger.info("Hibernate:query result list size:" + list.size());
		resultCode.setCode(ResultCode.SUCCESS);

		return list;
	} catch (Exception e) {
		resultCode.setCode(ResultCode.FAIL);
		logger.error("Hibernate:query from database fail");
		logger.error("Hibernate error:" + e.getStackTrace());
		logger.error("Hibernate error:" + e.getMessage());
		return null;
	}
}
 
Example 10
Source File: HibernateTemplate.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Prepare the given Criteria object, applying cache settings and/or
 * a transaction timeout.
 * @param criteria the Criteria object to prepare
 * @see #setCacheQueries
 * @see #setQueryCacheRegion
 */
protected void prepareCriteria(Criteria criteria) {
	if (isCacheQueries()) {
		criteria.setCacheable(true);
		if (getQueryCacheRegion() != null) {
			criteria.setCacheRegion(getQueryCacheRegion());
		}
	}
	if (getFetchSize() > 0) {
		criteria.setFetchSize(getFetchSize());
	}
	if (getMaxResults() > 0) {
		criteria.setMaxResults(getMaxResults());
	}

	SessionHolder sessionHolder =
			(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
	if (sessionHolder != null && sessionHolder.hasTimeout()) {
		criteria.setTimeout(sessionHolder.getTimeToLiveInSeconds());
	}
}
 
Example 11
Source File: MessageBundleServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Transactional(readOnly = true)
public List<String> getAllModuleNames() {
    Criteria query = sessionFactory.getCurrentSession().createCriteria(MessageBundleProperty.class)
            .setProjection(Projections.distinct(Projections.property("moduleName")))
            .addOrder(Order.asc("moduleName"));
    query.setCacheable(true);

    List<String> results = (List<String>) query.list();
    return results;
}
 
Example 12
Source File: _BaseRootDAO.java    From unitime with Apache License 2.0 5 votes vote down vote up
/**
 * Return all objects related to the implementation of this DAO with no filter.
 * Use the session given.
 */
@SuppressWarnings("unchecked")
public List<T> findAll (Session s, Order... orders) {
	Criteria crit = s.createCriteria(getReferenceClass());
	if (orders != null) {
		for (Order order: orders) {
			if (order != null)
				crit.addOrder(order);
		}
	}
	crit.setCacheable(true);
	return (List<T>)crit.list();
}
 
Example 13
Source File: MessageBundleServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Transactional(readOnly = true)
public List<String> getAllModuleNames() {
    Criteria query = sessionFactory.getCurrentSession().createCriteria(MessageBundleProperty.class)
            .setProjection(Projections.distinct(Projections.property("moduleName")))
            .addOrder(Order.asc("moduleName"));
    query.setCacheable(true);

    List<String> results = (List<String>) query.list();
    return results;
}
 
Example 14
Source File: HibernateDao.java    From jdal with Apache License 2.0 5 votes vote down vote up
/**
 * Get Page, apply filter if any.
 * If Filter is a entity model, use Example to create a criteria.
 * else enable filter by name on session. 
 * @param page with page definitions
 * @return page of results
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public <K> Page<K> getPage(Page<K> page) {
	
	List data = null;
	// try named query
	Query query = getQuery(page);
	if (query != null) {
		data = query.list();
	}
	else {
		// try filter, example and criteria builders
		Criteria criteria = getCriteria(page);
		ResultTransformer rt = ((CriteriaImpl) criteria).getResultTransformer(); 
		criteria.setProjection(Projections.rowCount());
		 page.setCount(((Long) criteria.uniqueResult()).intValue());
		// reset criteria
		criteria.setProjection(null);
		criteria.setResultTransformer(rt);
		// set start index and page size
		criteria.setFirstResult(page.getStartIndex())
			.setMaxResults(page.getPageSize());
		applyOrder(page, criteria);
		// run it
		criteria.setCacheable(cachePageQueries);
		data = criteria.list();
	}
	
	page.setData(data);
	
	return page;
}
 
Example 15
Source File: GrailsHibernateQueryUtils.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
/**
 * Configures the criteria instance to cache based on the configured mapping.
 *
 * @param targetClass The target class
 * @param criteria    The criteria
 */
private static void cacheCriteriaByMapping(Class<?> targetClass, Criteria criteria) {
    Mapping m = AbstractGrailsDomainBinder.getMapping(targetClass);
    if (m != null && m.getCache() != null && m.getCache().getEnabled()) {
        criteria.setCacheable(true);
    }
}
 
Example 16
Source File: ArticleService.java    From J2Cache with Apache License 2.0 5 votes vote down vote up
public Article findUnique(Criterion... criterions) {
    Criteria criteria = getSession().createCriteria(Article.class);
    for (Criterion c : criterions) {
        criteria.add(c);
    }
    criteria.setCacheable(true);
    return (Article)criteria.uniqueResult();
}
 
Example 17
Source File: ArticleService.java    From J2Cache with Apache License 2.0 5 votes vote down vote up
public List<Article> find(Criterion... criterions) {
    Criteria criteria = getSession().createCriteria(Article.class);
    for (Criterion c : criterions) {
        criteria.add(c);
    }
    criteria.setCacheable(true);
    return criteria.list();
}
 
Example 18
Source File: ArticleService.java    From J2Cache with Apache License 2.0 5 votes vote down vote up
public Article findUnique(Criterion... criterions) {
    Criteria criteria = getSession().createCriteria(Article.class);
    for (Criterion c : criterions) {
        criteria.add(c);
    }
    criteria.setCacheable(true);
    return (Article)criteria.uniqueResult();
}
 
Example 19
Source File: ArticleService.java    From J2Cache with Apache License 2.0 5 votes vote down vote up
public List<Article> find(Criterion... criterions) {
    Criteria criteria = getSession().createCriteria(Article.class);
    for (Criterion c : criterions) {
        criteria.add(c);
    }
    criteria.setCacheable(true);
    return criteria.list();
}
 
Example 20
Source File: HibernateStorage.java    From gsn with GNU General Public License v3.0 4 votes vote down vote up
/**
 * This method checks if there is one or more {@link ch.epfl.gsn.beans.StreamElement} available in the DataEnumerator.
 * If the current page is empty, it tries to load the next page.
 * @return
 */
public boolean hasMoreElements() {

    // Check if the DataEnumerator is closed
    if (closed)
        return false;

    // Check if there is still data in the current pageContent
    if (pci != null && pci.hasNext())
        return true;

    // Compute the next number of elements to fetch
    int offset = currentPage * pageSize;
    int mr = pageSize;
    if (maxResults > 0) {
        int remaining = maxResults - offset;
        mr = remaining > 0 ? remaining >= pageSize ? pageSize : remaining % pageSize : 0;
    }

    // Try to load the next page
    pci = null;
    Transaction tx = null;
    try {
        Session session = sf.getCurrentSession();
        tx = session.beginTransaction();
        //
        Criteria criteria = session.createCriteria(identifier);
        for (Criterion criterion : crits) {
            criteria.add(criterion);
        }
        criteria.addOrder(order);
        criteria.setCacheable(true);
        criteria.setReadOnly(true);
        criteria.setFirstResult(offset);
        criteria.setMaxResults(mr);
        //
        pci = criteria.list().iterator();
        tx.commit();
        currentPage++;

    } catch (RuntimeException e) {
        try {
            if (tx != null)
                tx.rollback();
        } catch (RuntimeException ex) {
            logger.error("Couldn't roll back transaction.");
        }
        throw e;
    }
    if(pci != null &&  pci.hasNext()) {
        return true;
    }
    else {
        close();
        return false;
    }
}