Search in sources :

Example 1 with SqlAstTranslatorFactory

use of org.hibernate.sql.ast.SqlAstTranslatorFactory in project hibernate-orm by hibernate.

the class SingleIdEntityLoaderDynamicBatch method load.

@Override
public T load(Object pkValue, Object entityInstance, LockOptions lockOptions, Boolean readOnly, SharedSessionContractImplementor session) {
    final Object[] batchIds = session.getPersistenceContextInternal().getBatchFetchQueue().getBatchLoadableEntityIds(getLoadable(), pkValue, maxBatchSize);
    final int numberOfIds = ArrayHelper.countNonNull(batchIds);
    if (numberOfIds <= 1) {
        initializeSingleIdLoaderIfNeeded(session);
        final T result = singleIdLoader.load(pkValue, entityInstance, lockOptions, readOnly, session);
        if (result == null) {
            // There was no entity with the specified ID. Make sure the EntityKey does not remain
            // in the batch to avoid including it in future batches that get executed.
            BatchFetchQueueHelper.removeBatchLoadableEntityKey(pkValue, getLoadable(), session);
        }
        return result;
    }
    final Object[] idsToLoad = new Object[numberOfIds];
    System.arraycopy(batchIds, 0, idsToLoad, 0, numberOfIds);
    if (log.isDebugEnabled()) {
        log.debugf("Batch loading entity [%s] : %s", getLoadable().getEntityName(), idsToLoad);
    }
    final List<JdbcParameter> jdbcParameters = new ArrayList<>();
    final SelectStatement sqlAst = LoaderSelectBuilder.createSelect(getLoadable(), // null here means to select everything
    null, getLoadable().getIdentifierMapping(), null, numberOfIds, session.getLoadQueryInfluencers(), lockOptions, jdbcParameters::add, session.getFactory());
    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(getLoadable().getIdentifierMapping().getJdbcTypeCount());
    int offset = 0;
    for (int i = 0; i < numberOfIds; i++) {
        offset += jdbcParameterBindings.registerParametersForEachJdbcValue(idsToLoad[i], Clause.WHERE, offset, getLoadable().getIdentifierMapping(), 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);
    JdbcSelectExecutorStandardImpl.INSTANCE.list(jdbcSelect, jdbcParameterBindings, getExecutionContext(pkValue, entityInstance, readOnly, lockOptions, session, subSelectFetchableKeysHandler), RowTransformerPassThruImpl.instance(), ListResultsConsumer.UniqueSemantic.FILTER);
    // noinspection ForLoopReplaceableByForEach
    for (int i = 0; i < idsToLoad.length; i++) {
        final Object id = idsToLoad[i];
        // found or not, remove the key from the batch-fetch queye
        BatchFetchQueueHelper.removeBatchLoadableEntityKey(id, getLoadable(), session);
    }
    final EntityKey entityKey = session.generateEntityKey(pkValue, getLoadable().getEntityPersister());
    // noinspection unchecked
    return (T) session.getPersistenceContext().getEntity(entityKey);
}
Also used : JdbcSelect(org.hibernate.sql.exec.spi.JdbcSelect) SubselectFetch(org.hibernate.engine.spi.SubselectFetch) JdbcParameterBindingsImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) ArrayList(java.util.ArrayList) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) SqlAstTranslatorFactory(org.hibernate.sql.ast.SqlAstTranslatorFactory) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) EntityKey(org.hibernate.engine.spi.EntityKey) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings)

Example 2 with SqlAstTranslatorFactory

use of org.hibernate.sql.ast.SqlAstTranslatorFactory in project hibernate-orm by hibernate.

the class SingleUniqueKeyEntityLoaderStandard method resolveId.

