Search in sources :

Example 1 with LoadingEntityEntry

use of org.hibernate.sql.results.graph.entity.LoadingEntityEntry in project hibernate-orm by hibernate.

the class BatchEntitySelectFetchInitializer method initializeInstance.

@Override
public void initializeInstance(RowProcessingState rowProcessingState) {
    if (isInitialized) {
        return;
    }
    if (!isAttributeAssignableToConcreteDescriptor()) {
        return;
    }
    final Object entityIdentifier = identifierAssembler.assemble(rowProcessingState);
    if (entityIdentifier == null) {
        return;
    }
    entityKey = new EntityKey(entityIdentifier, concreteDescriptor);
    final PersistenceContext persistenceContext = rowProcessingState.getSession().getPersistenceContextInternal();
    entityInstance = persistenceContext.getEntity(entityKey);
    if (entityInstance != null) {
        return;
    }
    Initializer initializer = rowProcessingState.getJdbcValuesSourceProcessingState().findInitializer(entityKey);
    if (initializer != null) {
        if (EntityLoadingLogger.DEBUG_ENABLED) {
            EntityLoadingLogger.LOGGER.debugf("(%s) Found an initializer for entity (%s) : %s", CONCRETE_NAME, toLoggableString(getNavigablePath(), entityIdentifier), entityIdentifier);
        }
        initializer.resolveInstance(rowProcessingState);
        entityInstance = initializer.getInitializedInstance();
        // EARLY EXIT!!!
        return;
    }
    final LoadingEntityEntry existingLoadingEntry = rowProcessingState.getSession().getPersistenceContext().getLoadContexts().findLoadingEntityEntry(entityKey);
    if (existingLoadingEntry != null) {
        if (existingLoadingEntry.getEntityInitializer() != this) {
            // the entity is already being loaded elsewhere
            if (EntityLoadingLogger.DEBUG_ENABLED) {
                EntityLoadingLogger.LOGGER.debugf("(%s) Entity [%s] being loaded by another initializer [%s] - skipping processing", CONCRETE_NAME, toLoggableString(getNavigablePath(), entityIdentifier), existingLoadingEntry.getEntityInitializer());
            }
            this.entityInstance = existingLoadingEntry.getEntityInstance();
            // EARLY EXIT!!!
            return;
        }
    }
    persistenceContext.getBatchFetchQueue().addBatchLoadableEntityKey(entityKey);
    toBatchLoad.put(entityKey, parentAccess.getInitializedInstance());
    isInitialized = true;
}
Also used : EntityKey(org.hibernate.engine.spi.EntityKey) EntityInitializer(org.hibernate.sql.results.graph.entity.EntityInitializer) Initializer(org.hibernate.sql.results.graph.Initializer) AbstractEntityInitializer(org.hibernate.sql.results.graph.entity.AbstractEntityInitializer) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) LoadingEntityEntry(org.hibernate.sql.results.graph.entity.LoadingEntityEntry)

Example 2 with LoadingEntityEntry

use of org.hibernate.sql.results.graph.entity.LoadingEntityEntry in project hibernate-orm by hibernate.

the class EntitySelectFetchInitializer method initializeInstance.

