Search in sources :

Example 46 with NavigablePath

use of org.hibernate.query.spi.NavigablePath in project hibernate-orm by hibernate.

the class LoaderSelectBuilder method generateSubSelect.

private QueryPart generateSubSelect(PluralAttributeMapping attributeMapping, TableGroup rootTableGroup, SubselectFetch subselect, int jdbcTypeCount, LoaderSqlAstCreationState creationState, SessionFactoryImplementor sessionFactory) {
    final ForeignKeyDescriptor fkDescriptor = attributeMapping.getKeyDescriptor();
    final QuerySpec subQuery = new QuerySpec(false);
    final QuerySpec loadingSqlAst = subselect.getLoadingSqlAst();
    // todo (6.0) : we need to find the owner's TableGroup in the `loadingSqlAst`
    final TableGroup ownerTableGroup = subselect.getOwnerTableGroup();
    // transfer the from-clause
    loadingSqlAst.getFromClause().visitRoots(subQuery.getFromClause()::addRoot);
    final SqlExpressionResolver sqlExpressionResolver = creationState.getSqlExpressionResolver();
    final NavigablePath navigablePath = ownerTableGroup.getNavigablePath().append(attributeMapping.getAttributeName());
    fkDescriptor.visitTargetSelectables((valuesPosition, selection) -> {
        // for each column, resolve a SqlSelection and add it to the sub-query select-clause
        final TableReference tableReference = ownerTableGroup.resolveTableReference(navigablePath, selection.getContainingTableExpression());
        final Expression expression = sqlExpressionResolver.resolveSqlExpression(createColumnReferenceKey(tableReference, selection.getSelectionExpression()), sqlAstProcessingState -> new ColumnReference(tableReference, selection, sessionFactory));
        subQuery.getSelectClause().addSqlSelection(new SqlSelectionImpl(valuesPosition + 1, valuesPosition, expression));
    });
    // transfer the restriction
    subQuery.applyPredicate(loadingSqlAst.getWhereClauseRestrictions());
    return subQuery;
}
Also used : TableReference(org.hibernate.sql.ast.tree.from.TableReference) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) PluralTableGroup(org.hibernate.sql.ast.tree.from.PluralTableGroup) NavigablePath(org.hibernate.query.spi.NavigablePath) EntityIdentifierNavigablePath(org.hibernate.query.sqm.spi.EntityIdentifierNavigablePath) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) Expression(org.hibernate.sql.ast.tree.expression.Expression) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) SimpleForeignKeyDescriptor(org.hibernate.metamodel.mapping.internal.SimpleForeignKeyDescriptor) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 47 with NavigablePath

use of org.hibernate.query.spi.NavigablePath in project hibernate-orm by hibernate.

the class LoaderSelectBuilder method generateSelect.

private SelectStatement generateSelect(SubselectFetch subselect) {
    assert loadable instanceof PluralAttributeMapping;
    final PluralAttributeMapping attributeMapping = (PluralAttributeMapping) loadable;
    final QuerySpec rootQuerySpec = new QuerySpec(true);
    final NavigablePath rootNavigablePath = new NavigablePath(loadable.getRootPathName());
    // We need to initialize the acronymMap based on subselect.getLoadingSqlAst() to avoid alias collisions
    final Map<String, TableReference> tableReferences = AliasCollector.getTableReferences(subselect.getLoadingSqlAst());
    final LoaderSqlAstCreationState sqlAstCreationState = new LoaderSqlAstCreationState(rootQuerySpec, new SqlAliasBaseManager(tableReferences.keySet()), new SimpleFromClauseAccessImpl(), lockOptions, this::visitFetches, numberOfKeysToLoad > 1, creationContext);
    final TableGroup rootTableGroup = loadable.createRootTableGroup(true, rootNavigablePath, null, () -> rootQuerySpec::applyPredicate, sqlAstCreationState, creationContext);
    rootQuerySpec.getFromClause().addRoot(rootTableGroup);
    sqlAstCreationState.getFromClauseAccess().registerTableGroup(rootNavigablePath, rootTableGroup);
    registerPluralTableGroupParts(sqlAstCreationState.getFromClauseAccess(), rootTableGroup);
    // generate and apply the restriction
    applySubSelectRestriction(rootQuerySpec, rootNavigablePath, rootTableGroup, subselect, sqlAstCreationState);
    // NOTE : no need to check - we are explicitly processing a plural-attribute
    applyFiltering(rootQuerySpec, rootTableGroup, attributeMapping, sqlAstCreationState);
    applyOrdering(rootTableGroup, attributeMapping);
    return new SelectStatement(rootQuerySpec, List.of(new CollectionDomainResult(rootNavigablePath, attributeMapping, null, rootTableGroup, sqlAstCreationState)));
}
Also used : NavigablePath(org.hibernate.query.spi.NavigablePath) EntityIdentifierNavigablePath(org.hibernate.query.sqm.spi.EntityIdentifierNavigablePath) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) PluralTableGroup(org.hibernate.sql.ast.tree.from.PluralTableGroup) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) SimpleFromClauseAccessImpl(org.hibernate.sql.ast.spi.SimpleFromClauseAccessImpl) SqlAliasBaseManager(org.hibernate.sql.ast.spi.SqlAliasBaseManager) CollectionDomainResult(org.hibernate.sql.results.graph.collection.internal.CollectionDomainResult) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) TableReference(org.hibernate.sql.ast.tree.from.TableReference) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec)

