Search in sources :

Example 6 with FromClauseAccess

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

the class BasicValuedPathInterpretation method from.

/**
 * Static factory
 */
public static <T> BasicValuedPathInterpretation<T> from(SqmBasicValuedSimplePath<T> sqmPath, SqlAstCreationState sqlAstCreationState, SemanticQueryWalker sqmWalker, boolean jpaQueryComplianceEnabled) {
    final FromClauseAccess fromClauseAccess = sqlAstCreationState.getFromClauseAccess();
    final TableGroup tableGroup = fromClauseAccess.getTableGroup(sqmPath.getNavigablePath().getParent());
    EntityMappingType treatTarget = null;
    if (jpaQueryComplianceEnabled) {
        if (sqmPath.getLhs() instanceof SqmTreatedPath) {
            final EntityDomainType treatTargetDomainType = ((SqmTreatedPath) sqmPath.getLhs()).getTreatTarget();
            final MappingMetamodel mappingMetamodel = sqlAstCreationState.getCreationContext().getSessionFactory().getRuntimeMetamodels().getMappingMetamodel();
            treatTarget = mappingMetamodel.findEntityDescriptor(treatTargetDomainType.getHibernateEntityName());
        } else if (sqmPath.getLhs().getNodeType() instanceof EntityDomainType) {
            final EntityDomainType entityDomainType = (EntityDomainType) sqmPath.getLhs().getNodeType();
            final MappingMetamodel mappingMetamodel = sqlAstCreationState.getCreationContext().getSessionFactory().getRuntimeMetamodels().getMappingMetamodel();
            treatTarget = mappingMetamodel.findEntityDescriptor(entityDomainType.getHibernateEntityName());
        }
    }
    final BasicValuedModelPart mapping = (BasicValuedModelPart) tableGroup.getModelPart().findSubPart(sqmPath.getReferencedPathSource().getPathName(), treatTarget);
    if (mapping == null) {
        if (jpaQueryComplianceEnabled) {
            // to get the better error, see if we got nothing because of treat handling
            final ModelPart subPart = tableGroup.getModelPart().findSubPart(sqmPath.getReferencedPathSource().getPathName(), null);
            if (subPart != null) {
                throw new StrictJpaComplianceViolation(StrictJpaComplianceViolation.Type.IMPLICIT_TREAT);
            }
        }
        throw new SemanticException("`" + sqmPath.getNavigablePath() + "` did not reference a known model part");
    }
    final TableReference tableReference = tableGroup.resolveTableReference(sqmPath.getNavigablePath(), mapping.getContainingTableExpression());
    final Expression expression = sqlAstCreationState.getSqlExpressionResolver().resolveSqlExpression(SqlExpressionResolver.createColumnReferenceKey(tableReference, mapping.getSelectionExpression()), sacs -> new ColumnReference(tableReference.getIdentificationVariable(), mapping, sqlAstCreationState.getCreationContext().getSessionFactory()));
    final ColumnReference columnReference;
    if (expression instanceof ColumnReference) {
        columnReference = ((ColumnReference) expression);
    } else if (expression instanceof SqlSelectionExpression) {
        final Expression selectedExpression = ((SqlSelectionExpression) expression).getSelection().getExpression();
        assert selectedExpression instanceof ColumnReference;
        columnReference = (ColumnReference) selectedExpression;
    } else {
        throw new UnsupportedOperationException("Unsupported basic-valued path expression : " + expression);
    }
    return new BasicValuedPathInterpretation<>(columnReference, sqmPath.getNavigablePath(), mapping, tableGroup);
}
Also used : TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) BasicValuedModelPart(org.hibernate.metamodel.mapping.BasicValuedModelPart) BasicValuedModelPart(org.hibernate.metamodel.mapping.BasicValuedModelPart) ModelPart(org.hibernate.metamodel.mapping.ModelPart) SqmTreatedPath(org.hibernate.query.sqm.tree.domain.SqmTreatedPath) SqlSelectionExpression(org.hibernate.sql.ast.tree.expression.SqlSelectionExpression) TableReference(org.hibernate.sql.ast.tree.from.TableReference) MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) FromClauseAccess(org.hibernate.sql.ast.spi.FromClauseAccess) SqlSelectionExpression(org.hibernate.sql.ast.tree.expression.SqlSelectionExpression) Expression(org.hibernate.sql.ast.tree.expression.Expression) StrictJpaComplianceViolation(org.hibernate.query.sqm.StrictJpaComplianceViolation) EntityDomainType(org.hibernate.metamodel.model.domain.EntityDomainType) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) SemanticException(org.hibernate.query.SemanticException) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 7 with FromClauseAccess

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

