Search in sources :

Example 11 with JdbcParameterBindings

use of org.hibernate.sql.exec.spi.JdbcParameterBindings 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;
        }
    }, RowTransformerStandardImpl.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 12 with JdbcParameterBindings

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

the class DatabaseSnapshotExecutor method loadDatabaseSnapshot.

Object[] loadDatabaseSnapshot(Object id, SharedSessionContractImplementor session) {
    if (log.isTraceEnabled()) {
        log.tracef("Getting current persistent state for `%s#%s`", entityDescriptor.getEntityName(), id);
    }
    final JdbcParameterBindings jdbcParameterBindings = new JdbcParameterBindingsImpl(entityDescriptor.getIdentifierMapping().getJdbcTypeCount());
    int offset = jdbcParameterBindings.registerParametersForEachJdbcValue(id, Clause.WHERE, entityDescriptor.getIdentifierMapping(), jdbcParameters, session);
    assert offset == jdbcParameters.size();
    final List<?> list = session.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() {
            return null;
        }
    }, RowTransformerDatabaseSnapshotImpl.instance(), ListResultsConsumer.UniqueSemantic.FILTER);
    final int size = list.size();
    assert size <= 1;
    if (size == 0) {
        return null;
    } else {
        final Object[] entitySnapshot = (Object[]) list.get(0);
        // So we must exclude it from the array
        if (entitySnapshot.length == 1) {
            return ArrayHelper.EMPTY_OBJECT_ARRAY;
        } else {
            final Object[] state = new Object[entitySnapshot.length - 1];
            System.arraycopy(entitySnapshot, 1, state, 0, state.length);
            return state;
        }
    }
}
Also used : JdbcParameterBindingsImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) QueryOptions(org.hibernate.query.spi.QueryOptions) 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 13 with JdbcParameterBindings

use of org.hibernate.sql.exec.spi.JdbcParameterBindings 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);
    session.getJdbcServices().getJdbcSelectExecutor().list(jdbcSelect, jdbcParameterBindings, getExecutionContext(pkValue, entityInstance, readOnly, lockOptions, session, subSelectFetchableKeysHandler), RowTransformerStandardImpl.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 14 with JdbcParameterBindings

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

the class SimpleDeleteQueryPlan method executeUpdate.

@Override
public int executeUpdate(DomainQueryExecutionContext executionContext) {
    BulkOperationCleanupAction.schedule(executionContext.getSession(), sqmDelete);
    final SharedSessionContractImplementor session = executionContext.getSession();
    final SessionFactoryImplementor factory = session.getFactory();
    final JdbcServices jdbcServices = factory.getJdbcServices();
    SqlAstTranslator<JdbcDelete> deleteTranslator = null;
    if (jdbcDelete == null) {
        deleteTranslator = createDeleteTranslator(executionContext);
    }
    final JdbcParameterBindings jdbcParameterBindings = SqmUtil.createJdbcParameterBindings(executionContext.getQueryParameterBindings(), domainParameterXref, jdbcParamsXref, factory.getRuntimeMetamodels().getMappingMetamodel(), sqmInterpretation.getFromClauseAccess()::findTableGroup, new SqmParameterMappingModelResolutionAccess() {

        @Override
        @SuppressWarnings("unchecked")
        public <T> MappingModelExpressible<T> getResolvedMappingModelType(SqmParameter<T> parameter) {
            return (MappingModelExpressible<T>) sqmInterpretation.getSqmParameterMappingModelTypeResolutions().get(parameter);
        }
    }, session);
    if (jdbcDelete != null && !jdbcDelete.isCompatibleWith(jdbcParameterBindings, executionContext.getQueryOptions())) {
        deleteTranslator = createDeleteTranslator(executionContext);
    }
    if (deleteTranslator != null) {
        jdbcDelete = deleteTranslator.translate(jdbcParameterBindings, executionContext.getQueryOptions());
    } else {
        jdbcDelete.bindFilterJdbcParameters(jdbcParameterBindings);
    }
    final boolean missingRestriction = sqmDelete.getWhereClause() == null || sqmDelete.getWhereClause().getPredicate() == null;
    if (missingRestriction) {
        assert domainParameterXref.getSqmParameterCount() == 0;
        assert jdbcParamsXref.isEmpty();
    }
    final SqmJdbcExecutionContextAdapter executionContextAdapter = SqmJdbcExecutionContextAdapter.usingLockingAndPaging(executionContext);
    SqmMutationStrategyHelper.cleanUpCollectionTables(entityDescriptor, (tableReference, attributeMapping) -> {
        if (missingRestriction) {
            return null;
        }
        final ForeignKeyDescriptor fkDescriptor = attributeMapping.getKeyDescriptor();
        final Expression fkColumnExpression = MappingModelHelper.buildColumnReferenceExpression(fkDescriptor.getKeyPart(), null, factory);
        final QuerySpec matchingIdSubQuery = new QuerySpec(false);
        final MutatingTableReferenceGroupWrapper tableGroup = new MutatingTableReferenceGroupWrapper(new NavigablePath(attributeMapping.getRootPathName()), attributeMapping, sqmInterpretation.getSqlAst().getTargetTable());
        final Expression fkTargetColumnExpression = MappingModelHelper.buildColumnReferenceExpression(tableGroup, fkDescriptor.getTargetPart(), sqmInterpretation.getSqlExpressionResolver(), factory);
        matchingIdSubQuery.getSelectClause().addSqlSelection(new SqlSelectionImpl(1, 0, fkTargetColumnExpression));
        matchingIdSubQuery.getFromClause().addRoot(tableGroup);
        matchingIdSubQuery.applyPredicate(sqmInterpretation.getSqlAst().getRestriction());
        return new InSubQueryPredicate(fkColumnExpression, matchingIdSubQuery, false);
    }, (missingRestriction ? JdbcParameterBindings.NO_BINDINGS : jdbcParameterBindings), executionContextAdapter);
    return jdbcServices.getJdbcMutationExecutor().execute(jdbcDelete, jdbcParameterBindings, sql -> session.getJdbcCoordinator().getStatementPreparer().prepareStatement(sql), (integer, preparedStatement) -> {
    }, executionContextAdapter);
}
Also used : MutatingTableReferenceGroupWrapper(org.hibernate.sql.ast.tree.from.MutatingTableReferenceGroupWrapper) NavigablePath(org.hibernate.spi.NavigablePath) SqmParameterMappingModelResolutionAccess(org.hibernate.query.sqm.spi.SqmParameterMappingModelResolutionAccess) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) Expression(org.hibernate.sql.ast.tree.expression.Expression) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) JdbcDelete(org.hibernate.sql.exec.spi.JdbcDelete) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings)

