Search in sources :

Example 1 with JdbcParameter

use of org.hibernate.sql.ast.tree.expression.JdbcParameter in project hibernate-orm by hibernate.

the class LoaderSelectBuilder method applyRestriction.

private void applyRestriction(QuerySpec rootQuerySpec, NavigablePath rootNavigablePath, TableGroup rootTableGroup, ModelPart modelPart, int numberColumns, Consumer<JdbcParameter> jdbcParameterConsumer, LoaderSqlAstCreationState sqlAstCreationState) {
    final SqlExpressionResolver sqlExpressionResolver = sqlAstCreationState.getSqlExpressionResolver();
    final NavigablePath navigablePath = rootNavigablePath.append(modelPart.getNavigableRole().getNavigableName());
    if (numberColumns == 1) {
        modelPart.forEachSelectable((columnIndex, selection) -> {
            final TableReference tableReference = rootTableGroup.resolveTableReference(navigablePath, selection.getContainingTableExpression());
            final ColumnReference columnRef = (ColumnReference) sqlExpressionResolver.resolveSqlExpression(createColumnReferenceKey(tableReference, selection.getSelectionExpression()), p -> new ColumnReference(tableReference, selection, creationContext.getSessionFactory()));
            if (numberOfKeysToLoad == 1) {
                final JdbcParameter jdbcParameter = new JdbcParameterImpl(selection.getJdbcMapping());
                jdbcParameterConsumer.accept(jdbcParameter);
                rootQuerySpec.applyPredicate(new ComparisonPredicate(columnRef, ComparisonOperator.EQUAL, jdbcParameter));
            } else {
                final InListPredicate predicate = new InListPredicate(columnRef);
                for (int i = 0; i < numberOfKeysToLoad; i++) {
                    for (int j = 0; j < numberColumns; j++) {
                        final JdbcParameter jdbcParameter = new JdbcParameterImpl(columnRef.getJdbcMapping());
                        jdbcParameterConsumer.accept(jdbcParameter);
                        predicate.addExpression(jdbcParameter);
                    }
                }
                rootQuerySpec.applyPredicate(predicate);
            }
        });
    } else {
        final List<ColumnReference> columnReferences = new ArrayList<>(numberColumns);
        modelPart.forEachSelectable((columnIndex, selection) -> {
            final TableReference tableReference = rootTableGroup.resolveTableReference(navigablePath, selection.getContainingTableExpression());
            columnReferences.add((ColumnReference) sqlExpressionResolver.resolveSqlExpression(createColumnReferenceKey(tableReference, selection.getSelectionExpression()), p -> new ColumnReference(tableReference, selection, creationContext.getSessionFactory())));
        });
        final SqlTuple tuple = new SqlTuple(columnReferences, modelPart);
        final InListPredicate predicate = new InListPredicate(tuple);
        for (int i = 0; i < numberOfKeysToLoad; i++) {
            final List<JdbcParameter> tupleParams = new ArrayList<>(numberColumns);
            for (int j = 0; j < numberColumns; j++) {
                final ColumnReference columnReference = columnReferences.get(j);
                final JdbcParameter jdbcParameter = new JdbcParameterImpl(columnReference.getJdbcMapping());
                jdbcParameterConsumer.accept(jdbcParameter);
                tupleParams.add(jdbcParameter);
            }
            final SqlTuple paramTuple = new SqlTuple(tupleParams, modelPart);
            predicate.addExpression(paramTuple);
        }
        rootQuerySpec.applyPredicate(predicate);
    }
}
Also used : Arrays(java.util.Arrays) CollectionFetch(org.hibernate.sql.results.graph.collection.internal.CollectionFetch) CollectionDomainResult(org.hibernate.sql.results.graph.collection.internal.CollectionDomainResult) GraphSemantic(org.hibernate.graph.GraphSemantic) ResultsHelper.attributeName(org.hibernate.query.results.ResultsHelper.attributeName) TableGroupJoin(org.hibernate.sql.ast.tree.from.TableGroupJoin) CascadingAction(org.hibernate.engine.spi.CascadingAction) EntityValuedModelPart(org.hibernate.metamodel.mapping.EntityValuedModelPart) EntityResultImpl(org.hibernate.sql.results.graph.entity.internal.EntityResultImpl) SqlAstCreationContext(org.hibernate.sql.ast.spi.SqlAstCreationContext) BagSemantics(org.hibernate.collection.spi.BagSemantics) FetchableContainer(org.hibernate.sql.results.graph.FetchableContainer) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) ComparisonPredicate(org.hibernate.sql.ast.tree.predicate.ComparisonPredicate) BiDirectionalFetch(org.hibernate.sql.results.graph.BiDirectionalFetch) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) Map(java.util.Map) FetchProfile(org.hibernate.engine.profile.FetchProfile) JdbcParameterImpl(org.hibernate.sql.exec.internal.JdbcParameterImpl) ComparisonOperator(org.hibernate.query.sqm.ComparisonOperator) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) CollectionPart(org.hibernate.metamodel.mapping.CollectionPart) EntityValuedFetchable(org.hibernate.sql.results.graph.entity.EntityValuedFetchable) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) Fetchable(org.hibernate.sql.results.graph.Fetchable) TableGroupJoinProducer(org.hibernate.sql.ast.tree.from.TableGroupJoinProducer) LockOptions(org.hibernate.LockOptions) NavigablePath(org.hibernate.query.spi.NavigablePath) AliasCollector(org.hibernate.sql.ast.spi.AliasCollector) DomainResult(org.hibernate.sql.results.graph.DomainResult) Expression(org.hibernate.sql.ast.tree.expression.Expression) OrderByFragment(org.hibernate.metamodel.mapping.ordering.OrderByFragment) SimpleFromClauseAccessImpl(org.hibernate.sql.ast.spi.SimpleFromClauseAccessImpl) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) Objects(java.util.Objects) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) LoadQueryInfluencers(org.hibernate.engine.spi.LoadQueryInfluencers) List(java.util.List) CascadeStyle(org.hibernate.engine.spi.CascadeStyle) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec) SubselectFetch(org.hibernate.engine.spi.SubselectFetch) SimpleForeignKeyDescriptor(org.hibernate.metamodel.mapping.internal.SimpleForeignKeyDescriptor) EmbeddedAttributeMapping(org.hibernate.metamodel.mapping.internal.EmbeddedAttributeMapping) SqlExpressionResolver.createColumnReferenceKey(org.hibernate.sql.ast.spi.SqlExpressionResolver.createColumnReferenceKey) FetchParent(org.hibernate.sql.results.graph.FetchParent) BasicValuedModelPart(org.hibernate.metamodel.mapping.BasicValuedModelPart) InListPredicate(org.hibernate.sql.ast.tree.predicate.InListPredicate) Logger(org.jboss.logging.Logger) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference) ArrayList(java.util.ArrayList) RootGraphImplementor(org.hibernate.graph.spi.RootGraphImplementor) TableReference(org.hibernate.sql.ast.tree.from.TableReference) ModelPart(org.hibernate.metamodel.mapping.ModelPart) Loader(org.hibernate.loader.ast.spi.Loader) BiConsumer(java.util.function.BiConsumer) EntityIdentifierNavigablePath(org.hibernate.query.sqm.spi.EntityIdentifierNavigablePath) SqlAliasBaseManager(org.hibernate.sql.ast.spi.SqlAliasBaseManager) SqlAstCreationState(org.hibernate.sql.ast.spi.SqlAstCreationState) FetchTiming(org.hibernate.engine.FetchTiming) Loadable(org.hibernate.loader.ast.spi.Loadable) Fetch(org.hibernate.sql.results.graph.Fetch) Consumer(java.util.function.Consumer) Restrictable(org.hibernate.metamodel.mapping.Restrictable) EntityGraphTraversalState(org.hibernate.sql.results.graph.EntityGraphTraversalState) FetchStyle(org.hibernate.engine.FetchStyle) StandardEntityGraphTraversalStateImpl(org.hibernate.sql.results.internal.StandardEntityGraphTraversalStateImpl) AbstractMap(java.util.AbstractMap) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) FromClauseAccess(org.hibernate.sql.ast.spi.FromClauseAccess) QueryPart(org.hibernate.sql.ast.tree.select.QueryPart) SqlAstJoinType(org.hibernate.sql.ast.SqlAstJoinType) NaturalIdMapping(org.hibernate.metamodel.mapping.NaturalIdMapping) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) NonAggregatedIdentifierMapping(org.hibernate.metamodel.mapping.NonAggregatedIdentifierMapping) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) Collections(java.util.Collections) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) EffectiveEntityGraph(org.hibernate.engine.spi.EffectiveEntityGraph) PluralTableGroup(org.hibernate.sql.ast.tree.from.PluralTableGroup) NavigablePath(org.hibernate.query.spi.NavigablePath) EntityIdentifierNavigablePath(org.hibernate.query.sqm.spi.EntityIdentifierNavigablePath) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) ArrayList(java.util.ArrayList) InListPredicate(org.hibernate.sql.ast.tree.predicate.InListPredicate) ComparisonPredicate(org.hibernate.sql.ast.tree.predicate.ComparisonPredicate) TableReference(org.hibernate.sql.ast.tree.from.TableReference) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple) JdbcParameterImpl(org.hibernate.sql.exec.internal.JdbcParameterImpl) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 2 with JdbcParameter