@Override
public Object resolveId(Object ukValue, SharedSessionContractImplementor session) {
    final SessionFactoryImplementor sessionFactory = session.getFactory();
    // todo (6.0) : cache the SQL AST and JdbcParameters
    final List<JdbcParameter> jdbcParameters = new ArrayList<>();
    final SelectStatement sqlAst = LoaderSelectBuilder.createSelectByUniqueKey(entityDescriptor, Collections.singletonList(entityDescriptor.getIdentifierMapping()), uniqueKeyAttribute, null, 1, LoadQueryInfluencers.NONE, LockOptions.NONE, jdbcParameters::add, sessionFactory);
    final JdbcServices jdbcServices = sessionFactory.getJdbcServices();
    final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment();
    final SqlAstTranslatorFactory sqlAstTranslatorFactory = jdbcEnvironment.getSqlAstTranslatorFactory();
    final JdbcParameterBindings jdbcParameterBindings = new JdbcParameterBindingsImpl(jdbcParameters.size());
    int offset = jdbcParameterBindings.registerParametersForEachJdbcValue(ukValue, Clause.WHERE, uniqueKeyAttribute, jdbcParameters, session);
    assert offset == jdbcParameters.size();
    final JdbcSelect jdbcSelect = sqlAstTranslatorFactory.buildSelectTranslator(sessionFactory, sqlAst).translate(jdbcParameterBindings, QueryOptions.NONE);
    final List<Object> list = sessionFactory.getJdbcServices().getJdbcSelectExecutor().list(jdbcSelect, jdbcParameterBindings, 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 QueryParameterBindings getQueryParameterBindings() {
            return QueryParameterBindings.NO_PARAM_BINDINGS;
        }

        @Override
        public Callback getCallback() {
            throw new UnsupportedOperationException("Follow-on locking not supported yet");
        }
    }, row -> row[0], ListResultsConsumer.UniqueSemantic.FILTER);
    assert list.size() == 1;
    return list.get(0);
}
Also used : JdbcSelect(org.hibernate.sql.exec.spi.JdbcSelect) JdbcParameterBindingsImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) ArrayList(java.util.ArrayList) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) 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) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) 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)

Example 3 with SqlAstTranslatorFactory

use of org.hibernate.sql.ast.SqlAstTranslatorFactory in project hibernate-orm by hibernate.

the class ConcreteSqmSelectQueryPlan method buildCacheableSqmInterpretation.

private static CacheableSqmInterpretation buildCacheableSqmInterpretation(SqmSelectStatement<?> sqm, DomainParameterXref domainParameterXref, DomainQueryExecutionContext executionContext) {
    final SharedSessionContractImplementor session = executionContext.getSession();
    final SessionFactoryImplementor sessionFactory = session.getFactory();
    final QueryEngine queryEngine = sessionFactory.getQueryEngine();
    final SqmTranslatorFactory sqmTranslatorFactory = queryEngine.getSqmTranslatorFactory();
    final SqmTranslator<SelectStatement> sqmConverter = sqmTranslatorFactory.createSelectTranslator(sqm, executionContext.getQueryOptions(), domainParameterXref, executionContext.getQueryParameterBindings(), executionContext.getSession().getLoadQueryInfluencers(), sessionFactory, true);
    // tableGroupAccess = sqmConverter.getFromClauseAccess();
    final SqmTranslation<SelectStatement> sqmInterpretation = sqmConverter.translate();
    final FromClauseAccess tableGroupAccess = sqmConverter.getFromClauseAccess();
    final JdbcServices jdbcServices = sessionFactory.getJdbcServices();
    final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment();
    final SqlAstTranslatorFactory sqlAstTranslatorFactory = jdbcEnvironment.getSqlAstTranslatorFactory();
    final SqlAstTranslator<JdbcSelect> selectTranslator = sqlAstTranslatorFactory.buildSelectTranslator(sessionFactory, sqmInterpretation.getSqlAst());
    final Map<QueryParameterImplementor<?>, Map<SqmParameter<?>, List<List<JdbcParameter>>>> jdbcParamsXref = SqmUtil.generateJdbcParamsXref(domainParameterXref, sqmInterpretation::getJdbcParamsBySqmParam);
    final JdbcParameterBindings jdbcParameterBindings = SqmUtil.createJdbcParameterBindings(executionContext.getQueryParameterBindings(), domainParameterXref, jdbcParamsXref, session.getFactory().getRuntimeMetamodels().getMappingMetamodel(), tableGroupAccess::findTableGroup, new SqmParameterMappingModelResolutionAccess() {

        @Override
        @SuppressWarnings("unchecked")
        public <T> MappingModelExpressible<T> getResolvedMappingModelType(SqmParameter<T> parameter) {
            return (MappingModelExpressible<T>) sqmInterpretation.getSqmParameterMappingModelTypeResolutions().get(parameter);
        }
    }, session);
    final JdbcSelect jdbcSelect = selectTranslator.translate(jdbcParameterBindings, executionContext.getQueryOptions());
    return new CacheableSqmInterpretation(sqmInterpretation.getSqlAst(), jdbcSelect, tableGroupAccess, jdbcParamsXref, sqmInterpretation.getSqmParameterMappingModelTypeResolutions(), jdbcParameterBindings);
}
Also used : MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) QueryEngine(org.hibernate.query.spi.QueryEngine) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) ArrayList(java.util.ArrayList) List(java.util.List) SqmTranslatorFactory(org.hibernate.query.sqm.sql.SqmTranslatorFactory) JdbcSelect(org.hibernate.sql.exec.spi.JdbcSelect) SqmParameterMappingModelResolutionAccess(org.hibernate.query.sqm.spi.SqmParameterMappingModelResolutionAccess) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) SqlAstTranslatorFactory(org.hibernate.sql.ast.SqlAstTranslatorFactory) FromClauseAccess(org.hibernate.sql.ast.spi.FromClauseAccess) QueryParameterImplementor(org.hibernate.query.spi.QueryParameterImplementor) Map(java.util.Map) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings)