Example 15 with JdbcParameterBindings

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

the class NativeNonSelectQueryPlanImpl method executeUpdate.

@Override
public int executeUpdate(DomainQueryExecutionContext executionContext) {
    final SharedSessionContractImplementor session = executionContext.getSession();
    session.autoFlushIfRequired(affectedTableNames);
    BulkOperationCleanupAction.schedule(session, affectedTableNames);
    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, session.getFactory());
    }
    final SQLQueryParser parser = new SQLQueryParser(sql, null, session.getSessionFactory());
    final JdbcMutation jdbcMutation = new NativeJdbcMutation(parser.process(), jdbcParameterBinders, affectedTableNames);
    return session.getJdbcServices().getJdbcMutationExecutor().execute(jdbcMutation, jdbcParameterBindings, sql -> session.getJdbcCoordinator().getStatementPreparer().prepareStatement(sql), (integer, preparedStatement) -> {
    }, SqmJdbcExecutionContextAdapter.usingLockingAndPaging(executionContext));
}
Also used : NativeJdbcMutation(org.hibernate.sql.exec.spi.NativeJdbcMutation) NativeJdbcMutation(org.hibernate.sql.exec.spi.NativeJdbcMutation) JdbcMutation(org.hibernate.sql.exec.spi.JdbcMutation) JdbcParameterBindingsImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) QueryParameterBindings(org.hibernate.query.spi.QueryParameterBindings) JdbcParameterBinder(org.hibernate.sql.exec.spi.JdbcParameterBinder) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings)

Aggregations

JdbcParameterBindings (org.hibernate.sql.exec.spi.JdbcParameterBindings)32 JdbcServices (org.hibernate.engine.jdbc.spi.JdbcServices)21 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)20 SharedSessionContractImplementor (org.hibernate.engine.spi.SharedSessionContractImplementor)19 JdbcParameterBindingsImpl (org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl)19 JdbcSelect (org.hibernate.sql.exec.spi.JdbcSelect)18 ArrayList (java.util.ArrayList)15 QueryParameterBindings (org.hibernate.query.spi.QueryParameterBindings)14 ExecutionContext (org.hibernate.sql.exec.spi.ExecutionContext)14 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)13 MappingModelExpressible (org.hibernate.metamodel.mapping.MappingModelExpressible)13 SelectStatement (org.hibernate.sql.ast.tree.select.SelectStatement)13 SqmParameterMappingModelResolutionAccess (org.hibernate.query.sqm.spi.SqmParameterMappingModelResolutionAccess)12 SqlAstTranslatorFactory (org.hibernate.sql.ast.SqlAstTranslatorFactory)12 Callback (org.hibernate.sql.exec.spi.Callback)12 QueryOptions (org.hibernate.query.spi.QueryOptions)11 JdbcParameter (org.hibernate.sql.ast.tree.expression.JdbcParameter)11 List (java.util.List)8 SqmParameter (org.hibernate.query.sqm.tree.expression.SqmParameter)7 QuerySpec (org.hibernate.sql.ast.tree.select.QuerySpec)7