@Override
public void initializeInstance(RowProcessingState rowProcessingState) {
    if (entityInstance != null || isInitialized) {
        return;
    }
    if (!isAttributeAssignableToConcreteDescriptor()) {
        return;
    }
    final Object entityIdentifier = identifierAssembler.assemble(rowProcessingState);
    if (entityIdentifier == null) {
        isInitialized = true;
        return;
    }
    if (EntityLoadingLogger.TRACE_ENABLED) {
        EntityLoadingLogger.LOGGER.tracef("(%s) Beginning Initializer#resolveInstance process for entity (%s) : %s", StringHelper.collapse(this.getClass().getName()), getNavigablePath(), entityIdentifier);
    }
    final SharedSessionContractImplementor session = rowProcessingState.getSession();
    final String entityName = concreteDescriptor.getEntityName();
    final EntityKey entityKey = new EntityKey(entityIdentifier, concreteDescriptor);
    final PersistenceContext persistenceContext = session.getPersistenceContextInternal();
    entityInstance = persistenceContext.getEntity(entityKey);
    if (entityInstance != null) {
        isInitialized = true;
        return;
    }
    Initializer initializer = rowProcessingState.getJdbcValuesSourceProcessingState().findInitializer(entityKey);
    if (initializer != null) {
        if (EntityLoadingLogger.DEBUG_ENABLED) {
            EntityLoadingLogger.LOGGER.debugf("(%s) Found an initializer for entity (%s) : %s", CONCRETE_NAME, toLoggableString(getNavigablePath(), entityIdentifier), entityIdentifier);
        }
        initializer.resolveInstance(rowProcessingState);
        entityInstance = initializer.getInitializedInstance();
        isInitialized = true;
        return;
    }
    final LoadingEntityEntry existingLoadingEntry = session.getPersistenceContext().getLoadContexts().findLoadingEntityEntry(entityKey);
    if (existingLoadingEntry != null) {
        if (EntityLoadingLogger.DEBUG_ENABLED) {
            EntityLoadingLogger.LOGGER.debugf("(%s) Found existing loading entry [%s] - using loading instance", CONCRETE_NAME, toLoggableString(getNavigablePath(), entityIdentifier));
        }
        this.entityInstance = existingLoadingEntry.getEntityInstance();
        if (existingLoadingEntry.getEntityInitializer() != this) {
            // the entity is already being loaded elsewhere
            if (EntityLoadingLogger.DEBUG_ENABLED) {
                EntityLoadingLogger.LOGGER.debugf("(%s) Entity [%s] being loaded by another initializer [%s] - skipping processing", CONCRETE_NAME, toLoggableString(getNavigablePath(), entityIdentifier), existingLoadingEntry.getEntityInitializer());
            }
            // EARLY EXIT!!!
            isInitialized = true;
            return;
        }
    }
    if (EntityLoadingLogger.DEBUG_ENABLED) {
        EntityLoadingLogger.LOGGER.debugf("(%s) Invoking session#internalLoad for entity (%s) : %s", CONCRETE_NAME, toLoggableString(getNavigablePath(), entityIdentifier), entityIdentifier);
    }
    entityInstance = session.internalLoad(entityName, entityIdentifier, true, referencedModelPart.isNullable() || referencedModelPart.isIgnoreNotFound());
    if (EntityLoadingLogger.DEBUG_ENABLED) {
        EntityLoadingLogger.LOGGER.debugf("(%s) Entity [%s] : %s has being loaded by session.internalLoad.", CONCRETE_NAME, toLoggableString(getNavigablePath(), entityIdentifier), entityIdentifier);
    }
    final boolean unwrapProxy = referencedModelPart.isUnwrapProxy() && isEnhancedForLazyLoading;
    if (entityInstance instanceof HibernateProxy) {
        ((HibernateProxy) entityInstance).getHibernateLazyInitializer().setUnwrap(unwrapProxy);
    }
    isInitialized = true;
}
Also used : EntityKey(org.hibernate.engine.spi.EntityKey) Initializer(org.hibernate.sql.results.graph.Initializer) EntityInitializer(org.hibernate.sql.results.graph.entity.EntityInitializer) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) LoggingHelper.toLoggableString(org.hibernate.internal.log.LoggingHelper.toLoggableString) HibernateProxy(org.hibernate.proxy.HibernateProxy) LoadingEntityEntry(org.hibernate.sql.results.graph.entity.LoadingEntityEntry)

Example 3 with LoadingEntityEntry

use of org.hibernate.sql.results.graph.entity.LoadingEntityEntry in project hibernate-orm by hibernate.

the class CollectionLoaderSubSelectFetch method load.

