Search in sources :

Example 16 with JdbcSelect

use of org.hibernate.sql.exec.spi.JdbcSelect in project hibernate-orm by hibernate.

the class AbstractNaturalIdLoader method selectByNaturalId.

/**
 * Perform a select, restricted by natural-id, based on `domainResultProducer` and `fetchProcessor`
 */
protected <L> L selectByNaturalId(Object bindValue, NaturalIdLoadOptions options, BiFunction<TableGroup, LoaderSqlAstCreationState, DomainResult<?>> domainResultProducer, LoaderSqlAstCreationState.FetchProcessor fetchProcessor, Function<Boolean, Long> statementStartHandler, BiConsumer<Object, Long> statementCompletionHandler, SharedSessionContractImplementor session) {
    final SessionFactoryImplementor sessionFactory = session.getFactory();
    final JdbcServices jdbcServices = sessionFactory.getJdbcServices();
    final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment();
    final SqlAstTranslatorFactory sqlAstTranslatorFactory = jdbcEnvironment.getSqlAstTranslatorFactory();
    final LockOptions lockOptions;
    if (options.getLockOptions() != null) {
        lockOptions = options.getLockOptions();
    } else {
        lockOptions = LockOptions.NONE;
    }
    final NavigablePath entityPath = new NavigablePath(entityDescriptor.getRootPathName());
    final QuerySpec rootQuerySpec = new QuerySpec(true);
    final LoaderSqlAstCreationState sqlAstCreationState = new LoaderSqlAstCreationState(rootQuerySpec, new SqlAliasBaseManager(), new SimpleFromClauseAccessImpl(), lockOptions, fetchProcessor, true, sessionFactory);
    final TableGroup rootTableGroup = entityDescriptor.createRootTableGroup(true, entityPath, null, () -> rootQuerySpec::applyPredicate, sqlAstCreationState, sessionFactory);
    rootQuerySpec.getFromClause().addRoot(rootTableGroup);
    sqlAstCreationState.getFromClauseAccess().registerTableGroup(entityPath, rootTableGroup);
    final DomainResult<?> domainResult = domainResultProducer.apply(rootTableGroup, sqlAstCreationState);
    final SelectStatement sqlSelect = new SelectStatement(rootQuerySpec, Collections.singletonList(domainResult));
    final List<JdbcParameter> jdbcParameters = new ArrayList<>(naturalIdMapping.getJdbcTypeCount());
    final JdbcParameterBindings jdbcParamBindings = new JdbcParameterBindingsImpl(jdbcParameters.size());
    applyNaturalIdRestriction(bindValue, rootTableGroup, rootQuerySpec::applyPredicate, (jdbcParameter, jdbcParameterBinding) -> {
        jdbcParameters.add(jdbcParameter);
        jdbcParamBindings.addBinding(jdbcParameter, jdbcParameterBinding);
    }, sqlAstCreationState, session);
    final QueryOptions queryOptions = new SimpleQueryOptions(lockOptions, false);
    final JdbcSelect jdbcSelect = sqlAstTranslatorFactory.buildSelectTranslator(sessionFactory, sqlSelect).translate(jdbcParamBindings, queryOptions);
    final StatisticsImplementor statistics = sessionFactory.getStatistics();
    final Long startToken = statementStartHandler.apply(statistics.isStatisticsEnabled());
    // noinspection unchecked
    final List<L> results = session.getFactory().getJdbcServices().getJdbcSelectExecutor().list(jdbcSelect, jdbcParamBindings, new ExecutionContext() {

        private final Callback callback = new CallbackImpl();

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

        @Override
        public QueryOptions getQueryOptions() {
            return queryOptions;
        }

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

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

        @Override
        public Callback getCallback() {
            return callback;
        }
    }, row -> (L) row[0], ListResultsConsumer.UniqueSemantic.FILTER);
    if (results.size() > 1) {
        throw new HibernateException(String.format("Loading by natural-id returned more that one row : %s", entityDescriptor.getEntityName()));
    }
    final L result;
    if (results.isEmpty()) {
        result = null;
    } else {
        result = results.get(0);
    }
    statementCompletionHandler.accept(result, startToken);
    return result;
}
Also used : LockOptions(org.hibernate.LockOptions) NavigablePath(org.hibernate.query.spi.NavigablePath) CallbackImpl(org.hibernate.sql.exec.internal.CallbackImpl) ArrayList(java.util.ArrayList) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) SqlAliasBaseManager(org.hibernate.sql.ast.spi.SqlAliasBaseManager) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) SimpleQueryOptions(org.hibernate.query.internal.SimpleQueryOptions) QueryOptions(org.hibernate.query.spi.QueryOptions) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) SimpleQueryOptions(org.hibernate.query.internal.SimpleQueryOptions) QueryParameterBindings(org.hibernate.query.spi.QueryParameterBindings) JdbcSelect(org.hibernate.sql.exec.spi.JdbcSelect) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) JdbcParameterBindingsImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl) HibernateException(org.hibernate.HibernateException) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) SimpleFromClauseAccessImpl(org.hibernate.sql.ast.spi.SimpleFromClauseAccessImpl) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) StatisticsImplementor(org.hibernate.stat.spi.StatisticsImplementor) SqlAstTranslatorFactory(org.hibernate.sql.ast.SqlAstTranslatorFactory) ExecutionContext(org.hibernate.sql.exec.spi.ExecutionContext) Callback(org.hibernate.sql.exec.spi.Callback) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings)

