Search in sources :

Example 41 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor 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 42 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor 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 43 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class DefaultLoadEventListener method assembleCacheEntry.

private Object assembleCacheEntry(final StandardCacheEntryImpl entry, final Serializable id, final EntityPersister persister, final LoadEvent event) throws HibernateException {
    final Object optionalObject = event.getInstanceToLoad();
    final EventSource session = event.getSession();
    final SessionFactoryImplementor factory = session.getFactory();
    if (traceEnabled) {
        LOG.tracev("Assembling entity from second-level cache: {0}", MessageHelper.infoString(persister, id, factory));
    }
    EntityPersister subclassPersister = factory.getEntityPersister(entry.getSubclass());
    Object result = optionalObject == null ? session.instantiate(subclassPersister, id) : optionalObject;
    // make it circular-reference safe
    final EntityKey entityKey = session.generateEntityKey(id, subclassPersister);
    TwoPhaseLoad.addUninitializedCachedEntity(entityKey, result, subclassPersister, LockMode.NONE, entry.getVersion(), session);
    Type[] types = subclassPersister.getPropertyTypes();
    Object[] values = entry.assemble(result, id, subclassPersister, session.getInterceptor(), session);
    // intializes result by side-effect
    TypeHelper.deepCopy(values, types, subclassPersister.getPropertyUpdateability(), values, session);
    Object version = Versioning.getVersion(values, subclassPersister);
    LOG.tracev("Cached Version: {0}", version);
    final PersistenceContext persistenceContext = session.getPersistenceContext();
    boolean isReadOnly = session.isDefaultReadOnly();
    if (persister.isMutable()) {
        Object proxy = persistenceContext.getProxy(entityKey);
        if (proxy != null) {
            // there is already a proxy for this impl
            // only set the status to read-only if the proxy is read-only
            isReadOnly = ((HibernateProxy) proxy).getHibernateLazyInitializer().isReadOnly();
        }
    } else {
        isReadOnly = true;
    }
    persistenceContext.addEntry(result, (isReadOnly ? Status.READ_ONLY : Status.MANAGED), values, null, id, version, LockMode.NONE, true, subclassPersister, false);
    subclassPersister.afterInitialize(result, session);
    persistenceContext.initializeNonLazyCollections();
    // upgrade the lock if necessary:
    //lock(result, lockMode);
    //PostLoad is needed for EJB3
    //TODO: reuse the PostLoadEvent...
    PostLoadEvent postLoadEvent = event.getPostLoadEvent().setEntity(result).setId(id).setPersister(persister);
    for (PostLoadEventListener listener : postLoadEventListeners(session)) {
        listener.onPostLoad(postLoadEvent);
    }
    return result;
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) PostLoadEvent(org.hibernate.event.spi.PostLoadEvent) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) StatefulPersistenceContext(org.hibernate.engine.internal.StatefulPersistenceContext) HibernateProxy(org.hibernate.proxy.HibernateProxy) PostLoadEventListener(org.hibernate.event.spi.PostLoadEventListener) EntityKey(org.hibernate.engine.spi.EntityKey) EventSource(org.hibernate.event.spi.EventSource) EmbeddedComponentType(org.hibernate.type.EmbeddedComponentType) EntityType(org.hibernate.type.EntityType) EventType(org.hibernate.event.spi.EventType) Type(org.hibernate.type.Type)

Example 44 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class DefaultResolveNaturalIdEventListener method loadFromDatasource.

/**
	 * Performs the process of loading an entity from the configured
	 * underlying datasource.
	 * 
	 * @param event The load event
	 *
	 * @return The object loaded from the datasource, or null if not found.
	 */
protected Serializable loadFromDatasource(final ResolveNaturalIdEvent event) {
    final SessionFactoryImplementor factory = event.getSession().getFactory();
    final boolean stats = factory.getStatistics().isStatisticsEnabled();
    long startTime = 0;
    if (stats) {
        startTime = System.nanoTime();
    }
    final Serializable pk = event.getEntityPersister().loadEntityIdByNaturalId(event.getOrderedNaturalIdValues(), event.getLockOptions(), event.getSession());
    if (stats) {
        final NaturalIdRegionAccessStrategy naturalIdCacheAccessStrategy = event.getEntityPersister().getNaturalIdCacheAccessStrategy();
        final String regionName = naturalIdCacheAccessStrategy == null ? null : naturalIdCacheAccessStrategy.getRegion().getName();
        final long endTime = System.nanoTime();
        final long milliseconds = TimeUnit.MILLISECONDS.convert(endTime - startTime, TimeUnit.NANOSECONDS);
        factory.getStatisticsImplementor().naturalIdQueryExecuted(regionName, milliseconds);
    }
    //PK can be null if the entity doesn't exist
    if (pk != null) {
        event.getSession().getPersistenceContext().getNaturalIdHelper().cacheNaturalIdCrossReferenceFromLoad(event.getEntityPersister(), pk, event.getOrderedNaturalIdValues());
    }
    return pk;
}
Also used : Serializable(java.io.Serializable) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) NaturalIdRegionAccessStrategy(org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy)