@Override
public PersistentCollection<?> load(Object triggerKey, SharedSessionContractImplementor session) {
    final CollectionKey collectionKey = new CollectionKey(attributeMapping.getCollectionDescriptor(), triggerKey);
    final SessionFactoryImplementor sessionFactory = session.getFactory();
    final JdbcServices jdbcServices = sessionFactory.getJdbcServices();
    final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment();
    final SqlAstTranslatorFactory sqlAstTranslatorFactory = jdbcEnvironment.getSqlAstTranslatorFactory();
    final PersistenceContext persistenceContext = session.getPersistenceContext();
    // try to find a registered SubselectFetch
    final PersistentCollection<?> collection = persistenceContext.getCollection(collectionKey);
    attributeMapping.getCollectionDescriptor().getCollectionType().getKeyOfOwner(collection.getOwner(), session);
    final EntityEntry ownerEntry = persistenceContext.getEntry(collection.getOwner());
    final BatchFetchQueue batchFetchQueue = persistenceContext.getBatchFetchQueue();
    final EntityKey triggerKeyOwnerKey = ownerEntry.getEntityKey();
    final SubselectFetch registeredFetch = batchFetchQueue.getSubselect(triggerKeyOwnerKey);
    List<PersistentCollection<?>> subSelectFetchedCollections = null;
    if (registeredFetch != null) {
        subSelectFetchedCollections = CollectionHelper.arrayList(registeredFetch.getResultingEntityKeys().size());
        // there was one, so we want to make sure to prepare the corresponding collection
        // reference for reading
        final Iterator<EntityKey> itr = registeredFetch.getResultingEntityKeys().iterator();
        while (itr.hasNext()) {
            final EntityKey key = itr.next();
            final PersistentCollection<?> containedCollection = persistenceContext.getCollection(new CollectionKey(attributeMapping.getCollectionDescriptor(), key.getIdentifier()));
            if (containedCollection != collection) {
                containedCollection.beginRead();
                containedCollection.beforeInitialize(getLoadable().getCollectionDescriptor(), -1);
                subSelectFetchedCollections.add(containedCollection);
            }
        }
    }
    final JdbcSelect jdbcSelect = sqlAstTranslatorFactory.buildSelectTranslator(sessionFactory, sqlAst).translate(this.subselect.getLoadingJdbcParameterBindings(), QueryOptions.NONE);
    final SubselectFetch.RegistrationHandler subSelectFetchableKeysHandler = SubselectFetch.createRegistrationHandler(batchFetchQueue, sqlAst, this.subselect.getLoadingJdbcParameters(), this.subselect.getLoadingJdbcParameterBindings());
    jdbcServices.getJdbcSelectExecutor().list(jdbcSelect, this.subselect.getLoadingJdbcParameterBindings(), new ExecutionContext() {

        @Override
        public SharedSessionContractImplementor getSession() {
            return session;
        }

        @Override
        public QueryOptions getQueryOptions() {
            return QueryOptions.NONE;
        }

        @Override
        public String getQueryIdentifier(String sql) {
            return sql;
        }

        @Override
        public void registerLoadingEntityEntry(EntityKey entityKey, LoadingEntityEntry entry) {
            subSelectFetchableKeysHandler.addKey(entityKey, entry);
        }

        @Override
        public QueryParameterBindings getQueryParameterBindings() {
            return QueryParameterBindings.NO_PARAM_BINDINGS;
        }

        @Override
        public Callback getCallback() {
            return null;
        }
    }, RowTransformerPassThruImpl.instance(), ListResultsConsumer.UniqueSemantic.FILTER);
    if (subSelectFetchedCollections != null && !subSelectFetchedCollections.isEmpty()) {
        subSelectFetchedCollections.forEach(c -> {
            if (c.wasInitialized()) {
                return;
            }
            c.initializeEmptyCollection(getLoadable().getCollectionDescriptor());
            ResultsHelper.finalizeCollectionLoading(persistenceContext, getLoadable().getCollectionDescriptor(), c, c.getKey(), true);
        });
        subSelectFetchedCollections.clear();
    }
    return collection;
}
Also used : JdbcSelect(org.hibernate.sql.exec.spi.JdbcSelect) SubselectFetch(org.hibernate.engine.spi.SubselectFetch) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) CollectionKey(org.hibernate.engine.spi.CollectionKey) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) QueryOptions(org.hibernate.query.spi.QueryOptions) BatchFetchQueue(org.hibernate.engine.spi.BatchFetchQueue) SqlAstTranslatorFactory(org.hibernate.sql.ast.SqlAstTranslatorFactory) EntityKey(org.hibernate.engine.spi.EntityKey) PersistentCollection(org.hibernate.collection.spi.PersistentCollection) LoadingEntityEntry(org.hibernate.sql.results.graph.entity.LoadingEntityEntry) EntityEntry(org.hibernate.engine.spi.EntityEntry) ExecutionContext(org.hibernate.sql.exec.spi.ExecutionContext) Callback(org.hibernate.sql.exec.spi.Callback) QueryParameterBindings(org.hibernate.query.spi.QueryParameterBindings) LoadingEntityEntry(org.hibernate.sql.results.graph.entity.LoadingEntityEntry)

Example 4 with LoadingEntityEntry

use of org.hibernate.sql.results.graph.entity.LoadingEntityEntry in project hibernate-orm by hibernate.

the class CollectionLoaderSingleKey method load.