Example 17 with JdbcSelect

use of org.hibernate.sql.exec.spi.JdbcSelect in project hibernate-orm by hibernate.

the class SingleUniqueKeyEntityLoaderStandard method load.

@Override
public T load(Object ukValue, LockOptions lockOptions, Boolean readOnly, 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.emptyList(), 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() {

        private final Callback callback = new CallbackImpl();

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

        @Override
        public QueryOptions getQueryOptions() {
            return new QueryOptionsAdapter() {

                @Override
                public Boolean isReadOnly() {
                    return readOnly;
                }
            };
        }

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

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

        @Override
        public Callback getCallback() {
            return callback;
        }
    }, row -> row[0], ListResultsConsumer.UniqueSemantic.FILTER);
    switch(list.size()) {
        case 0:
            return null;
        case 1:
            // noinspection unchecked
            return (T) list.get(0);
    }
    throw new HibernateException("More than one row with the given identifier was found: " + ukValue + ", for class: " + entityDescriptor.getEntityName());
}
Also used : CallbackImpl(org.hibernate.sql.exec.internal.CallbackImpl) ArrayList(java.util.ArrayList) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) QueryOptions(org.hibernate.query.spi.QueryOptions) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) QueryParameterBindings(org.hibernate.query.spi.QueryParameterBindings) JdbcSelect(org.hibernate.sql.exec.spi.JdbcSelect) JdbcParameterBindingsImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl) HibernateException(org.hibernate.HibernateException) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) SqlAstTranslatorFactory(org.hibernate.sql.ast.SqlAstTranslatorFactory) ExecutionContext(org.hibernate.sql.exec.spi.ExecutionContext) Callback(org.hibernate.sql.exec.spi.Callback) QueryOptionsAdapter(org.hibernate.query.spi.QueryOptionsAdapter) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings)

Example 18 with JdbcSelect

use of org.hibernate.sql.exec.spi.JdbcSelect in project hibernate-orm by hibernate.

the class CollectionLoaderBatchKey method batchLoad.

