Search in sources :

Example 1 with CollectionCacheEntry

use of org.hibernate.cache.spi.entry.CollectionCacheEntry in project hibernate-orm by hibernate.

the class CollectionLoadContext method addCollectionToCache.

/**
	 * Add the collection to the second-level cache
	 *
	 * @param lce The entry representing the collection to add
	 * @param persister The persister
	 */
private void addCollectionToCache(LoadingCollectionEntry lce, CollectionPersister persister) {
    final SharedSessionContractImplementor session = getLoadContext().getPersistenceContext().getSession();
    final SessionFactoryImplementor factory = session.getFactory();
    final boolean debugEnabled = LOG.isDebugEnabled();
    if (debugEnabled) {
        LOG.debugf("Caching collection: %s", MessageHelper.collectionInfoString(persister, lce.getCollection(), lce.getKey(), session));
    }
    if (!session.getLoadQueryInfluencers().getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters(session)) {
        // some filters affecting the collection are enabled on the session, so do not do the put into the cache.
        if (debugEnabled) {
            LOG.debug("Refusing to add to cache due to enabled filters");
        }
        // EARLY EXIT!!!!!
        return;
    }
    final Object version;
    if (persister.isVersioned()) {
        Object collectionOwner = getLoadContext().getPersistenceContext().getCollectionOwner(lce.getKey(), persister);
        if (collectionOwner == null) {
            // resolution against the PC anyway just to be safe since the lookup should not be costly.
            if (lce.getCollection() != null) {
                final Object linkedOwner = lce.getCollection().getOwner();
                if (linkedOwner != null) {
                    final Serializable ownerKey = persister.getOwnerEntityPersister().getIdentifier(linkedOwner, session);
                    collectionOwner = getLoadContext().getPersistenceContext().getCollectionOwner(ownerKey, persister);
                }
            }
            if (collectionOwner == null) {
                throw new HibernateException("Unable to resolve owner of loading collection [" + MessageHelper.collectionInfoString(persister, lce.getCollection(), lce.getKey(), session) + "] for second level caching");
            }
        }
        version = getLoadContext().getPersistenceContext().getEntry(collectionOwner).getVersion();
    } else {
        version = null;
    }
    final CollectionCacheEntry entry = new CollectionCacheEntry(lce.getCollection(), persister);
    final CollectionRegionAccessStrategy cache = persister.getCacheAccessStrategy();
    final Object cacheKey = cache.generateCacheKey(lce.getKey(), persister, session.getFactory(), session.getTenantIdentifier());
    boolean isPutFromLoad = true;
    if (persister.getElementType().isAssociationType()) {
        for (Serializable id : entry.getState()) {
            EntityPersister entityPersister = ((QueryableCollection) persister).getElementPersister();
            if (session.getPersistenceContext().wasInsertedDuringTransaction(entityPersister, id)) {
                isPutFromLoad = false;
                break;
            }
        }
    }
    // CollectionRegionAccessStrategy has no update, so avoid putting uncommitted data via putFromLoad
    if (isPutFromLoad) {
        try {
            session.getEventListenerManager().cachePutStart();
            final boolean put = cache.putFromLoad(session, cacheKey, persister.getCacheEntryStructure().structure(entry), session.getTimestamp(), version, factory.getSessionFactoryOptions().isMinimalPutsEnabled() && session.getCacheMode() != CacheMode.REFRESH);
            if (put && factory.getStatistics().isStatisticsEnabled()) {
                factory.getStatistics().secondLevelCachePut(persister.getCacheAccessStrategy().getRegion().getName());
            }
        } finally {
            session.getEventListenerManager().cachePutEnd();
        }
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) Serializable(java.io.Serializable) CollectionCacheEntry(org.hibernate.cache.spi.entry.CollectionCacheEntry) HibernateException(org.hibernate.HibernateException) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) QueryableCollection(org.hibernate.persister.collection.QueryableCollection) CollectionRegionAccessStrategy(org.hibernate.cache.spi.access.CollectionRegionAccessStrategy)

Example 2 with CollectionCacheEntry

use of org.hibernate.cache.spi.entry.CollectionCacheEntry in project hibernate-orm by hibernate.

the class DefaultInitializeCollectionEventListener method initializeCollectionFromCache.

/**
	 * Try to initialize a collection from the cache
	 *
	 * @param id The id of the collection of initialize
	 * @param persister The collection persister
	 * @param collection The collection to initialize
	 * @param source The originating session
	 *
	 * @return true if we were able to initialize the collection from the cache;
	 *         false otherwise.
	 */