the class ToOneAttributeMapping method createTableGroupJoin.

@Override
public TableGroupJoin createTableGroupJoin(NavigablePath navigablePath, TableGroup lhs, String explicitSourceAlias, SqlAstJoinType requestedJoinType, boolean fetched, boolean addsPredicate, SqlAliasBaseGenerator aliasBaseGenerator, SqlExpressionResolver sqlExpressionResolver, FromClauseAccess fromClauseAccess, SqlAstCreationContext creationContext) {
    // This is vital for the map key property check that comes next
    assert !(lhs instanceof PluralTableGroup);
    final SqlAstJoinType joinType = requireNonNullElse(requestedJoinType, SqlAstJoinType.INNER);
    // we check if this attribute is the map key property to reuse the existing index table group
    if (!addsPredicate && (joinType == SqlAstJoinType.INNER || joinType == SqlAstJoinType.LEFT)) {
        TableGroup parentTableGroup = lhs;
        ModelPartContainer parentContainer = lhs.getModelPart();
        StringBuilder embeddablePathSb = null;
        // Traverse up embeddable table groups until we find a table group for a collection part
        while (!(parentContainer instanceof CollectionPart)) {
            if (parentContainer instanceof EmbeddableValuedModelPart) {
                if (embeddablePathSb == null) {
                    embeddablePathSb = new StringBuilder();
                }
                embeddablePathSb.insert(0, parentContainer.getPartName() + ".");
                parentTableGroup = fromClauseAccess.findTableGroup(parentTableGroup.getNavigablePath().getParent());
                parentContainer = parentTableGroup.getModelPart();
            } else {
                break;
            }
        }
        if (CollectionPart.Nature.ELEMENT.getName().equals(parentTableGroup.getNavigablePath().getLocalName())) {
            final PluralTableGroup pluralTableGroup = (PluralTableGroup) fromClauseAccess.findTableGroup(parentTableGroup.getNavigablePath().getParent());
            final String indexPropertyName = pluralTableGroup.getModelPart().getIndexMetadata().getIndexPropertyName();
            final String pathName;
            if (embeddablePathSb != null) {
                pathName = embeddablePathSb.append(getAttributeName()).toString();
            } else {
                pathName = getAttributeName();
            }
            if (pathName.equals(indexPropertyName)) {
                final TableGroup indexTableGroup = pluralTableGroup.getIndexTableGroup();
                // If this is the map key property, we can reuse the index table group
                initializeIfNeeded(lhs, requestedJoinType, indexTableGroup);
                return new TableGroupJoin(navigablePath, joinType, new MappedByTableGroup(navigablePath, this, indexTableGroup, fetched, pluralTableGroup, (np, tableExpression) -> {
                    if (!canUseParentTableGroup) {
                        return false;
                    }
                    if (!identifyingColumnsTableExpression.equals(tableExpression)) {
                        return false;
                    }
                    if (navigablePath.equals(np.getParent())) {
                        return targetKeyPropertyNames.contains(np.getLocalName());
                    }
                    final String relativePath = np.relativize(navigablePath);
                    if (relativePath == null) {
                        return false;
                    }
                    return targetKeyPropertyNames.contains(relativePath);
                }), null);
            }
        }
    }
    final LazyTableGroup lazyTableGroup = createRootTableGroupJoin(navigablePath, lhs, explicitSourceAlias, requestedJoinType, fetched, null, aliasBaseGenerator, sqlExpressionResolver, fromClauseAccess, creationContext);
    final TableGroupJoin join = new TableGroupJoin(navigablePath, joinType, lazyTableGroup, null);
    final TableReference lhsTableReference = lhs.resolveTableReference(navigablePath, identifyingColumnsTableExpression);
    lazyTableGroup.setTableGroupInitializerCallback((tableGroup) -> join.applyPredicate(foreignKeyDescriptor.generateJoinPredicate(sideNature == ForeignKeyDescriptor.Nature.TARGET ? lhsTableReference : tableGroup.getPrimaryTableReference(), sideNature == ForeignKeyDescriptor.Nature.TARGET ? tableGroup.getPrimaryTableReference() : lhsTableReference, sqlExpressionResolver, creationContext)));
    if (hasNotFoundAction()) {
        getAssociatedEntityMappingType().applyWhereRestrictions(join::applyPredicate, lazyTableGroup.getTableGroup(), true, null);
    }
    return join;
}
Also used : Arrays(java.util.Arrays) EntityPersister(org.hibernate.persister.entity.EntityPersister) Property(org.hibernate.mapping.Property) TreatedNavigablePath(org.hibernate.spi.TreatedNavigablePath) TableGroupJoin(org.hibernate.sql.ast.tree.from.TableGroupJoin) PropertyAccess(org.hibernate.property.access.spi.PropertyAccess) EntityResultImpl(org.hibernate.sql.results.graph.entity.internal.EntityResultImpl) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) ToOne(org.hibernate.mapping.ToOne) SqlAstCreationContext(org.hibernate.sql.ast.spi.SqlAstCreationContext) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) EntityAssociationMapping(org.hibernate.metamodel.mapping.EntityAssociationMapping) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) PersistentClass(org.hibernate.mapping.PersistentClass) FetchOptions(org.hibernate.sql.results.graph.FetchOptions) Join(org.hibernate.mapping.Join) TableGroupProducer(org.hibernate.sql.ast.tree.from.TableGroupProducer) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) EntityDelayedResultImpl(org.hibernate.sql.results.graph.entity.internal.EntityDelayedResultImpl) CollectionPart(org.hibernate.metamodel.mapping.CollectionPart) SqlSelection(org.hibernate.sql.ast.spi.SqlSelection) CorrelatedTableGroup(org.hibernate.sql.ast.tree.from.CorrelatedTableGroup) EntityValuedFetchable(org.hibernate.sql.results.graph.entity.EntityValuedFetchable) EntityDelayedFetchImpl(org.hibernate.sql.results.graph.entity.internal.EntityDelayedFetchImpl) MappedByTableGroup(org.hibernate.sql.ast.tree.from.MappedByTableGroup) TableGroupJoinProducer(org.hibernate.sql.ast.tree.from.TableGroupJoinProducer) AttributeMetadataAccess(org.hibernate.metamodel.mapping.AttributeMetadataAccess) LazyTableGroup(org.hibernate.sql.ast.tree.from.LazyTableGroup) OneToOne(org.hibernate.mapping.OneToOne) VirtualModelPart(org.hibernate.metamodel.mapping.VirtualModelPart) NotFoundSnapshotResult(org.hibernate.sql.results.graph.entity.internal.NotFoundSnapshotResult) StringHelper(org.hibernate.internal.util.StringHelper) DomainResult(org.hibernate.sql.results.graph.DomainResult) Set(java.util.Set) Value(org.hibernate.mapping.Value) Collection(org.hibernate.mapping.Collection) NavigablePath(org.hibernate.spi.NavigablePath) SqlAliasBase(org.hibernate.sql.ast.spi.SqlAliasBase) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) NavigableRole(org.hibernate.metamodel.model.domain.NavigableRole) ArrayHelper(org.hibernate.internal.util.collections.ArrayHelper) EntityIdentifierNavigablePath(org.hibernate.spi.EntityIdentifierNavigablePath) CircularBiDirectionalFetchImpl(org.hibernate.sql.results.internal.domain.CircularBiDirectionalFetchImpl) AbstractEntityPersister(org.hibernate.persister.entity.AbstractEntityPersister) SelectableConsumer(org.hibernate.metamodel.mapping.SelectableConsumer) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) IndexedConsumer(org.hibernate.mapping.IndexedConsumer) FetchParent(org.hibernate.sql.results.graph.FetchParent) CircularFetchImpl(org.hibernate.sql.results.internal.domain.CircularFetchImpl) DomainResultCreationState(org.hibernate.sql.results.graph.DomainResultCreationState) SqlAliasBaseGenerator(org.hibernate.sql.ast.spi.SqlAliasBaseGenerator) EntityFetchSelectImpl(org.hibernate.sql.results.graph.entity.internal.EntityFetchSelectImpl) JdbcMapping(org.hibernate.metamodel.mapping.JdbcMapping) EntityResultJoinedSubclassImpl(org.hibernate.sql.results.graph.entity.internal.EntityResultJoinedSubclassImpl) SqlAliasStemHelper(org.hibernate.sql.ast.spi.SqlAliasStemHelper) EmbeddedComponentType(org.hibernate.type.EmbeddedComponentType) EntityType(org.hibernate.type.EntityType) Clause(org.hibernate.sql.ast.Clause) Supplier(java.util.function.Supplier) Objects.requireNonNullElse(java.util.Objects.requireNonNullElse) MappingType(org.hibernate.metamodel.mapping.MappingType) TableReference(org.hibernate.sql.ast.tree.from.TableReference) HashSet(java.util.HashSet) ModelPart(org.hibernate.metamodel.mapping.ModelPart) ComponentType(org.hibernate.type.ComponentType) CompositeType(org.hibernate.type.CompositeType) BiConsumer(java.util.function.BiConsumer) ManagedMappingType(org.hibernate.metamodel.mapping.ManagedMappingType) StandardTableGroup(org.hibernate.sql.ast.tree.from.StandardTableGroup) SqlAstCreationState(org.hibernate.sql.ast.spi.SqlAstCreationState) FetchTiming(org.hibernate.engine.FetchTiming) ManyToOne(org.hibernate.mapping.ManyToOne) LockMode(org.hibernate.LockMode) AssociationKey(org.hibernate.metamodel.mapping.AssociationKey) Predicate(org.hibernate.sql.ast.tree.predicate.Predicate) Iterator(java.util.Iterator) ModelPartContainer(org.hibernate.metamodel.mapping.ModelPartContainer) EmbeddableValuedFetchable(org.hibernate.sql.results.graph.embeddable.EmbeddableValuedFetchable) Fetch(org.hibernate.sql.results.graph.Fetch) Consumer(java.util.function.Consumer) QueryableCollection(org.hibernate.persister.collection.QueryableCollection) EntityFetch(org.hibernate.sql.results.graph.entity.EntityFetch) FetchStyle(org.hibernate.engine.FetchStyle) FromClauseAccess(org.hibernate.sql.ast.spi.FromClauseAccess) SqlAstJoinType(org.hibernate.sql.ast.SqlAstJoinType) NotFoundAction(org.hibernate.annotations.NotFoundAction) Selectable(org.hibernate.mapping.Selectable) EmbeddableValuedModelPart(org.hibernate.metamodel.mapping.EmbeddableValuedModelPart) Collections(java.util.Collections) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) PluralTableGroup(org.hibernate.sql.ast.tree.from.PluralTableGroup) EntityFetchJoinedImpl(org.hibernate.sql.results.graph.entity.internal.EntityFetchJoinedImpl) Type(org.hibernate.type.Type) CorrelatedTableGroup(org.hibernate.sql.ast.tree.from.CorrelatedTableGroup) MappedByTableGroup(org.hibernate.sql.ast.tree.from.MappedByTableGroup) LazyTableGroup(org.hibernate.sql.ast.tree.from.LazyTableGroup) StandardTableGroup(org.hibernate.sql.ast.tree.from.StandardTableGroup) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) PluralTableGroup(org.hibernate.sql.ast.tree.from.PluralTableGroup) PluralTableGroup(org.hibernate.sql.ast.tree.from.PluralTableGroup) MappedByTableGroup(org.hibernate.sql.ast.tree.from.MappedByTableGroup) TableGroupJoin(org.hibernate.sql.ast.tree.from.TableGroupJoin) TableReference(org.hibernate.sql.ast.tree.from.TableReference) LazyTableGroup(org.hibernate.sql.ast.tree.from.LazyTableGroup) SqlAstJoinType(org.hibernate.sql.ast.SqlAstJoinType) EmbeddableValuedModelPart(org.hibernate.metamodel.mapping.EmbeddableValuedModelPart) CollectionPart(org.hibernate.metamodel.mapping.CollectionPart) ModelPartContainer(org.hibernate.metamodel.mapping.ModelPartContainer)