private void batchLoad(Object[] batchIds, int numberOfIds, SharedSessionContractImplementor session) {
    if (log.isDebugEnabled()) {
        log.debugf("Batch loading collection [%s] : %s", getLoadable().getCollectionDescriptor().getRole(), batchIds);
    }
    int smallBatchStart = 0;
    int smallBatchLength = Math.min(numberOfIds, batchSize);
    while (true) {
        final List<JdbcParameter> jdbcParameters;
        final SelectStatement sqlAst;
        if (smallBatchLength == batchSize) {
            jdbcParameters = this.batchSizeJdbcParameters;
            sqlAst = this.batchSizeSqlAst;
        } else {
            jdbcParameters = new ArrayList<>();
            sqlAst = LoaderSelectBuilder.createSelect(getLoadable(), // null here means to select everything
            null, getLoadable().getKeyDescriptor(), null, numberOfIds, session.getLoadQueryInfluencers(), LockOptions.NONE, 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 JdbcSelect jdbcSelect = sqlAstTranslatorFactory.buildSelectTranslator(sessionFactory, sqlAst).translate(null, QueryOptions.NONE);
        final JdbcParameterBindings jdbcParameterBindings = new JdbcParameterBindingsImpl(keyJdbcCount * smallBatchLength);
        jdbcSelect.bindFilterJdbcParameters(jdbcParameterBindings);
        int offset = 0;
        for (int i = smallBatchStart; i < smallBatchStart + smallBatchLength; i++) {
            offset += jdbcParameterBindings.registerParametersForEachJdbcValue(batchIds[i], Clause.WHERE, offset, getLoadable().getKeyDescriptor(), jdbcParameters, session);
        }
        assert offset == jdbcParameters.size();
        final SubselectFetch.RegistrationHandler subSelectFetchableKeysHandler = SubselectFetch.createRegistrationHandler(session.getPersistenceContext().getBatchFetchQueue(), sqlAst, Collections.emptyList(), jdbcParameterBindings);
        jdbcServices.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 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);
        // prepare for the next round...
        smallBatchStart += smallBatchLength;
        if (smallBatchStart >= numberOfIds) {
            break;
        }
        smallBatchLength = Math.min(numberOfIds - smallBatchStart, batchSize);
    }
}
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) 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) 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 19 with JdbcSelect

use of org.hibernate.sql.exec.spi.JdbcSelect in project hibernate-orm by hibernate.

the class GeneratedValuesProcessor method processGeneratedValues.

public void processGeneratedValues(Object entity, Object id, Object[] state, SharedSessionContractImplementor session) {
    if (selectStatement == null) {
        return;
    }
    final JdbcServices jdbcServices = sessionFactory.getJdbcServices();
    final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment();
    final SqlAstTranslatorFactory sqlAstTranslatorFactory = jdbcEnvironment.getSqlAstTranslatorFactory();
    final JdbcParameterBindings jdbcParamBindings = new JdbcParameterBindingsImpl(jdbcParameters.size());
    int offset = jdbcParamBindings.registerParametersForEachJdbcValue(id, Clause.WHERE, entityDescriptor.getIdentifierMapping(), jdbcParameters, session);
    assert offset == jdbcParameters.size();
    final JdbcSelect jdbcSelect = sqlAstTranslatorFactory.buildSelectTranslator(sessionFactory, selectStatement).translate(jdbcParamBindings, QueryOptions.NONE);
    final List<Object[]> results = session.getFactory().getJdbcServices().getJdbcSelectExecutor().list(jdbcSelect, jdbcParamBindings, 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 UnsupportedMappingException("Follow-on locking not supported yet");
        }
    }, (row) -> row, ListResultsConsumer.UniqueSemantic.FILTER);
    assert results.size() == 1;
    final Object[] dbSelectionResults = results.get(0);
    for (int i = 0; i < valueDescriptors.size(); i++) {
        final GeneratedValueDescriptor descriptor = valueDescriptors.get(i);
        final Object generatedValue = descriptor.resolver.resolveGeneratedValue(dbSelectionResults, entity, session);
        state[descriptor.attribute.getStateArrayPosition()] = generatedValue;
        descriptor.attribute.getAttributeMetadataAccess().resolveAttributeMetadata(entityDescriptor).getPropertyAccess().getSetter().set(entity, generatedValue);
    }
}
Also used : JdbcSelect(org.hibernate.sql.exec.spi.JdbcSelect) JdbcParameterBindingsImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl) 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) UnsupportedMappingException(org.hibernate.metamodel.UnsupportedMappingException) 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 20 with JdbcSelect

