Java Code Examples for org.hibernate.query.Query#setCacheable()

The following examples show how to use org.hibernate.query.Query#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: TestQueryCache.java    From HibernateTips with MIT License 6 votes vote down vote up
@Test
public void selectAuthors() {
	log.info("... selectAuthors ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();

	Session s = em.unwrap(Session.class);
	Query<Author> q = s.createQuery("SELECT a FROM Author a WHERE id = :id", Author.class);
	q.setParameter("id", 1L);
	q.setCacheable(true);
	log.info(q.getSingleResult());
	
	log.info(q.getSingleResult());

	em.getTransaction().commit();
	em.close();
}
 
Example 2
Source File: HibernateFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Using a named query, find all the objects matching the criteria within.
 * Warning: This can be very expensive if the returned list is large. Use
 * only for small tables with static data
 * @param qryName Named query to use to find a list of objects.
 * @param qryParams Map of named bind parameters whose keys are Strings. The
 * map can also be null.
 * @param cacheable if we should cache the results of this query
 * @return List of objects returned by named query, or null if nothing
 * found.
 */
protected List listObjectsByNamedQuery(String qryName, Map qryParams,
        boolean cacheable) {
    Session session = null;
    List retval = null;
    session = HibernateFactory.getSession();
    Query query = session.getNamedQuery(qryName);
    query.setCacheable(cacheable);
    bindParameters(query, qryParams);
    retval = query.list();
    return retval;
}
 
Example 3
Source File: KickstartFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Looks up a specific KickstartCommandName
 * @param commandName name of the KickstartCommandName
 * @return found instance, if any
 */
public static KickstartCommandName lookupKickstartCommandName(String commandName) {
    Session session = null;
    KickstartCommandName retval = null;
    session = HibernateFactory.getSession();
    Query query =
            session.getNamedQuery("KickstartCommandName.findByLabel");
    //Retrieve from cache if there
    query.setCacheable(true);
    query.setParameter("name", commandName);
    retval = (KickstartCommandName) query.uniqueResult();
    return retval;

}
 
Example 4
Source File: AbstractSharedSessionContract.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void initQueryFromNamedDefinition(Query query, NamedQueryDefinition nqd) {
	// todo : cacheable and readonly should be Boolean rather than boolean...
	query.setCacheable( nqd.isCacheable() );
	query.setCacheRegion( nqd.getCacheRegion() );
	query.setReadOnly( nqd.isReadOnly() );

	if ( nqd.getTimeout() != null ) {
		query.setTimeout( nqd.getTimeout() );
	}
	if ( nqd.getFetchSize() != null ) {
		query.setFetchSize( nqd.getFetchSize() );
	}
	if ( nqd.getCacheMode() != null ) {
		query.setCacheMode( nqd.getCacheMode() );
	}
	if ( nqd.getComment() != null ) {
		query.setComment( nqd.getComment() );
	}
	if ( nqd.getFirstResult() != null ) {
		query.setFirstResult( nqd.getFirstResult() );
	}
	if ( nqd.getMaxResults() != null ) {
		query.setMaxResults( nqd.getMaxResults() );
	}
	if ( nqd.getFlushMode() != null ) {
		query.setHibernateFlushMode( nqd.getFlushMode() );
	}
}
 
Example 5
Source File: MCRCategLinkServiceImpl.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Collection<String> getLinksFromCategory(MCRCategoryID id) {
    Query<?> q = HIB_CONNECTION_INSTANCE.getNamedQuery(NAMED_QUERY_NAMESPACE + "ObjectIDByCategory");
    q.setCacheable(true);
    q.setParameter("id", id);
    q.setReadOnly(true);
    return (Collection<String>) q.getResultList();
}
 
Example 6
Source File: MCRCategLinkServiceImpl.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Collection<String> getLinksFromCategoryForType(MCRCategoryID id, String type) {
    Query<?> q = HIB_CONNECTION_INSTANCE.getNamedQuery(NAMED_QUERY_NAMESPACE + "ObjectIDByCategoryAndType");
    q.setCacheable(true);
    q.setParameter("id", id);
    q.setParameter("type", type);
    q.setReadOnly(true);
    return (Collection<String>) q.getResultList();
}
 
Example 7
Source File: MCRCategLinkServiceImpl.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Collection<MCRCategoryID> getLinksFromReference(MCRCategLinkReference reference) {
    Query<?> q = HIB_CONNECTION_INSTANCE.getNamedQuery(NAMED_QUERY_NAMESPACE + "categoriesByObjectID");
    q.setCacheable(true);
    q.setParameter("id", reference.getObjectID());
    q.setParameter("type", reference.getType());
    q.setReadOnly(true);
    return (Collection<MCRCategoryID>) q.getResultList();
}
 
Example 8
Source File: MCRCategLinkServiceImpl.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isInCategory(MCRCategLinkReference reference, MCRCategoryID id) {
    Query<?> q = HIB_CONNECTION_INSTANCE.getNamedQuery(NAMED_QUERY_NAMESPACE + "CategoryAndObjectID");
    q.setCacheable(true);
    q.setReadOnly(true);
    q.setParameter("rootID", id.getRootID());
    q.setParameter("categID", id.getID());
    q.setParameter("objectID", reference.getObjectID());
    q.setParameter("type", reference.getType());
    return !q.getResultList().isEmpty();
}
 
Example 9
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, Query criteria) {
    Mapping m = AbstractGrailsDomainBinder.getMapping(targetClass);
    if (m != null && m.getCache() != null && m.getCache().getEnabled()) {
        criteria.setCacheable(true);
    }
}
 