@Override
public PersistentCollection<?> load(Object key, SharedSessionContractImplementor session) {
    final CollectionKey collectionKey = new CollectionKey(attributeMapping.getCollectionDescriptor(), key);
    final SessionFactoryImplementor sessionFactory = session.getFactory();
    final JdbcServices jdbcServices = sessionFactory.getJdbcServices();
    final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment();
    final SqlAstTranslatorFactory sqlAstTranslatorFactory = jdbcEnvironment.getSqlAstTranslatorFactory();
    final JdbcParameterBindings jdbcParameterBindings = new JdbcParameterBindingsImpl(keyJdbcCount);
    int offset = jdbcParameterBindings.registerParametersForEachJdbcValue(key, Clause.WHERE, attributeMapping.getKeyDescriptor(), jdbcParameters, session);
    assert offset == jdbcParameters.size();
    final JdbcSelect jdbcSelect = sqlAstTranslatorFactory.buildSelectTranslator(sessionFactory, sqlAst).translate(jdbcParameterBindings, QueryOptions.NONE);
    final SubselectFetch.RegistrationHandler subSelectFetchableKeysHandler = SubselectFetch.createRegistrationHandler(session.getPersistenceContext().getBatchFetchQueue(), sqlAst, jdbcParameters, jdbcParameterBindings);
    jdbcServices.getJdbcSelectExecutor().list(jdbcSelect, jdbcParameterBindings, new ExecutionContext() {

        @Override
        public SharedSessionContractImplementor getSession() {
            return session;
        }

        @Override
        public CollectionKey getCollectionKey() {
            return collectionKey;
        }

        @Override
        public void registerLoadingEntityEntry(EntityKey entityKey, LoadingEntityEntry entry) {
            subSelectFetchableKeysHandler.addKey(entityKey, entry);
        }

        @Override
        public QueryOptions getQueryOptions() {
            return QueryOptions.NONE;
        }

        @Override
        public String getQueryIdentifier(String sql) {
            return sql;
        }

        @Override
        public QueryParameterBindings getQueryParameterBindings() {
            return QueryParameterBindings.NO_PARAM_BINDINGS;
        }

        @Override
        public Callback getCallback() {
            return null;
        }
    }, RowTransformerPassThruImpl.instance(), ListResultsConsumer.UniqueSemantic.FILTER);
    return session.getPersistenceContext().getCollection(collectionKey);
}
Also used : JdbcSelect(org.hibernate.sql.exec.spi.JdbcSelect) SubselectFetch(org.hibernate.engine.spi.SubselectFetch) JdbcParameterBindingsImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) CollectionKey(org.hibernate.engine.spi.CollectionKey) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) QueryOptions(org.hibernate.query.spi.QueryOptions) SqlAstTranslatorFactory(org.hibernate.sql.ast.SqlAstTranslatorFactory) EntityKey(org.hibernate.engine.spi.EntityKey) ExecutionContext(org.hibernate.sql.exec.spi.ExecutionContext) Callback(org.hibernate.sql.exec.spi.Callback) QueryParameterBindings(org.hibernate.query.spi.QueryParameterBindings) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings) LoadingEntityEntry(org.hibernate.sql.results.graph.entity.LoadingEntityEntry)

Example 5 with LoadingEntityEntry

use of org.hibernate.sql.results.graph.entity.LoadingEntityEntry in project hibernate-orm by hibernate.

the class StandardEntityInstanceResolver method resolveEntityInstance.

public static Object resolveEntityInstance(EntityKey entityKey, boolean eager, SharedSessionContractImplementor session) {
    // First, look for it in the PC as a managed entity
    final Object managedEntity = session.getPersistenceContext().getEntity(entityKey);
    if (managedEntity != null) {
        // todo (6.0) : check status?  aka, return deleted entities?
        return managedEntity;
    }
    // Next, check currently loading entities
    final LoadingEntityEntry loadingEntry = session.getPersistenceContext().getLoadContexts().findLoadingEntityEntry(entityKey);
    if (loadingEntry != null) {
        return loadingEntry.getEntityInstance();
    }
    // Lastly, try to load from database
    return session.internalLoad(entityKey.getEntityName(), entityKey.getIdentifier(), eager, false);
}
Also used : LoadingEntityEntry(org.hibernate.sql.results.graph.entity.LoadingEntityEntry)

Aggregations

LoadingEntityEntry (org.hibernate.sql.results.graph.entity.LoadingEntityEntry)8 EntityKey (org.hibernate.engine.spi.EntityKey)7 SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)6 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)4 JdbcServices (org.hibernate.engine.jdbc.spi.JdbcServices)4 PersistenceContext (org.hibernate.engine.spi.PersistenceContext)4 SubselectFetch (org.hibernate.engine.spi.SubselectFetch)4 QueryOptions (org.hibernate.query.spi.QueryOptions)4 QueryParameterBindings (org.hibernate.query.spi.QueryParameterBindings)4 SqlAstTranslatorFactory (org.hibernate.sql.ast.SqlAstTranslatorFactory)4 Callback (org.hibernate.sql.exec.spi.Callback)4 ExecutionContext (org.hibernate.sql.exec.spi.ExecutionContext)4 JdbcSelect (org.hibernate.sql.exec.spi.JdbcSelect)4 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)3 JdbcParameterBindingsImpl (org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl)3 JdbcParameterBindings (org.hibernate.sql.exec.spi.JdbcParameterBindings)3 CollectionKey (org.hibernate.engine.spi.CollectionKey)2 HibernateProxy (org.hibernate.proxy.HibernateProxy)2 JdbcParameter (org.hibernate.sql.ast.tree.expression.JdbcParameter)2 SelectStatement (org.hibernate.sql.ast.tree.select.SelectStatement)2