Example 48 with NavigablePath

use of org.hibernate.query.spi.NavigablePath 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 49 with NavigablePath

use of org.hibernate.query.spi.NavigablePath in project hibernate-orm by hibernate.

the class NonAggregatedIdentifierMappingImpl method toSqlExpression.

@Override
public SqlTuple toSqlExpression(TableGroup tableGroup, Clause clause, SqmToSqlAstConverter walker, SqlAstCreationState sqlAstCreationState) {
    if (hasContainingClass()) {
        final SelectableMappings selectableMappings = getEmbeddableTypeDescriptor();
        final List<ColumnReference> columnReferences = CollectionHelper.arrayList(selectableMappings.getJdbcTypeCount());
        final NavigablePath navigablePath = tableGroup.getNavigablePath().append(getNavigableRole().getNavigableName());
        final TableReference defaultTableReference = tableGroup.resolveTableReference(navigablePath, getContainingTableExpression());
        int offset = 0;
        for (AttributeMapping attributeMapping : identifierValueMapper.getAttributeMappings()) {
            offset += attributeMapping.forEachSelectable(offset, (columnIndex, selection) -> {
                final TableReference tableReference = defaultTableReference.resolveTableReference(selection.getContainingTableExpression()) != null ? defaultTableReference : tableGroup.resolveTableReference(navigablePath, selection.getContainingTableExpression());
                final Expression columnReference = sqlAstCreationState.getSqlExpressionResolver().resolveSqlExpression(SqlExpressionResolver.createColumnReferenceKey(tableReference, selection.getSelectionExpression()), sqlAstProcessingState -> new ColumnReference(tableReference.getIdentificationVariable(), selection, sqlAstCreationState.getCreationContext().getSessionFactory()));
                columnReferences.add((ColumnReference) columnReference);
            });
        }
        return new SqlTuple(columnReferences, this);
    }
    return super.toSqlExpression(tableGroup, clause, walker, sqlAstCreationState);
}
Also used : CollectionHelper(org.hibernate.internal.util.collections.CollectionHelper) DomainResultCreationState(org.hibernate.sql.results.graph.DomainResultCreationState) SelectableMappings(org.hibernate.metamodel.mapping.SelectableMappings) EntityPersister(org.hibernate.persister.entity.EntityPersister) JdbcMapping(org.hibernate.metamodel.mapping.JdbcMapping) RootClass(org.hibernate.mapping.RootClass) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference) PersistenceContext(org.hibernate.engine.spi.PersistenceContext) Clause(org.hibernate.sql.ast.Clause) TableReference(org.hibernate.sql.ast.tree.from.TableReference) ModelPart(org.hibernate.metamodel.mapping.ModelPart) BiConsumer(java.util.function.BiConsumer) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SqlSelection(org.hibernate.sql.ast.spi.SqlSelection) SqlAstCreationState(org.hibernate.sql.ast.spi.SqlAstCreationState) EmbeddableMappingType(org.hibernate.metamodel.mapping.EmbeddableMappingType) NavigablePath(org.hibernate.query.spi.NavigablePath) Expression(org.hibernate.sql.ast.tree.expression.Expression) SqmToSqlAstConverter(org.hibernate.query.sqm.sql.SqmToSqlAstConverter) EntityKey(org.hibernate.engine.spi.EntityKey) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) List(java.util.List) AbstractCompositeIdentifierMapping(org.hibernate.metamodel.internal.AbstractCompositeIdentifierMapping) Component(org.hibernate.mapping.Component) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple) NonAggregatedIdentifierMapping(org.hibernate.metamodel.mapping.NonAggregatedIdentifierMapping) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) TableReference(org.hibernate.sql.ast.tree.from.TableReference) SelectableMappings(org.hibernate.metamodel.mapping.SelectableMappings) NavigablePath(org.hibernate.query.spi.NavigablePath) Expression(org.hibernate.sql.ast.tree.expression.Expression) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 50 with NavigablePath