Example 45 with SessionFactoryImplementor

use of org.hibernate.engine.spi.SessionFactoryImplementor in project hibernate-orm by hibernate.

the class InLogicOperatorNode method initialize.

@Override
public void initialize() throws SemanticException {
    final Node lhs = getLeftHandOperand();
    if (lhs == null) {
        throw new SemanticException("left-hand operand of in operator was null");
    }
    final Node inList = getInList();
    if (inList == null) {
        throw new SemanticException("right-hand operand of in operator was null");
    }
    // one-or-more params.
    if (SqlNode.class.isAssignableFrom(lhs.getClass())) {
        Type lhsType = ((SqlNode) lhs).getDataType();
        AST inListChild = inList.getFirstChild();
        while (inListChild != null) {
            if (ExpectedTypeAwareNode.class.isAssignableFrom(inListChild.getClass())) {
                ((ExpectedTypeAwareNode) inListChild).setExpectedType(lhsType);
            }
            // fix for HHH-9605
            if (CollectionFunction.class.isInstance(inListChild) && ExpectedTypeAwareNode.class.isInstance(lhs)) {
                final Type rhsType = ((CollectionFunction) inListChild).getDataType();
                ((ExpectedTypeAwareNode) lhs).setExpectedType(rhsType);
            }
            inListChild = inListChild.getNextSibling();
        }
    }
    final SessionFactoryImplementor sessionFactory = getSessionFactoryHelper().getFactory();
    if (sessionFactory.getDialect().supportsRowValueConstructorSyntaxInInList()) {
        return;
    }
    final Type lhsType = extractDataType(lhs);
    if (lhsType == null) {
        return;
    }
    final int lhsColumnSpan = lhsType.getColumnSpan(sessionFactory);
    final Node rhsNode = (Node) inList.getFirstChild();
    if (!isNodeAcceptable(rhsNode)) {
        return;
    }
    int rhsColumnSpan;
    if (rhsNode == null) {
        // early exit for empty IN list
        return;
    } else if (rhsNode.getType() == HqlTokenTypes.VECTOR_EXPR) {
        rhsColumnSpan = rhsNode.getNumberOfChildren();
    } else {
        final Type rhsType = extractDataType(rhsNode);
        if (rhsType == null) {
            return;
        }
        rhsColumnSpan = rhsType.getColumnSpan(sessionFactory);
    }
    if (lhsColumnSpan > 1 && rhsColumnSpan > 1) {
        mutateRowValueConstructorSyntaxInInListSyntax(lhsColumnSpan, rhsColumnSpan);
    }
}
Also used : Type(org.hibernate.type.Type) AST(antlr.collections.AST) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SemanticException(antlr.SemanticException)

Aggregations

SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)129 Test (org.junit.Test)46 Configuration (org.hibernate.cfg.Configuration)27 SQLException (java.sql.SQLException)18 Type (org.hibernate.type.Type)16 EntityPersister (org.hibernate.persister.entity.EntityPersister)13 Connection (java.sql.Connection)12 HibernateException (org.hibernate.HibernateException)12 PreparedStatement (java.sql.PreparedStatement)11 Metadata (org.hibernate.boot.Metadata)11 Statement (java.sql.Statement)10 ArrayList (java.util.ArrayList)10 JdbcConnectionAccess (org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess)10 JdbcServices (org.hibernate.engine.jdbc.spi.JdbcServices)10 Serializable (java.io.Serializable)9 EncapsulatedCompositeIdResultSetProcessorTest (org.hibernate.test.loadplans.process.EncapsulatedCompositeIdResultSetProcessorTest)8 HashMap (java.util.HashMap)7 Integrator (org.hibernate.integrator.spi.Integrator)7 SessionFactoryServiceRegistry (org.hibernate.service.spi.SessionFactoryServiceRegistry)7 Map (java.util.Map)6