Example 8 with FromClauseAccess

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

the class ToOneAttributeMapping method generateFetch.

@Override
public EntityFetch generateFetch(FetchParent fetchParent, NavigablePath fetchablePath, FetchTiming fetchTiming, boolean selected, String resultVariable, DomainResultCreationState creationState) {
    final SqlAstCreationState sqlAstCreationState = creationState.getSqlAstCreationState();
    final FromClauseAccess fromClauseAccess = sqlAstCreationState.getFromClauseAccess();
    final TableGroup parentTableGroup = fromClauseAccess.getTableGroup(fetchParent.getNavigablePath());
    final NavigablePath parentNavigablePath = fetchablePath.getParent();
    assert parentNavigablePath.equals(fetchParent.getNavigablePath()) || fetchParent.getNavigablePath() instanceof TreatedNavigablePath && parentNavigablePath.equals(fetchParent.getNavigablePath().getRealParent());
    if ((hasNotFoundAction() || (fetchTiming == FetchTiming.IMMEDIATE && selected))) {
        final TableGroup tableGroup = determineTableGroup(fetchablePath, fetchParent, parentTableGroup, resultVariable, fromClauseAccess, creationState);
        return withRegisteredAssociationKeys(() -> {
            final DomainResult<?> keyResult;
            if (notFoundAction != null) {
                if (sideNature == ForeignKeyDescriptor.Nature.KEY) {
                    keyResult = foreignKeyDescriptor.createKeyDomainResult(fetchablePath, parentTableGroup, fetchParent, creationState);
                } else {
                    keyResult = foreignKeyDescriptor.createTargetDomainResult(fetchablePath, parentTableGroup, fetchParent, creationState);
                }
            } else {
                keyResult = null;
            }
            return new EntityFetchJoinedImpl(fetchParent, this, tableGroup, keyResult, fetchablePath, creationState);
        }, creationState);
    }
    /*
			1. No JoinTable
				Model:
					EntityA{
						@ManyToOne
						EntityB b
					}

					EntityB{
						@ManyToOne
						EntityA a
					}

				Relational:
					ENTITY_A( id )
					ENTITY_B( id, entity_a_id)

				1.1 EntityA -> EntityB : as keyResult we need ENTITY_B.id
				1.2 EntityB -> EntityA : as keyResult we need ENTITY_B.entity_a_id (FK referring column)

			2. JoinTable

		 */
    final ForeignKeyDescriptor.Nature resolvingKeySideOfForeignKey = creationState.getCurrentlyResolvingForeignKeyPart();
    final ForeignKeyDescriptor.Nature side;
    if (resolvingKeySideOfForeignKey == ForeignKeyDescriptor.Nature.KEY && this.sideNature == ForeignKeyDescriptor.Nature.TARGET) {
        // If we are currently resolving the key part of a foreign key we do not want to add joins.
        // So if the lhs of this association is the target of the FK, we have to use the KEY part to avoid a join
        side = ForeignKeyDescriptor.Nature.KEY;
    } else {
        side = this.sideNature;
    }
    final DomainResult<?> keyResult = foreignKeyDescriptor.createDomainResult(fetchablePath, parentTableGroup, side, fetchParent, creationState);
    final boolean selectByUniqueKey = isSelectByUniqueKey(side);
    if (fetchTiming == FetchTiming.IMMEDIATE) {
        return new EntityFetchSelectImpl(fetchParent, this, fetchablePath, keyResult, selectByUniqueKey, creationState);
    }
    return new EntityDelayedFetchImpl(fetchParent, this, fetchablePath, keyResult, selectByUniqueKey);
}
Also used : EntityFetchJoinedImpl(org.hibernate.sql.results.graph.entity.internal.EntityFetchJoinedImpl) CorrelatedTableGroup(org.hibernate.sql.ast.tree.from.CorrelatedTableGroup) MappedByTableGroup(org.hibernate.sql.ast.tree.from.MappedByTableGroup) LazyTableGroup(org.hibernate.sql.ast.tree.from.LazyTableGroup) StandardTableGroup(org.hibernate.sql.ast.tree.from.StandardTableGroup) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) PluralTableGroup(org.hibernate.sql.ast.tree.from.PluralTableGroup) TreatedNavigablePath(org.hibernate.spi.TreatedNavigablePath) NavigablePath(org.hibernate.spi.NavigablePath) EntityIdentifierNavigablePath(org.hibernate.spi.EntityIdentifierNavigablePath) TreatedNavigablePath(org.hibernate.spi.TreatedNavigablePath) FromClauseAccess(org.hibernate.sql.ast.spi.FromClauseAccess) SqlAstCreationState(org.hibernate.sql.ast.spi.SqlAstCreationState) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) EntityFetchSelectImpl(org.hibernate.sql.results.graph.entity.internal.EntityFetchSelectImpl) EntityDelayedFetchImpl(org.hibernate.sql.results.graph.entity.internal.EntityDelayedFetchImpl)