use of org.hibernate.query.spi.NavigablePath in project hibernate-orm by hibernate.

the class EntityRowIdMappingImpl method createDomainResult.

@Override
public <T> DomainResult<T> createDomainResult(NavigablePath navigablePath, TableGroup tableGroup, String resultVariable, DomainResultCreationState creationState) {
    final SqlAstCreationState sqlAstCreationState = creationState.getSqlAstCreationState();
    final SqlExpressionResolver sqlExpressionResolver = sqlAstCreationState.getSqlExpressionResolver();
    final TableReference columnTableReference = tableGroup.resolveTableReference(navigablePath, tableExpression);
    final SqlSelection sqlSelection = sqlExpressionResolver.resolveSqlSelection(sqlExpressionResolver.resolveSqlExpression(SqlExpressionResolver.createColumnReferenceKey(columnTableReference, rowIdName), sqlAstProcessingState -> new ColumnReference(columnTableReference, rowIdName, false, // having to write a Dialect
    null, null, rowIdType, sqlAstCreationState.getCreationContext().getSessionFactory())), rowIdType.getJavaTypeDescriptor(), sqlAstCreationState.getCreationContext().getSessionFactory().getTypeConfiguration());
    return new BasicResult(sqlSelection.getValuesArrayPosition(), resultVariable, rowIdType.getJavaTypeDescriptor(), navigablePath);
}
Also used : DomainResultCreationState(org.hibernate.sql.results.graph.DomainResultCreationState) JdbcMapping(org.hibernate.metamodel.mapping.JdbcMapping) BasicType(org.hibernate.type.BasicType) NavigablePath(org.hibernate.query.spi.NavigablePath) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference) DomainResult(org.hibernate.sql.results.graph.DomainResult) JavaType(org.hibernate.type.descriptor.java.JavaType) Clause(org.hibernate.sql.ast.Clause) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) BasicResult(org.hibernate.sql.results.graph.basic.BasicResult) MappingType(org.hibernate.metamodel.mapping.MappingType) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) TableReference(org.hibernate.sql.ast.tree.from.TableReference) NavigableRole(org.hibernate.metamodel.model.domain.NavigableRole) EntityRowIdMapping(org.hibernate.metamodel.mapping.EntityRowIdMapping) SelectableMapping(org.hibernate.metamodel.mapping.SelectableMapping) BiConsumer(java.util.function.BiConsumer) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) SqlSelection(org.hibernate.sql.ast.spi.SqlSelection) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) IndexedConsumer(org.hibernate.mapping.IndexedConsumer) SqlAstCreationState(org.hibernate.sql.ast.spi.SqlAstCreationState) TableReference(org.hibernate.sql.ast.tree.from.TableReference) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) BasicResult(org.hibernate.sql.results.graph.basic.BasicResult) SqlAstCreationState(org.hibernate.sql.ast.spi.SqlAstCreationState) SqlSelection(org.hibernate.sql.ast.spi.SqlSelection) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Aggregations

NavigablePath (org.hibernate.query.spi.NavigablePath)67 TableGroup (org.hibernate.sql.ast.tree.from.TableGroup)53 TableReference (org.hibernate.sql.ast.tree.from.TableReference)30 PluralTableGroup (org.hibernate.sql.ast.tree.from.PluralTableGroup)28 ColumnReference (org.hibernate.sql.ast.tree.expression.ColumnReference)27 SqlExpressionResolver (org.hibernate.sql.ast.spi.SqlExpressionResolver)24 Fetch (org.hibernate.sql.results.graph.Fetch)23 SqlSelection (org.hibernate.sql.ast.spi.SqlSelection)22 PluralAttributeMapping (org.hibernate.metamodel.mapping.PluralAttributeMapping)21 QuerySpec (org.hibernate.sql.ast.tree.select.QuerySpec)21 FetchTiming (org.hibernate.engine.FetchTiming)20 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)20 Expression (org.hibernate.sql.ast.tree.expression.Expression)20 LazyTableGroup (org.hibernate.sql.ast.tree.from.LazyTableGroup)20 DomainResultCreationState (org.hibernate.sql.results.graph.DomainResultCreationState)20 ModelPart (org.hibernate.metamodel.mapping.ModelPart)19 CorrelatedTableGroup (org.hibernate.sql.ast.tree.from.CorrelatedTableGroup)19 FetchParent (org.hibernate.sql.results.graph.FetchParent)19 ArrayList (java.util.ArrayList)18 BiConsumer (java.util.function.BiConsumer)18