use of org.hibernate.sql.ast.tree.expression.JdbcParameter in project hibernate-orm by hibernate.

the class SimpleNaturalIdLoader method applyNaturalIdRestriction.

@Override
protected void applyNaturalIdRestriction(Object bindValue, TableGroup rootTableGroup, Consumer<Predicate> predicateConsumer, BiConsumer<JdbcParameter, JdbcParameterBinding> jdbcParameterConsumer, LoaderSqlAstCreationState sqlAstCreationState, SharedSessionContractImplementor session) {
    if (bindValue == null) {
        naturalIdMapping().getAttribute().forEachSelectable((index, selectable) -> {
            final Expression columnReference = resolveColumnReference(rootTableGroup, selectable, sqlAstCreationState.getSqlExpressionResolver(), session.getFactory());
            predicateConsumer.accept(new NullnessPredicate(columnReference));
        });
    } else {
        naturalIdMapping().getAttribute().breakDownJdbcValues(bindValue, (jdbcValue, jdbcValueMapping) -> {
            final Expression columnReference = resolveColumnReference(rootTableGroup, jdbcValueMapping, sqlAstCreationState.getSqlExpressionResolver(), session.getFactory());
            if (jdbcValue == null) {
                predicateConsumer.accept(new NullnessPredicate(columnReference));
            } else {
                final JdbcParameter jdbcParameter = new JdbcParameterImpl(jdbcValueMapping.getJdbcMapping());
                final ComparisonPredicate predicate = new ComparisonPredicate(columnReference, ComparisonOperator.EQUAL, jdbcParameter);
                predicateConsumer.accept(predicate);
                jdbcParameterConsumer.accept(jdbcParameter, new JdbcParameterBindingImpl(jdbcValueMapping.getJdbcMapping(), jdbcValue));
            }
        }, session);
    }
}
Also used : Expression(org.hibernate.sql.ast.tree.expression.Expression) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) JdbcParameterBindingImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingImpl) NullnessPredicate(org.hibernate.sql.ast.tree.predicate.NullnessPredicate) JdbcParameterImpl(org.hibernate.sql.exec.internal.JdbcParameterImpl) ComparisonPredicate(org.hibernate.sql.ast.tree.predicate.ComparisonPredicate)