use of org.hibernate.sql.exec.spi.JdbcSelect in project hibernate-orm by hibernate.

the class NativeSelectQueryPlanImpl method performScroll.

@Override
public ScrollableResultsImplementor<R> performScroll(ScrollMode scrollMode, DomainQueryExecutionContext executionContext) {
    if (executionContext.getQueryOptions().getEffectiveLimit().getMaxRowsJpa() == 0) {
        return EmptyScrollableResults.INSTANCE;
    }
    final List<JdbcParameterBinder> jdbcParameterBinders;
    final JdbcParameterBindings jdbcParameterBindings;
    final QueryParameterBindings queryParameterBindings = executionContext.getQueryParameterBindings();
    if (parameterList == null || parameterList.isEmpty()) {
        jdbcParameterBinders = Collections.emptyList();
        jdbcParameterBindings = JdbcParameterBindings.NO_BINDINGS;
    } else {
        jdbcParameterBinders = new ArrayList<>(parameterList.size());
        jdbcParameterBindings = new JdbcParameterBindingsImpl(parameterList.size());
        jdbcParameterBindings.registerNativeQueryParameters(queryParameterBindings, parameterList, jdbcParameterBinders, executionContext.getSession().getFactory());
    }
    final JdbcSelect jdbcSelect = new JdbcSelect(sql, jdbcParameterBinders, resultSetMapping, affectedTableNames, Collections.emptySet());
    final JdbcSelectExecutor executor = JdbcSelectExecutorStandardImpl.INSTANCE;
    // return jdbcServices.getJdbcSelectExecutor().scroll(
    return executor.scroll(jdbcSelect, scrollMode, jdbcParameterBindings, SqmJdbcExecutionContextAdapter.usingLockingAndPaging(executionContext), null);
}
Also used : JdbcSelect(org.hibernate.sql.exec.spi.JdbcSelect) JdbcParameterBindingsImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl) QueryParameterBindings(org.hibernate.query.spi.QueryParameterBindings) JdbcParameterBinder(org.hibernate.sql.exec.spi.JdbcParameterBinder) JdbcSelectExecutor(org.hibernate.sql.exec.spi.JdbcSelectExecutor) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings)

Aggregations

JdbcSelect (org.hibernate.sql.exec.spi.JdbcSelect)21 JdbcParameterBindings (org.hibernate.sql.exec.spi.JdbcParameterBindings)17 JdbcServices (org.hibernate.engine.jdbc.spi.JdbcServices)16 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)14 SelectStatement (org.hibernate.sql.ast.tree.select.SelectStatement)14 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)13 JdbcParameterBindingsImpl (org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl)13 SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)12 QueryParameterBindings (org.hibernate.query.spi.QueryParameterBindings)12 SqlAstTranslatorFactory (org.hibernate.sql.ast.SqlAstTranslatorFactory)12 ArrayList (java.util.ArrayList)11 ExecutionContext (org.hibernate.sql.exec.spi.ExecutionContext)11 QueryOptions (org.hibernate.query.spi.QueryOptions)10 Callback (org.hibernate.sql.exec.spi.Callback)10 JdbcParameter (org.hibernate.sql.ast.tree.expression.JdbcParameter)9 TableGroup (org.hibernate.sql.ast.tree.from.TableGroup)6 List (java.util.List)5 EntityKey (org.hibernate.engine.spi.EntityKey)5 SubselectFetch (org.hibernate.engine.spi.SubselectFetch)5 MappingModelExpressible (org.hibernate.metamodel.mapping.MappingModelExpressible)5