private boolean initializeCollectionFromCache(Serializable id, CollectionPersister persister, PersistentCollection collection, SessionImplementor source) {
    if (!source.getLoadQueryInfluencers().getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters(source)) {
        LOG.trace("Disregarding cached version (if any) of collection due to enabled filters");
        return false;
    }
    final boolean useCache = persister.hasCache() && source.getCacheMode().isGetEnabled();
    if (!useCache) {
        return false;
    }
    final SessionFactoryImplementor factory = source.getFactory();
    final CollectionRegionAccessStrategy cacheAccessStrategy = persister.getCacheAccessStrategy();
    final Object ck = cacheAccessStrategy.generateCacheKey(id, persister, factory, source.getTenantIdentifier());
    final Object ce = CacheHelper.fromSharedCache(source, ck, persister.getCacheAccessStrategy());
    if (factory.getStatistics().isStatisticsEnabled()) {
        if (ce == null) {
            factory.getStatisticsImplementor().secondLevelCacheMiss(cacheAccessStrategy.getRegion().getName());
        } else {
            factory.getStatisticsImplementor().secondLevelCacheHit(cacheAccessStrategy.getRegion().getName());
        }
    }
    if (ce == null) {
        return false;
    }
    CollectionCacheEntry cacheEntry = (CollectionCacheEntry) persister.getCacheEntryStructure().destructure(ce, factory);
    final PersistenceContext persistenceContext = source.getPersistenceContext();
    cacheEntry.assemble(collection, persister, persistenceContext.getCollectionOwner(id, persister));
    persistenceContext.getCollectionEntry(collection).postInitialize(collection);
    // addInitializedCollection(collection, persister, id);
    return true;
}
Also used : CollectionCacheEntry(org.hibernate.cache.spi.entry.CollectionCacheEntry) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) CollectionRegionAccessStrategy(org.hibernate.cache.spi.access.CollectionRegionAccessStrategy)

Example 3 with CollectionCacheEntry

use of org.hibernate.cache.spi.entry.CollectionCacheEntry in project hibernate-orm by hibernate.

the class DynamicFilterTest method testSecondLevelCachedCollectionsFiltering.

@Test
public void testSecondLevelCachedCollectionsFiltering() {
    TestData testData = new TestData();
    testData.prepare();
    Session session = openSession();
    long ts = ((SessionImplementor) session).getTimestamp();
    // Force a collection into the second level cache, with its non-filtered elements
    Salesperson sp = (Salesperson) session.load(Salesperson.class, testData.steveId);
    Hibernate.initialize(sp.getOrders());
    CollectionPersister persister = sessionFactory().getCollectionPersister(Salesperson.class.getName() + ".orders");
    assertTrue("No cache for collection", persister.hasCache());
    CollectionRegionAccessStrategy cache = persister.getCacheAccessStrategy();
    Object cacheKey = cache.generateCacheKey(testData.steveId, persister, sessionFactory(), session.getTenantIdentifier());
    CollectionCacheEntry cachedData = (CollectionCacheEntry) cache.get((SessionImplementor) session, cacheKey, ts);
    assertNotNull("collection was not in cache", cachedData);
    session.close();
    session = openSession();
    ts = ((SessionImplementor) session).getTimestamp();
    session.enableFilter("fulfilledOrders").setParameter("asOfDate", testData.lastMonth.getTime());
    sp = (Salesperson) session.createQuery("from Salesperson as s where s.id = :id").setLong("id", testData.steveId).uniqueResult();
    assertEquals("Filtered-collection not bypassing 2L-cache", 1, sp.getOrders().size());
    Object cacheKey2 = cache.generateCacheKey(testData.steveId, persister, sessionFactory(), session.getTenantIdentifier());
    CollectionCacheEntry cachedData2 = (CollectionCacheEntry) persister.getCacheAccessStrategy().get((SessionImplementor) session, cacheKey2, ts);
    assertNotNull("collection no longer in cache!", cachedData2);
    assertSame("Different cache values!", cachedData, cachedData2);
    session.close();
    session = openSession();
    session.enableFilter("fulfilledOrders").setParameter("asOfDate", testData.lastMonth.getTime());
    sp = (Salesperson) session.load(Salesperson.class, testData.steveId);
    assertEquals("Filtered-collection not bypassing 2L-cache", 1, sp.getOrders().size());
    session.close();
    // Finally, make sure that the original cached version did not get over-written
    session = openSession();
    sp = (Salesperson) session.load(Salesperson.class, testData.steveId);
    assertEquals("Actual cached version got over-written", 2, sp.getOrders().size());
    session.close();
    testData.release();
}
Also used : CollectionCacheEntry(org.hibernate.cache.spi.entry.CollectionCacheEntry) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) SessionImplementor(org.hibernate.engine.spi.SessionImplementor) CollectionRegionAccessStrategy(org.hibernate.cache.spi.access.CollectionRegionAccessStrategy) Session(org.hibernate.Session) Test(org.junit.Test)

Aggregations

CollectionRegionAccessStrategy (org.hibernate.cache.spi.access.CollectionRegionAccessStrategy)3 CollectionCacheEntry (org.hibernate.cache.spi.entry.CollectionCacheEntry)3 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)2 Serializable (java.io.Serializable)1 HibernateException (org.hibernate.HibernateException)1 Session (org.hibernate.Session)1 PersistenceContext (org.hibernate.engine.spi.PersistenceContext)1 SessionImplementor (org.hibernate.engine.spi.SessionImplementor)1 SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)1 CollectionPersister (org.hibernate.persister.collection.CollectionPersister)1 QueryableCollection (org.hibernate.persister.collection.QueryableCollection)1 EntityPersister (org.hibernate.persister.entity.EntityPersister)1 Test (org.junit.Test)1