Example 10
Source File: GrailsHibernateTemplate.java    From gorm-hibernate5 with Apache License 2.0 5 votes vote down vote up
/**
 * Prepare the given Query object, applying cache settings and/or a
 * transaction timeout.
 *
 * @param jpaQuery the Query object to prepare
 */
protected <T> void prepareCriteria(Query<T> jpaQuery) {
    if (cacheQueries) {
        jpaQuery.setCacheable(true);
    }
    if (shouldPassReadOnlyToHibernate()) {
        jpaQuery.setReadOnly(true);
    }
    SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory);
    if (sessionHolder != null && sessionHolder.hasTimeout()) {
        jpaQuery.setTimeout(sessionHolder.getTimeToLiveInSeconds());
    }
}
 
Example 11
Source File: HibernateUserSettingStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public UserSetting getUserSetting( User user, String name )
{
    Session session = sessionFactory.getCurrentSession();
    Query<UserSetting> query = session.createQuery( "from UserSetting us where us.user = :user and us.name = :name" );
    query.setParameter( "user", user );
    query.setParameter( "name", name );
    query.setCacheable( CACHEABLE );

    return query.uniqueResult();
}
 
Example 12
Source File: HibernateUserSettingStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public List<UserSetting> getAllUserSettings( User user )
{
    Session session = sessionFactory.getCurrentSession();
    Query<UserSetting> query = session.createQuery( "from UserSetting us where us.user = :user" );
    query.setParameter( "user", user );
    query.setCacheable( CACHEABLE );

    return query.list();
}
 