Example 4 with SqlAstTranslatorFactory

use of org.hibernate.sql.ast.SqlAstTranslatorFactory in project hibernate-orm by hibernate.

the class CollectionElementLoaderByIndex method load.

public Object load(Object key, Object index, SharedSessionContractImplementor session) {
    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);
    offset += jdbcParameterBindings.registerParametersForEachJdbcValue(incrementIndexByBase(index), Clause.WHERE, offset, attributeMapping.getIndexDescriptor(), jdbcParameters, session);
    assert offset == jdbcParameters.size();
    final JdbcSelect jdbcSelect = sqlAstTranslatorFactory.buildSelectTranslator(sessionFactory, sqlAst).translate(jdbcParameterBindings, QueryOptions.NONE);
    List<Object> list = jdbcServices.getJdbcSelectExecutor().list(jdbcSelect, jdbcParameterBindings, new ExecutionContext() {

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

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

        @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);
    if (list.isEmpty()) {
        return null;
    }
    return list.get(0);
}
Also used : JdbcSelect(org.hibernate.sql.exec.spi.JdbcSelect) JdbcParameterBindingsImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) CollectionKey(org.hibernate.engine.spi.CollectionKey) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) QueryOptions(org.hibernate.query.spi.QueryOptions) SqlAstTranslatorFactory(org.hibernate.sql.ast.SqlAstTranslatorFactory) 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)

Example 5 with SqlAstTranslatorFactory

use of org.hibernate.sql.ast.SqlAstTranslatorFactory 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)

Aggregations

JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)13 JdbcServices (org.hibernate.engine.jdbc.spi.JdbcServices)13 SqlAstTranslatorFactory (org.hibernate.sql.ast.SqlAstTranslatorFactory)13 JdbcSelect (org.hibernate.sql.exec.spi.JdbcSelect)12 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)11 SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)11 JdbcParameterBindings (org.hibernate.sql.exec.spi.JdbcParameterBindings)11 QueryOptions (org.hibernate.query.spi.QueryOptions)10 QueryParameterBindings (org.hibernate.query.spi.QueryParameterBindings)10 JdbcParameterBindingsImpl (org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl)10 Callback (org.hibernate.sql.exec.spi.Callback)10 ExecutionContext (org.hibernate.sql.exec.spi.ExecutionContext)10 SelectStatement (org.hibernate.sql.ast.tree.select.SelectStatement)8 ArrayList (java.util.ArrayList)7 JdbcParameter (org.hibernate.sql.ast.tree.expression.JdbcParameter)7 EntityKey (org.hibernate.engine.spi.EntityKey)5 SubselectFetch (org.hibernate.engine.spi.SubselectFetch)5 LoadingEntityEntry (org.hibernate.sql.results.graph.entity.LoadingEntityEntry)4 HibernateException (org.hibernate.HibernateException)3 CollectionKey (org.hibernate.engine.spi.CollectionKey)3