Example 9 with FromClauseAccess

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

the class CollectionIdentifierDescriptorImpl method generateFetch.

@Override
public Fetch generateFetch(FetchParent fetchParent, NavigablePath fetchablePath, FetchTiming fetchTiming, boolean selected, String resultVariable, DomainResultCreationState creationState) {
    // get the collection TableGroup
    final FromClauseAccess fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess();
    final TableGroup tableGroup = fromClauseAccess.getTableGroup(fetchablePath.getParent());
    final SqlAstCreationState astCreationState = creationState.getSqlAstCreationState();
    final SqlAstCreationContext astCreationContext = astCreationState.getCreationContext();
    final SessionFactoryImplementor sessionFactory = astCreationContext.getSessionFactory();
    final SqlExpressionResolver sqlExpressionResolver = astCreationState.getSqlExpressionResolver();
    final SqlSelection sqlSelection = sqlExpressionResolver.resolveSqlSelection(sqlExpressionResolver.resolveSqlExpression(SqlExpressionResolver.createColumnReferenceKey(tableGroup.getPrimaryTableReference(), columnName), p -> new ColumnReference(tableGroup.getPrimaryTableReference().getIdentificationVariable(), columnName, false, null, null, type, sessionFactory)), type.getJavaTypeDescriptor(), fetchParent, sessionFactory.getTypeConfiguration());
    return new BasicFetch<>(sqlSelection.getValuesArrayPosition(), fetchParent, fetchablePath, this, null, FetchTiming.IMMEDIATE, creationState);
}
Also used : DomainResultCreationState(org.hibernate.sql.results.graph.DomainResultCreationState) JdbcMapping(org.hibernate.metamodel.mapping.JdbcMapping) BasicType(org.hibernate.type.BasicType) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference) JavaType(org.hibernate.type.descriptor.java.JavaType) CollectionIdentifierDescriptor(org.hibernate.metamodel.mapping.CollectionIdentifierDescriptor) Clause(org.hibernate.sql.ast.Clause) BasicFetch(org.hibernate.sql.results.graph.basic.BasicFetch) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) MappingType(org.hibernate.metamodel.mapping.MappingType) SqlAstCreationContext(org.hibernate.sql.ast.spi.SqlAstCreationContext) FetchOptions(org.hibernate.sql.results.graph.FetchOptions) 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) FetchTiming(org.hibernate.engine.FetchTiming) DomainResult(org.hibernate.sql.results.graph.DomainResult) NavigablePath(org.hibernate.spi.NavigablePath) Fetch(org.hibernate.sql.results.graph.Fetch) BasicResult(org.hibernate.sql.results.graph.basic.BasicResult) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) NavigableRole(org.hibernate.metamodel.model.domain.NavigableRole) FetchStyle(org.hibernate.engine.FetchStyle) FromClauseAccess(org.hibernate.sql.ast.spi.FromClauseAccess) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) IndexedConsumer(org.hibernate.mapping.IndexedConsumer) FetchParent(org.hibernate.sql.results.graph.FetchParent) BasicFetch(org.hibernate.sql.results.graph.basic.BasicFetch) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) FromClauseAccess(org.hibernate.sql.ast.spi.FromClauseAccess) SqlAstCreationContext(org.hibernate.sql.ast.spi.SqlAstCreationContext) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) SqlAstCreationState(org.hibernate.sql.ast.spi.SqlAstCreationState) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SqlSelection(org.hibernate.sql.ast.spi.SqlSelection) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 10 with FromClauseAccess