Example 13
Source File: MCRCategLinkServiceImpl.java    From mycore with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Map<MCRCategoryID, Number> countLinksForType(MCRCategory parent, String type, boolean childrenOnly) {
    boolean restrictedByType = type != null;
    String queryName;
    if (childrenOnly) {
        queryName = restrictedByType ? "NumberByTypePerChildOfParentID" : "NumberPerChildOfParentID";
    } else {
        queryName = restrictedByType ? "NumberByTypePerClassID" : "NumberPerClassID";
    }
    Map<MCRCategoryID, Number> countLinks = new HashMap<>();
    Collection<MCRCategoryID> ids = childrenOnly ? getAllChildIDs(parent) : getAllCategIDs(parent);
    for (MCRCategoryID id : ids) {
        // initialize all categIDs with link count of zero
        countLinks.put(id, 0);
    }
    //have to use rootID here if childrenOnly=false
    //old classification browser/editor could not determine links correctly otherwise
    if (!childrenOnly) {
        parent = parent.getRoot();
    } else if (!(parent instanceof MCRCategoryImpl) || ((MCRCategoryImpl) parent).getInternalID() == 0) {
        parent = MCRCategoryDAOImpl.getByNaturalID(MCREntityManagerProvider.getCurrentEntityManager(),
            parent.getId());
    }
    LOGGER.info("parentID:{}", parent.getId());
    String classID = parent.getId().getRootID();
    Query<?> q = HIB_CONNECTION_INSTANCE.getNamedQuery(NAMED_QUERY_NAMESPACE + queryName);
    // query can take long time, please cache result
    q.setCacheable(true);
    q.setReadOnly(true);
    q.setParameter("classID", classID);
    if (childrenOnly) {
        q.setParameter("parentID", ((MCRCategoryImpl) parent).getInternalID());
    }
    if (restrictedByType) {
        q.setParameter("type", type);
    }
    // get object count for every category (not accumulated)
    @SuppressWarnings("unchecked")
    List<Object[]> result = (List<Object[]>) q.getResultList();
    for (Object[] sr : result) {
        MCRCategoryID key = new MCRCategoryID(classID, sr[0].toString());
        Number value = (Number) sr[1];
        countLinks.put(key, value);
    }
    return countLinks;
}
 
Example 14
Source File: GrailsHibernateQueryUtils.java    From gorm-hibernate5 with Apache License 2.0 4 votes vote down vote up
/**
 * Populates criteria arguments for the given target class and arguments map
 *
 * @param entity The {@link org.grails.datastore.mapping.model.PersistentEntity} instance
 * @param query  The criteria instance
 * @param argMap The arguments map
 */
@SuppressWarnings("rawtypes")
public static void populateArgumentsForCriteria(
        PersistentEntity entity,
        Query query,
        Map argMap,
        ConversionService conversionService,
        boolean useDefaultMapping) {
    Integer maxParam = null;
    Integer offsetParam = null;
    if (argMap.containsKey(DynamicFinder.ARGUMENT_MAX)) {
        maxParam = conversionService.convert(argMap.get(DynamicFinder.ARGUMENT_MAX), Integer.class);
    }
    if (argMap.containsKey(DynamicFinder.ARGUMENT_OFFSET)) {
        offsetParam = conversionService.convert(argMap.get(DynamicFinder.ARGUMENT_OFFSET), Integer.class);
    }
    if (argMap.containsKey(DynamicFinder.ARGUMENT_FETCH_SIZE)) {
        query.setFetchSize(conversionService.convert(argMap.get(DynamicFinder.ARGUMENT_FETCH_SIZE), Integer.class));
    }
    if (argMap.containsKey(DynamicFinder.ARGUMENT_TIMEOUT)) {
        query.setTimeout(conversionService.convert(argMap.get(DynamicFinder.ARGUMENT_TIMEOUT), Integer.class));
    }
    if (argMap.containsKey(DynamicFinder.ARGUMENT_FLUSH_MODE)) {
        query.setHibernateFlushMode(convertFlushMode(argMap.get(DynamicFinder.ARGUMENT_FLUSH_MODE)));
    }
    if (argMap.containsKey(DynamicFinder.ARGUMENT_READ_ONLY)) {
        query.setReadOnly(ClassUtils.getBooleanFromMap(DynamicFinder.ARGUMENT_READ_ONLY, argMap));
    }

    final int max = maxParam == null ? -1 : maxParam;
    final int offset = offsetParam == null ? -1 : offsetParam;
    if (max > -1) {
        query.setMaxResults(max);
    }
    if (offset > -1) {
        query.setFirstResult(offset);
    }
    if (ClassUtils.getBooleanFromMap(DynamicFinder.ARGUMENT_LOCK, argMap)) {
        query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
        query.setCacheable(false);
    } else {
        if (argMap.containsKey(DynamicFinder.ARGUMENT_CACHE)) {
            query.setCacheable(ClassUtils.getBooleanFromMap(DynamicFinder.ARGUMENT_CACHE, argMap));
        } else {
            cacheCriteriaByMapping(entity.getJavaClass(), query);
        }
    }

}