Example 3 with JdbcParameter

use of org.hibernate.sql.ast.tree.expression.JdbcParameter 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 4 with JdbcParameter

use of org.hibernate.sql.ast.tree.expression.JdbcParameter in project hibernate-orm by hibernate.

the class SingleIdEntityLoaderStandardImpl method createLoadPlan.

private SingleIdLoadPlan<T> createLoadPlan(LockOptions lockOptions, LoadQueryInfluencers queryInfluencers, SessionFactoryImplementor sessionFactory) {
    final List<JdbcParameter> jdbcParameters = new ArrayList<>();
    final SelectStatement sqlAst = LoaderSelectBuilder.createSelect(getLoadable(), // null here means to select everything
    null, getLoadable().getIdentifierMapping(), null, 1, queryInfluencers, lockOptions, jdbcParameters::add, sessionFactory);
    return new SingleIdLoadPlan<>((Loadable) getLoadable(), getLoadable().getIdentifierMapping(), sqlAst, jdbcParameters, lockOptions, sessionFactory);
}
Also used : SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) ArrayList(java.util.ArrayList)

Example 5 with JdbcParameter

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

Aggregations

JdbcParameter (org.hibernate.sql.ast.tree.expression.JdbcParameter)29 ArrayList (java.util.ArrayList)22 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)18 SelectStatement (org.hibernate.sql.ast.tree.select.SelectStatement)17 JdbcParameterBindings (org.hibernate.sql.exec.spi.JdbcParameterBindings)15 List (java.util.List)13 Map (java.util.Map)13 ExecutionContext (org.hibernate.sql.exec.spi.ExecutionContext)13 Expression (org.hibernate.sql.ast.tree.expression.Expression)12 Collections (java.util.Collections)11 JdbcServices (org.hibernate.engine.jdbc.spi.JdbcServices)11 TableGroup (org.hibernate.sql.ast.tree.from.TableGroup)11 IdentityHashMap (java.util.IdentityHashMap)10 LinkedHashMap (java.util.LinkedHashMap)10 JdbcSelect (org.hibernate.sql.exec.spi.JdbcSelect)10 MappingModelExpressible (org.hibernate.metamodel.mapping.MappingModelExpressible)9 BiConsumer (java.util.function.BiConsumer)8 CollectionHelper (org.hibernate.internal.util.collections.CollectionHelper)8 JdbcMapping (org.hibernate.metamodel.mapping.JdbcMapping)8 EntityPersister (org.hibernate.persister.entity.EntityPersister)8