use of org.hibernate.sql.ast.spi.FromClauseAccess 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) List(java.util.List) ArrayList(java.util.ArrayList) 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)

Aggregations

FromClauseAccess (org.hibernate.sql.ast.spi.FromClauseAccess)16 TableGroup (org.hibernate.sql.ast.tree.from.TableGroup)15 NavigablePath (org.hibernate.spi.NavigablePath)9 CorrelatedTableGroup (org.hibernate.sql.ast.tree.from.CorrelatedTableGroup)9 LazyTableGroup (org.hibernate.sql.ast.tree.from.LazyTableGroup)9 PluralTableGroup (org.hibernate.sql.ast.tree.from.PluralTableGroup)9 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)6 SqlSelection (org.hibernate.sql.ast.spi.SqlSelection)6 ColumnReference (org.hibernate.sql.ast.tree.expression.ColumnReference)6 Expression (org.hibernate.sql.ast.tree.expression.Expression)6 PluralAttributeMapping (org.hibernate.metamodel.mapping.PluralAttributeMapping)5 SqlAstCreationState (org.hibernate.sql.ast.spi.SqlAstCreationState)5 CollectionPart (org.hibernate.metamodel.mapping.CollectionPart)4 ModelPart (org.hibernate.metamodel.mapping.ModelPart)4 SqmQuerySpec (org.hibernate.query.sqm.tree.select.SqmQuerySpec)4 SqlSelectionExpression (org.hibernate.sql.ast.tree.expression.SqlSelectionExpression)4 CorrelatedPluralTableGroup (org.hibernate.sql.ast.tree.from.CorrelatedPluralTableGroup)4 QueryPartTableGroup (org.hibernate.sql.ast.tree.from.QueryPartTableGroup)4 SyntheticVirtualTableGroup (org.hibernate.sql.ast.tree.from.SyntheticVirtualTableGroup)4 TableReference (org.hibernate.sql.ast.tree.from.TableReference)4