Search in sources :

Example 16 with PluralAttributeMapping

use of org.hibernate.metamodel.mapping.PluralAttributeMapping in project hibernate-orm by hibernate.

the class TemporaryTable method createIdTable.

public static TemporaryTable createIdTable(EntityMappingType entityDescriptor, Function<String, String> temporaryTableNameAdjuster, Dialect dialect, RuntimeModelCreationContext runtimeModelCreationContext) {
    return new TemporaryTable(entityDescriptor, temporaryTableNameAdjuster, dialect, temporaryTable -> {
        final List<TemporaryTableColumn> columns = new ArrayList<>();
        final PersistentClass entityBinding = runtimeModelCreationContext.getBootModel().getEntityBinding(entityDescriptor.getEntityName());
        final Iterator<JdbcMapping> jdbcMappings = entityDescriptor.getIdentifierMapping().getJdbcMappings().iterator();
        for (Column column : entityBinding.getKey().getColumns()) {
            final JdbcMapping jdbcMapping = jdbcMappings.next();
            columns.add(new TemporaryTableColumn(temporaryTable, column.getText(dialect), jdbcMapping, column.getSqlType(dialect, runtimeModelCreationContext.getMetadata()), column.isNullable(), true));
        }
        entityDescriptor.visitSubTypeAttributeMappings(attribute -> {
            if (attribute instanceof PluralAttributeMapping) {
                final PluralAttributeMapping pluralAttribute = (PluralAttributeMapping) attribute;
                if (pluralAttribute.getSeparateCollectionTable() != null) {
                    // Ensure that the FK target columns are available
                    ForeignKeyDescriptor keyDescriptor = pluralAttribute.getKeyDescriptor();
                    if (keyDescriptor == null) {
                        // and the callback is re-queued.
                        throw new IllegalStateException("Not yet ready: " + pluralAttribute);
                    }
                    final ModelPart fkTarget = keyDescriptor.getTargetPart();
                    if (!(fkTarget instanceof EntityIdentifierMapping)) {
                        final Value value = entityBinding.getSubclassProperty(pluralAttribute.getAttributeName()).getValue();
                        final Iterator<Selectable> columnIterator = ((Collection) value).getKey().getColumnIterator();
                        fkTarget.forEachSelectable((columnIndex, selection) -> {
                            final Selectable selectable = columnIterator.next();
                            if (selectable instanceof Column) {
                                final Column column = (Column) selectable;
                                columns.add(new TemporaryTableColumn(temporaryTable, selectable.getText(dialect), selection.getJdbcMapping(), column.getSqlType(dialect, runtimeModelCreationContext.getMetadata()), column.isNullable()));
                            }
                        });
                    }
                }
            }
        });
        return columns;
    });
}
Also used : JdbcMapping(org.hibernate.metamodel.mapping.JdbcMapping) ModelPart(org.hibernate.metamodel.mapping.ModelPart) ArrayList(java.util.ArrayList) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) Column(org.hibernate.mapping.Column) Selectable(org.hibernate.mapping.Selectable) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) SimpleValue(org.hibernate.mapping.SimpleValue) Value(org.hibernate.mapping.Value) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 17 with PluralAttributeMapping

use of org.hibernate.metamodel.mapping.PluralAttributeMapping in project hibernate-orm by hibernate.

the class BaseSqmToSqlAstConverter method visitTableGroup.

private Expression visitTableGroup(TableGroup tableGroup, SqmFrom<?, ?> path) {
    final ModelPartContainer modelPart;
    final MappingModelExpressible<?> inferredValueMapping = getInferredValueMapping();
    // For plain SqmFrom node uses, prefer the mapping type from the context if possible
    if (!(inferredValueMapping instanceof ModelPartContainer)) {
        modelPart = tableGroup.getModelPart();
    } else {
        modelPart = (ModelPartContainer) inferredValueMapping;
    }
    final ModelPart resultModelPart;
    final ModelPart interpretationModelPart;
    final TableGroup parentGroupToUse;
    if (modelPart instanceof ToOneAttributeMapping) {
        final ToOneAttributeMapping toOneAttributeMapping = (ToOneAttributeMapping) modelPart;
        final ModelPart targetPart = toOneAttributeMapping.getForeignKeyDescriptor().getPart(toOneAttributeMapping.getSideNature().inverse());
        if (tableGroup.getModelPart().getPartMappingType() == modelPart.getPartMappingType()) {
            resultModelPart = targetPart;
        } else {
            // If the table group is for a different mapping type i.e. an inheritance subtype,
            // lookup the target part on that mapping type
            resultModelPart = tableGroup.getModelPart().findSubPart(targetPart.getPartName(), null);
        }
        interpretationModelPart = modelPart;
        parentGroupToUse = null;
    } else if (modelPart instanceof PluralAttributeMapping) {
        final PluralAttributeMapping pluralAttributeMapping = (PluralAttributeMapping) modelPart;
        final CollectionPart elementDescriptor = pluralAttributeMapping.getElementDescriptor();
        if (elementDescriptor instanceof EntityCollectionPart) {
            // Usually, we need to resolve to the PK for visitTableGroup
            final EntityCollectionPart collectionPart = (EntityCollectionPart) elementDescriptor;
            final ModelPart collectionTargetPart = collectionPart.getForeignKeyDescriptor().getPart(collectionPart.getSideNature().inverse());
            final EntityIdentifierMapping identifierMapping = collectionPart.getEntityMappingType().getIdentifierMapping();
            // If the FK points to the PK, we can use the FK part though, if this is not a root
            if (collectionTargetPart == identifierMapping && !(path instanceof SqmRoot<?>)) {
                resultModelPart = collectionPart.getForeignKeyDescriptor().getPart(collectionPart.getSideNature());
            } else {
                resultModelPart = identifierMapping;
            }
        } else {
            resultModelPart = elementDescriptor;
        }
        interpretationModelPart = elementDescriptor;
        parentGroupToUse = null;
    } else if (modelPart instanceof EntityCollectionPart) {
        // Usually, we need to resolve to the PK for visitTableGroup
        final EntityCollectionPart collectionPart = (EntityCollectionPart) modelPart;
        final ModelPart collectionTargetPart = collectionPart.getForeignKeyDescriptor().getPart(collectionPart.getSideNature().inverse());
        final EntityIdentifierMapping identifierMapping = collectionPart.getEntityMappingType().getIdentifierMapping();
        // If the FK points to the PK, we can use the FK part though, if this is not a root
        if (collectionTargetPart == identifierMapping && !(path instanceof SqmRoot<?>)) {
            resultModelPart = collectionPart.getForeignKeyDescriptor().getPart(collectionPart.getSideNature());
        } else {
            resultModelPart = identifierMapping;
        }
        interpretationModelPart = modelPart;
        parentGroupToUse = findTableGroup(tableGroup.getNavigablePath().getParent());
    } else if (modelPart instanceof EntityMappingType) {
        resultModelPart = ((EntityMappingType) modelPart).getIdentifierMapping();
        interpretationModelPart = modelPart;
        // todo: I think this will always be null anyways because EntityMappingType will only be the model part
        // of a TableGroup if that is a root TableGroup, so check if we can just switch to null
        parentGroupToUse = findTableGroup(tableGroup.getNavigablePath().getParent());
    } else {
        resultModelPart = modelPart;
        interpretationModelPart = modelPart;
        parentGroupToUse = null;
    }
    final NavigablePath navigablePath;
    if (interpretationModelPart == modelPart) {
        navigablePath = tableGroup.getNavigablePath();
    } else {
        navigablePath = tableGroup.getNavigablePath().append(interpretationModelPart.getPartName());
    }
    final Expression result;
    if (interpretationModelPart instanceof EntityValuedModelPart) {
        final boolean expandToAllColumns;
        if (currentClauseStack.getCurrent() == Clause.GROUP) {
            // When the table group is known to be fetched i.e. a fetch join
            // but also when the from clause is part of the select clause
            // we need to expand to all columns, as we also expand this to all columns in the select clause
            expandToAllColumns = tableGroup.isFetched() || selectClauseContains(path);
        } else {
            expandToAllColumns = false;
        }
        final EntityValuedModelPart mapping = (EntityValuedModelPart) interpretationModelPart;
        EntityMappingType mappingType;
        if (path instanceof SqmTreatedPath) {
            mappingType = creationContext.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().findEntityDescriptor(((SqmTreatedPath<?, ?>) path).getTreatTarget().getHibernateEntityName());
        } else {
            mappingType = mapping.getEntityMappingType();
        }
        result = EntityValuedPathInterpretation.from(navigablePath, parentGroupToUse == null ? tableGroup : parentGroupToUse, expandToAllColumns ? null : resultModelPart, (EntityValuedModelPart) interpretationModelPart, mappingType, this);
    } else if (interpretationModelPart instanceof EmbeddableValuedModelPart) {
        final EmbeddableValuedModelPart mapping = (EmbeddableValuedModelPart) resultModelPart;
        result = new EmbeddableValuedPathInterpretation<>(mapping.toSqlExpression(tableGroup, currentClauseStack.getCurrent(), this, getSqlAstCreationState()), navigablePath, (EmbeddableValuedModelPart) interpretationModelPart, tableGroup);
    } else {
        assert interpretationModelPart instanceof BasicValuedModelPart;
        final BasicValuedModelPart mapping = (BasicValuedModelPart) resultModelPart;
        final TableReference tableReference = tableGroup.resolveTableReference(navigablePath.append(resultModelPart.getPartName()), mapping.getContainingTableExpression());
        final Expression expression = getSqlExpressionResolver().resolveSqlExpression(SqlExpressionResolver.createColumnReferenceKey(tableReference, mapping.getSelectionExpression()), sacs -> new ColumnReference(tableReference.getIdentificationVariable(), mapping, 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);
        }
        result = new BasicValuedPathInterpretation<>(columnReference, navigablePath, (BasicValuedModelPart) interpretationModelPart, tableGroup);
    }
    return withTreatRestriction(result, path);
}
Also used : VirtualTableGroup(org.hibernate.sql.ast.tree.from.VirtualTableGroup) SqmToDuration(org.hibernate.query.sqm.tree.expression.SqmToDuration) Statement(org.hibernate.sql.ast.tree.Statement) Format(org.hibernate.sql.ast.tree.expression.Format) SqlExpressible(org.hibernate.metamodel.mapping.SqlExpressible) SqmFieldLiteral(org.hibernate.query.sqm.tree.expression.SqmFieldLiteral) BasicType(org.hibernate.type.BasicType) MultipleBagFetchException(org.hibernate.loader.MultipleBagFetchException) BaseSemanticQueryWalker(org.hibernate.query.sqm.spi.BaseSemanticQueryWalker) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) EntityCollectionPart(org.hibernate.metamodel.mapping.internal.EntityCollectionPart) UNARY_MINUS(org.hibernate.query.sqm.UnaryArithmeticOperator.UNARY_MINUS) SqlTypes(org.hibernate.type.SqlTypes) JdbcMappingContainer(org.hibernate.metamodel.mapping.JdbcMappingContainer) SelfInterpretingSqmPath(org.hibernate.query.sqm.sql.internal.SelfInterpretingSqmPath) PostInsertIdentifierGenerator(org.hibernate.id.PostInsertIdentifierGenerator) Map(java.util.Map) FetchProfile(org.hibernate.engine.profile.FetchProfile) BigInteger(java.math.BigInteger) EntityVersionMapping(org.hibernate.metamodel.mapping.EntityVersionMapping) PluralValuedSimplePathInterpretation(org.hibernate.query.sqm.sql.internal.PluralValuedSimplePathInterpretation) SqmSearchClauseSpecification(org.hibernate.query.sqm.tree.cte.SqmSearchClauseSpecification) SqmCorrelatedRootJoin(org.hibernate.query.sqm.tree.domain.SqmCorrelatedRootJoin) SqlSelection(org.hibernate.sql.ast.spi.SqlSelection) IdentifierGenerator(org.hibernate.id.IdentifierGenerator) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) JdbcType(org.hibernate.type.descriptor.jdbc.JdbcType) InferredBasicValueResolver(org.hibernate.boot.model.process.internal.InferredBasicValueResolver) SqmSummarization(org.hibernate.query.sqm.tree.expression.SqmSummarization) FetchClauseType(org.hibernate.query.sqm.FetchClauseType) LazyTableGroup(org.hibernate.sql.ast.tree.from.LazyTableGroup) Optimizer(org.hibernate.id.enhanced.Optimizer) NavigablePath(org.hibernate.query.spi.NavigablePath) AbstractSqlAstTranslator(org.hibernate.sql.ast.spi.AbstractSqlAstTranslator) PreparedStatement(java.sql.PreparedStatement) SqmBooleanExpressionPredicate(org.hibernate.query.sqm.tree.predicate.SqmBooleanExpressionPredicate) SqmQueryPart(org.hibernate.query.sqm.tree.select.SqmQueryPart) SqlAliasBase(org.hibernate.sql.ast.spi.SqlAliasBase) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) StandardStack(org.hibernate.internal.util.collections.StandardStack) SelectStatement(org.hibernate.sql.ast.tree.select.SelectStatement) SqmCteContainer(org.hibernate.query.sqm.tree.cte.SqmCteContainer) SqmJoin(org.hibernate.query.sqm.tree.from.SqmJoin) Overflow(org.hibernate.sql.ast.tree.expression.Overflow) SECOND(org.hibernate.query.sqm.TemporalUnit.SECOND) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) SqmPath(org.hibernate.query.sqm.tree.domain.SqmPath) FetchParent(org.hibernate.sql.results.graph.FetchParent) SqlAliasBaseGenerator(org.hibernate.sql.ast.spi.SqlAliasBaseGenerator) FilterHelper(org.hibernate.internal.FilterHelper) QueryOptions(org.hibernate.query.spi.QueryOptions) SqmParameterInterpretation(org.hibernate.query.sqm.sql.internal.SqmParameterInterpretation) SearchClauseSpecification(org.hibernate.sql.ast.tree.cte.SearchClauseSpecification) JdbcTypeIndicators(org.hibernate.type.descriptor.jdbc.JdbcTypeIndicators) SelfRenderingPredicate(org.hibernate.sql.ast.tree.predicate.SelfRenderingPredicate) SqmBasicValuedSimplePath(org.hibernate.query.sqm.tree.domain.SqmBasicValuedSimplePath) Supplier(java.util.function.Supplier) SemanticException(org.hibernate.query.SemanticException) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings) SqmIndexAggregateFunction(org.hibernate.query.sqm.tree.domain.SqmIndexAggregateFunction) LinkedHashMap(java.util.LinkedHashMap) CteTable(org.hibernate.sql.ast.tree.cte.CteTable) NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) BasicSqmPathSource(org.hibernate.metamodel.model.domain.internal.BasicSqmPathSource) SqmTuple(org.hibernate.query.sqm.tree.expression.SqmTuple) SqmQuerySpec(org.hibernate.query.sqm.tree.select.SqmQuerySpec) BasicDomainType(org.hibernate.metamodel.model.domain.BasicDomainType) SqmSetClause(org.hibernate.query.sqm.tree.update.SqmSetClause) BinaryArithmeticExpression(org.hibernate.sql.ast.tree.expression.BinaryArithmeticExpression) SqmDynamicInstantiationTarget(org.hibernate.query.sqm.tree.select.SqmDynamicInstantiationTarget) ToOneAttributeMapping(org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping) NegatedPredicate(org.hibernate.sql.ast.tree.predicate.NegatedPredicate) TimestampaddFunction(org.hibernate.dialect.function.TimestampaddFunction) JpaCriteriaParameter(org.hibernate.query.sqm.tree.expression.JpaCriteriaParameter) SqmVisitableNode(org.hibernate.query.sqm.tree.SqmVisitableNode) BasicJavaType(org.hibernate.type.descriptor.java.BasicJavaType) DeleteStatement(org.hibernate.sql.ast.tree.delete.DeleteStatement) ModelPartContainer(org.hibernate.metamodel.mapping.ModelPartContainer) QueryParameterBindings(org.hibernate.query.spi.QueryParameterBindings) SqmOver(org.hibernate.query.sqm.tree.expression.SqmOver) LikePredicate(org.hibernate.sql.ast.tree.predicate.LikePredicate) EntityDiscriminatorMapping(org.hibernate.metamodel.mapping.EntityDiscriminatorMapping) QueryLiteral(org.hibernate.sql.ast.tree.expression.QueryLiteral) SqlTypedMapping(org.hibernate.metamodel.mapping.SqlTypedMapping) Fetch(org.hibernate.sql.results.graph.Fetch) EntityGraphTraversalState(org.hibernate.sql.results.graph.EntityGraphTraversalState) FromClauseAccess(org.hibernate.sql.ast.spi.FromClauseAccess) SUBTRACT(org.hibernate.query.sqm.BinaryArithmeticOperator.SUBTRACT) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) SqmFromClause(org.hibernate.query.sqm.tree.from.SqmFromClause) SqmRoot(org.hibernate.query.sqm.tree.from.SqmRoot) DomainParameterXref(org.hibernate.query.sqm.internal.DomainParameterXref) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) DynamicInstantiationNature(org.hibernate.query.sqm.DynamicInstantiationNature) JdbcParametersImpl(org.hibernate.sql.exec.internal.JdbcParametersImpl) UserVersionType(org.hibernate.usertype.UserVersionType) Bindable(org.hibernate.metamodel.mapping.Bindable) EntityPersister(org.hibernate.persister.entity.EntityPersister) SqlAstProcessingStateImpl(org.hibernate.query.sqm.sql.internal.SqlAstProcessingStateImpl) PredicateCollector(org.hibernate.sql.ast.tree.predicate.PredicateCollector) ADD(org.hibernate.query.sqm.BinaryArithmeticOperator.ADD) TimestampdiffFunction(org.hibernate.dialect.function.TimestampdiffFunction) CompositeSqmPathSource(org.hibernate.metamodel.model.domain.internal.CompositeSqmPathSource) TableGroupJoin(org.hibernate.sql.ast.tree.from.TableGroupJoin) NotYetImplementedFor6Exception(org.hibernate.NotYetImplementedFor6Exception) SqmModifiedSubQueryExpression(org.hibernate.query.sqm.tree.expression.SqmModifiedSubQueryExpression) SqmSortSpecification(org.hibernate.query.sqm.tree.select.SqmSortSpecification) SqmCaseSearched(org.hibernate.query.sqm.tree.expression.SqmCaseSearched) SqmIndexedCollectionAccessPath(org.hibernate.query.sqm.tree.domain.SqmIndexedCollectionAccessPath) SqmLiteralNull(org.hibernate.query.sqm.tree.expression.SqmLiteralNull) Locale(java.util.Locale) ConvertibleModelPart(org.hibernate.metamodel.mapping.ConvertibleModelPart) SqmMapEntryReference(org.hibernate.query.sqm.tree.domain.SqmMapEntryReference) BetweenPredicate(org.hibernate.sql.ast.tree.predicate.BetweenPredicate) AbstractJdbcParameter(org.hibernate.sql.exec.internal.AbstractJdbcParameter) JdbcParameterImpl(org.hibernate.sql.exec.internal.JdbcParameterImpl) SqmOverflow(org.hibernate.query.sqm.tree.expression.SqmOverflow) ComparisonOperator(org.hibernate.query.sqm.ComparisonOperator) SqmInsertSelectStatement(org.hibernate.query.sqm.tree.insert.SqmInsertSelectStatement) CollectionPart(org.hibernate.metamodel.mapping.CollectionPart) CorrelatedTableGroup(org.hibernate.sql.ast.tree.from.CorrelatedTableGroup) Assignable(org.hibernate.sql.ast.tree.update.Assignable) SqmPredicate(org.hibernate.query.sqm.tree.predicate.SqmPredicate) Any(org.hibernate.sql.ast.tree.expression.Any) Assignment(org.hibernate.sql.ast.tree.update.Assignment) SqmSelectStatement(org.hibernate.query.sqm.tree.select.SqmSelectStatement) SelfRenderingFunctionSqlAstExpression(org.hibernate.query.sqm.function.SelfRenderingFunctionSqlAstExpression) Collection(java.util.Collection) SingleTableEntityPersister(org.hibernate.persister.entity.SingleTableEntityPersister) BasicValuedMapping(org.hibernate.metamodel.mapping.BasicValuedMapping) OrderByFragment(org.hibernate.metamodel.mapping.ordering.OrderByFragment) SqmBinaryArithmetic(org.hibernate.query.sqm.tree.expression.SqmBinaryArithmetic) SqmJpaCriteriaParameterWrapper(org.hibernate.query.sqm.tree.expression.SqmJpaCriteriaParameterWrapper) SqmAnyValuedSimplePath(org.hibernate.query.sqm.tree.domain.SqmAnyValuedSimplePath) UpdateStatement(org.hibernate.sql.ast.tree.update.UpdateStatement) SqmNegatedPredicate(org.hibernate.query.sqm.tree.predicate.SqmNegatedPredicate) QueryTransformer(org.hibernate.sql.ast.tree.expression.QueryTransformer) SqlAstProcessingState(org.hibernate.sql.ast.spi.SqlAstProcessingState) CorrelatedPluralTableGroup(org.hibernate.sql.ast.tree.from.CorrelatedPluralTableGroup) EntityTypeLiteral(org.hibernate.sql.ast.tree.expression.EntityTypeLiteral) QueryParameterImplementor(org.hibernate.query.spi.QueryParameterImplementor) SqmExtractUnit(org.hibernate.query.sqm.tree.expression.SqmExtractUnit) SqmCrossJoin(org.hibernate.query.sqm.tree.from.SqmCrossJoin) ExistsPredicate(org.hibernate.sql.ast.tree.predicate.ExistsPredicate) SqmFrom(org.hibernate.query.sqm.tree.from.SqmFrom) NullnessHelper.coalesceSuppliedValues(org.hibernate.internal.util.NullnessHelper.coalesceSuppliedValues) SqmPositionalParameter(org.hibernate.query.sqm.tree.expression.SqmPositionalParameter) DomainResultCreationState(org.hibernate.sql.results.graph.DomainResultCreationState) SqmAliasedNode(org.hibernate.query.sqm.tree.select.SqmAliasedNode) SqmDynamicInstantiationArgument(org.hibernate.query.sqm.tree.select.SqmDynamicInstantiationArgument) SqmSelectableNode(org.hibernate.query.sqm.tree.select.SqmSelectableNode) JdbcMapping(org.hibernate.metamodel.mapping.JdbcMapping) NATIVE(org.hibernate.query.sqm.TemporalUnit.NATIVE) Logger(org.jboss.logging.Logger) UnaryOperation(org.hibernate.sql.ast.tree.expression.UnaryOperation) OptimizableGenerator(org.hibernate.id.OptimizableGenerator) SqmParameterizedEntityType(org.hibernate.query.sqm.tree.expression.SqmParameterizedEntityType) Function(java.util.function.Function) SortOrder(org.hibernate.query.sqm.SortOrder) Duration(org.hibernate.sql.ast.tree.expression.Duration) SqmEnumLiteral(org.hibernate.query.sqm.tree.expression.SqmEnumLiteral) ExtractUnit(org.hibernate.sql.ast.tree.expression.ExtractUnit) TableReference(org.hibernate.sql.ast.tree.from.TableReference) HashSet(java.util.HashSet) ModelPart(org.hibernate.metamodel.mapping.ModelPart) SqmTreatedRoot(org.hibernate.query.sqm.tree.domain.SqmTreatedRoot) SqmEvery(org.hibernate.query.sqm.tree.expression.SqmEvery) SqmNamedParameter(org.hibernate.query.sqm.tree.expression.SqmNamedParameter) SqlTreeCreationException(org.hibernate.sql.ast.SqlTreeCreationException) BinaryArithmeticOperator(org.hibernate.query.sqm.BinaryArithmeticOperator) SqmAndPredicate(org.hibernate.query.sqm.tree.predicate.SqmAndPredicate) SqlAliasBaseManager(org.hibernate.sql.ast.spi.SqlAliasBaseManager) SqmByUnit(org.hibernate.query.sqm.tree.expression.SqmByUnit) SqlAstQueryPartProcessingStateImpl(org.hibernate.query.sqm.sql.internal.SqlAstQueryPartProcessingStateImpl) CompositeNestedGeneratedValueGenerator(org.hibernate.id.CompositeNestedGeneratedValueGenerator) SqmMemberOfPredicate(org.hibernate.query.sqm.tree.predicate.SqmMemberOfPredicate) Values(org.hibernate.sql.ast.tree.insert.Values) DomainResultProducer(org.hibernate.query.sqm.sql.internal.DomainResultProducer) SelfRenderingAggregateFunctionSqlAstExpression(org.hibernate.query.sqm.function.SelfRenderingAggregateFunctionSqlAstExpression) AppliedGraph(org.hibernate.graph.spi.AppliedGraph) QueryGroup(org.hibernate.sql.ast.tree.select.QueryGroup) DiscriminatedAssociationPathInterpretation(org.hibernate.query.sqm.sql.internal.DiscriminatedAssociationPathInterpretation) SqmUnaryOperation(org.hibernate.query.sqm.tree.expression.SqmUnaryOperation) QueryPartTableReference(org.hibernate.sql.ast.tree.from.QueryPartTableReference) PluralPersistentAttribute(org.hibernate.metamodel.model.domain.PluralPersistentAttribute) UnaryArithmeticOperator(org.hibernate.query.sqm.UnaryArithmeticOperator) Consumer(java.util.function.Consumer) AbstractMap(java.util.AbstractMap) CaseSearchedExpression(org.hibernate.sql.ast.tree.expression.CaseSearchedExpression) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) SqmInsertStatement(org.hibernate.query.sqm.tree.insert.SqmInsertStatement) SelectableMapping(org.hibernate.metamodel.mapping.SelectableMapping) SqlTypedMappingJdbcParameter(org.hibernate.sql.exec.internal.SqlTypedMappingJdbcParameter) SqmPluralPartJoin(org.hibernate.query.sqm.tree.domain.SqmPluralPartJoin) NonAggregatedCompositeSimplePath(org.hibernate.query.sqm.tree.domain.NonAggregatedCompositeSimplePath) BasicValueConverter(org.hibernate.metamodel.model.convert.spi.BasicValueConverter) PluralTableGroup(org.hibernate.sql.ast.tree.from.PluralTableGroup) Arrays(java.util.Arrays) SqmExpressible(org.hibernate.query.sqm.SqmExpressible) SqmFormat(org.hibernate.query.sqm.tree.expression.SqmFormat) EPOCH(org.hibernate.query.sqm.TemporalUnit.EPOCH) SqmAttributeJoin(org.hibernate.query.sqm.tree.from.SqmAttributeJoin) SqmCaseSimple(org.hibernate.query.sqm.tree.expression.SqmCaseSimple) SqlAstTreeHelper(org.hibernate.sql.ast.spi.SqlAstTreeHelper) EntityValuedModelPart(org.hibernate.metamodel.mapping.EntityValuedModelPart) SqmLikePredicate(org.hibernate.query.sqm.tree.predicate.SqmLikePredicate) Internal(org.hibernate.Internal) SqmStatement(org.hibernate.query.sqm.tree.SqmStatement) SqmPluralValuedSimplePath(org.hibernate.query.sqm.tree.domain.SqmPluralValuedSimplePath) SqmTreatedPath(org.hibernate.query.sqm.tree.domain.SqmTreatedPath) BigDecimal(java.math.BigDecimal) SqmAliasedNodeRef(org.hibernate.query.sqm.tree.expression.SqmAliasedNodeRef) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) BindableType(org.hibernate.query.BindableType) SqmExistsPredicate(org.hibernate.query.sqm.tree.predicate.SqmExistsPredicate) SqmEmbeddedValuedSimplePath(org.hibernate.query.sqm.tree.domain.SqmEmbeddedValuedSimplePath) EntityValuedPathInterpretation(org.hibernate.query.sqm.sql.internal.EntityValuedPathInterpretation) PatternRenderer(org.hibernate.query.sqm.produce.function.internal.PatternRenderer) SqmCastTarget(org.hibernate.query.sqm.tree.expression.SqmCastTarget) Fetchable(org.hibernate.sql.results.graph.Fetchable) DAY(org.hibernate.query.sqm.TemporalUnit.DAY) SelfRenderingSqlFragmentExpression(org.hibernate.sql.ast.tree.expression.SelfRenderingSqlFragmentExpression) ConvertedQueryLiteral(org.hibernate.sql.ast.tree.expression.ConvertedQueryLiteral) TypeConfiguration(org.hibernate.type.spi.TypeConfiguration) SqmEntityValuedSimplePath(org.hibernate.query.sqm.tree.domain.SqmEntityValuedSimplePath) Set(java.util.Set) Expression(org.hibernate.sql.ast.tree.expression.Expression) TemporalUnit(org.hibernate.query.sqm.TemporalUnit) SqmCollectionSize(org.hibernate.query.sqm.tree.expression.SqmCollectionSize) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) SqmTrimSpecification(org.hibernate.query.sqm.tree.expression.SqmTrimSpecification) SqlAstQueryPartProcessingState(org.hibernate.sql.ast.spi.SqlAstQueryPartProcessingState) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple) JpaPath(org.hibernate.query.criteria.JpaPath) Star(org.hibernate.sql.ast.tree.expression.Star) SqmParameter(org.hibernate.query.sqm.tree.expression.SqmParameter) ValueMapping(org.hibernate.metamodel.mapping.ValueMapping) SqmPathSource(org.hibernate.query.sqm.SqmPathSource) Conversion(org.hibernate.query.sqm.tree.expression.Conversion) InsertStatement(org.hibernate.sql.ast.tree.insert.InsertStatement) SqlTypedMappingImpl(org.hibernate.metamodel.mapping.internal.SqlTypedMappingImpl) SqmJoinType(org.hibernate.query.sqm.tree.SqmJoinType) SqmCollation(org.hibernate.query.sqm.tree.expression.SqmCollation) HibernateException(org.hibernate.HibernateException) QueryException(org.hibernate.QueryException) SqmSelectClause(org.hibernate.query.sqm.tree.select.SqmSelectClause) SqmAny(org.hibernate.query.sqm.tree.expression.SqmAny) JdbcLiteral(org.hibernate.sql.ast.tree.expression.JdbcLiteral) NonAggregatedCompositeValuedPathInterpretation(org.hibernate.query.sqm.sql.internal.NonAggregatedCompositeValuedPathInterpretation) SqmLiteralEntityType(org.hibernate.query.sqm.tree.expression.SqmLiteralEntityType) CteContainer(org.hibernate.sql.ast.tree.cte.CteContainer) Distinct(org.hibernate.sql.ast.tree.expression.Distinct) JavaType(org.hibernate.type.descriptor.java.JavaType) SqmDurationUnit(org.hibernate.query.sqm.tree.expression.SqmDurationUnit) SqmSubQuery(org.hibernate.query.sqm.tree.select.SqmSubQuery) InterpretationException(org.hibernate.query.sqm.InterpretationException) Clause(org.hibernate.sql.ast.Clause) ArrayList(java.util.ArrayList) SQLException(java.sql.SQLException) EntityDomainType(org.hibernate.metamodel.model.domain.EntityDomainType) SqmOrPredicate(org.hibernate.query.sqm.tree.predicate.SqmOrPredicate) BiConsumer(java.util.function.BiConsumer) QueryParameterBinding(org.hibernate.query.spi.QueryParameterBinding) SqmCorrelation(org.hibernate.query.sqm.tree.domain.SqmCorrelation) SqlAstNode(org.hibernate.sql.ast.tree.SqlAstNode) MULTIPLY(org.hibernate.query.sqm.BinaryArithmeticOperator.MULTIPLY) ReturnableType(org.hibernate.query.ReturnableType) VersionTypeSeedParameterSpecification(org.hibernate.sql.exec.internal.VersionTypeSeedParameterSpecification) FetchTiming(org.hibernate.engine.FetchTiming) BulkInsertionCapableIdentifierGenerator(org.hibernate.id.BulkInsertionCapableIdentifierGenerator) SqmNullnessPredicate(org.hibernate.query.sqm.tree.predicate.SqmNullnessPredicate) DiscriminatorSqmPath(org.hibernate.metamodel.model.domain.internal.DiscriminatorSqmPath) SqmElementAggregateFunction(org.hibernate.query.sqm.tree.domain.SqmElementAggregateFunction) SqmQueryGroup(org.hibernate.query.sqm.tree.select.SqmQueryGroup) SqlTreeCreationLogger(org.hibernate.sql.ast.SqlTreeCreationLogger) StandardEntityGraphTraversalStateImpl(org.hibernate.sql.results.internal.StandardEntityGraphTraversalStateImpl) SqmAssignment(org.hibernate.query.sqm.tree.update.SqmAssignment) CollectionClassification(org.hibernate.metamodel.CollectionClassification) SqmWhereClause(org.hibernate.query.sqm.tree.predicate.SqmWhereClause) SqmComparisonPredicate(org.hibernate.query.sqm.tree.predicate.SqmComparisonPredicate) SqmGroupedPredicate(org.hibernate.query.sqm.tree.predicate.SqmGroupedPredicate) SqmPathInterpretation(org.hibernate.query.sqm.sql.internal.SqmPathInterpretation) SqmValues(org.hibernate.query.sqm.tree.insert.SqmValues) SelfRenderingExpression(org.hibernate.sql.ast.tree.expression.SelfRenderingExpression) CollectionHelper(org.hibernate.internal.util.collections.CollectionHelper) SqmJpaCompoundSelection(org.hibernate.query.sqm.tree.select.SqmJpaCompoundSelection) ExecutionContext(org.hibernate.sql.exec.spi.ExecutionContext) CastTarget(org.hibernate.sql.ast.tree.expression.CastTarget) SqmCteTable(org.hibernate.query.sqm.tree.cte.SqmCteTable) SqmInsertValuesStatement(org.hibernate.query.sqm.tree.insert.SqmInsertValuesStatement) CteStatement(org.hibernate.sql.ast.tree.cte.CteStatement) Joinable(org.hibernate.persister.entity.Joinable) SqmExpression(org.hibernate.query.sqm.tree.expression.SqmExpression) SqmFunction(org.hibernate.query.sqm.tree.expression.SqmFunction) SqlAstCreationContext(org.hibernate.sql.ast.spi.SqlAstCreationContext) SqmEntityJoin(org.hibernate.query.sqm.tree.from.SqmEntityJoin) SqmInListPredicate(org.hibernate.query.sqm.tree.predicate.SqmInListPredicate) ComparisonPredicate(org.hibernate.sql.ast.tree.predicate.ComparisonPredicate) EntityAssociationMapping(org.hibernate.metamodel.mapping.EntityAssociationMapping) EmbeddableValuedPathInterpretation(org.hibernate.query.sqm.sql.internal.EmbeddableValuedPathInterpretation) Summarization(org.hibernate.sql.ast.tree.expression.Summarization) DynamicInstantiation(org.hibernate.sql.results.graph.instantiation.internal.DynamicInstantiation) TypeConfiguration.isDuration(org.hibernate.type.spi.TypeConfiguration.isDuration) SqmUpdateStatement(org.hibernate.query.sqm.tree.update.SqmUpdateStatement) EnumJavaType(org.hibernate.type.descriptor.java.EnumJavaType) SqmMapEntryResult(org.hibernate.query.sqm.sql.internal.SqmMapEntryResult) SqmOrderByClause(org.hibernate.query.sqm.tree.select.SqmOrderByClause) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) TemporalType(jakarta.persistence.TemporalType) TableGroupJoinProducer(org.hibernate.sql.ast.tree.from.TableGroupJoinProducer) SqmDeleteStatement(org.hibernate.query.sqm.tree.delete.SqmDeleteStatement) IdentityHashMap(java.util.IdentityHashMap) NullnessPredicate(org.hibernate.sql.ast.tree.predicate.NullnessPredicate) SqmBetweenPredicate(org.hibernate.query.sqm.tree.predicate.SqmBetweenPredicate) DomainResult(org.hibernate.sql.results.graph.DomainResult) OrdinalEnumValueConverter(org.hibernate.metamodel.model.convert.internal.OrdinalEnumValueConverter) CaseSimpleExpression(org.hibernate.sql.ast.tree.expression.CaseSimpleExpression) GroupedPredicate(org.hibernate.sql.ast.tree.predicate.GroupedPredicate) MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) LoadQueryInfluencers(org.hibernate.engine.spi.LoadQueryInfluencers) List(java.util.List) QueryPartTableGroup(org.hibernate.sql.ast.tree.from.QueryPartTableGroup) BooleanExpressionPredicate(org.hibernate.sql.ast.tree.predicate.BooleanExpressionPredicate) Over(org.hibernate.sql.ast.tree.expression.Over) AbstractEntityPersister(org.hibernate.persister.entity.AbstractEntityPersister) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec) DurationUnit(org.hibernate.sql.ast.tree.expression.DurationUnit) BasicValuedModelPart(org.hibernate.metamodel.mapping.BasicValuedModelPart) Collation(org.hibernate.sql.ast.tree.expression.Collation) InListPredicate(org.hibernate.sql.ast.tree.predicate.InListPredicate) BasicEntityIdentifierMapping(org.hibernate.metamodel.mapping.BasicEntityIdentifierMapping) Junction(org.hibernate.sql.ast.tree.predicate.Junction) SelectableMappings(org.hibernate.metamodel.mapping.SelectableMappings) SqmDistinct(org.hibernate.query.sqm.tree.expression.SqmDistinct) SqmInSubQueryPredicate(org.hibernate.query.sqm.tree.predicate.SqmInSubQueryPredicate) QueryLogging(org.hibernate.query.QueryLogging) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference) HashMap(java.util.HashMap) SqmLiteral(org.hibernate.query.sqm.tree.expression.SqmLiteral) SqmEmptinessPredicate(org.hibernate.query.sqm.tree.predicate.SqmEmptinessPredicate) SortSpecification(org.hibernate.sql.ast.tree.select.SortSpecification) AbstractSqmSpecificPluralPartPath(org.hibernate.query.sqm.tree.domain.AbstractSqmSpecificPluralPartPath) CteColumn(org.hibernate.sql.ast.tree.cte.CteColumn) SqmDynamicInstantiation(org.hibernate.query.sqm.tree.select.SqmDynamicInstantiation) JavaObjectType(org.hibernate.type.JavaObjectType) JdbcParameters(org.hibernate.sql.exec.spi.JdbcParameters) SqlAstCreationState(org.hibernate.sql.ast.spi.SqlAstCreationState) LockMode(org.hibernate.LockMode) Predicate(org.hibernate.sql.ast.tree.predicate.Predicate) Iterator(java.util.Iterator) EmbeddableMappingType(org.hibernate.metamodel.mapping.EmbeddableMappingType) SqmStar(org.hibernate.query.sqm.tree.expression.SqmStar) SqlSelectionExpression(org.hibernate.sql.ast.tree.expression.SqlSelectionExpression) SqmSelection(org.hibernate.query.sqm.tree.select.SqmSelection) SqmQuerySource(org.hibernate.query.sqm.SqmQuerySource) SqmCteStatement(org.hibernate.query.sqm.tree.cte.SqmCteStatement) SqmTypedNode(org.hibernate.query.sqm.tree.SqmTypedNode) EmbeddedCollectionPart(org.hibernate.metamodel.mapping.internal.EmbeddedCollectionPart) AbstractSqmSelfRenderingFunctionDescriptor(org.hibernate.query.sqm.function.AbstractSqmSelfRenderingFunctionDescriptor) TrimSpecification(org.hibernate.sql.ast.tree.expression.TrimSpecification) SelectClause(org.hibernate.sql.ast.tree.select.SelectClause) Association(org.hibernate.metamodel.mapping.Association) CastType(org.hibernate.query.sqm.CastType) SqmCteTableColumn(org.hibernate.query.sqm.tree.cte.SqmCteTableColumn) Every(org.hibernate.sql.ast.tree.expression.Every) SqmMappingModelHelper(org.hibernate.query.sqm.internal.SqmMappingModelHelper) QueryPart(org.hibernate.sql.ast.tree.select.QueryPart) SqlAstJoinType(org.hibernate.sql.ast.SqlAstJoinType) EmbeddableValuedModelPart(org.hibernate.metamodel.mapping.EmbeddableValuedModelPart) Stack(org.hibernate.internal.util.collections.Stack) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) BasicValuedPathInterpretation(org.hibernate.query.sqm.sql.internal.BasicValuedPathInterpretation) Collections(java.util.Collections) EntityTypeImpl(org.hibernate.metamodel.model.domain.internal.EntityTypeImpl) ModifiedSubQueryExpression(org.hibernate.sql.ast.tree.expression.ModifiedSubQueryExpression) NavigablePath(org.hibernate.query.spi.NavigablePath) ConvertibleModelPart(org.hibernate.metamodel.mapping.ConvertibleModelPart) ModelPart(org.hibernate.metamodel.mapping.ModelPart) EntityValuedModelPart(org.hibernate.metamodel.mapping.EntityValuedModelPart) BasicValuedModelPart(org.hibernate.metamodel.mapping.BasicValuedModelPart) EmbeddableValuedModelPart(org.hibernate.metamodel.mapping.EmbeddableValuedModelPart) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) SqmTreatedPath(org.hibernate.query.sqm.tree.domain.SqmTreatedPath) NamedTableReference(org.hibernate.sql.ast.tree.from.NamedTableReference) TableReference(org.hibernate.sql.ast.tree.from.TableReference) QueryPartTableReference(org.hibernate.sql.ast.tree.from.QueryPartTableReference) ToOneAttributeMapping(org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping) EntityValuedModelPart(org.hibernate.metamodel.mapping.EntityValuedModelPart) EntityCollectionPart(org.hibernate.metamodel.mapping.internal.EntityCollectionPart) CollectionPart(org.hibernate.metamodel.mapping.CollectionPart) EmbeddedCollectionPart(org.hibernate.metamodel.mapping.internal.EmbeddedCollectionPart) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) EmbeddableValuedPathInterpretation(org.hibernate.query.sqm.sql.internal.EmbeddableValuedPathInterpretation) EntityCollectionPart(org.hibernate.metamodel.mapping.internal.EntityCollectionPart) VirtualTableGroup(org.hibernate.sql.ast.tree.from.VirtualTableGroup) LazyTableGroup(org.hibernate.sql.ast.tree.from.LazyTableGroup) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) CorrelatedTableGroup(org.hibernate.sql.ast.tree.from.CorrelatedTableGroup) CorrelatedPluralTableGroup(org.hibernate.sql.ast.tree.from.CorrelatedPluralTableGroup) PluralTableGroup(org.hibernate.sql.ast.tree.from.PluralTableGroup) QueryPartTableGroup(org.hibernate.sql.ast.tree.from.QueryPartTableGroup) BasicValuedModelPart(org.hibernate.metamodel.mapping.BasicValuedModelPart) BasicValuedPathInterpretation(org.hibernate.query.sqm.sql.internal.BasicValuedPathInterpretation) SqmRoot(org.hibernate.query.sqm.tree.from.SqmRoot) SqlSelectionExpression(org.hibernate.sql.ast.tree.expression.SqlSelectionExpression) BinaryArithmeticExpression(org.hibernate.sql.ast.tree.expression.BinaryArithmeticExpression) SqmModifiedSubQueryExpression(org.hibernate.query.sqm.tree.expression.SqmModifiedSubQueryExpression) SelfRenderingFunctionSqlAstExpression(org.hibernate.query.sqm.function.SelfRenderingFunctionSqlAstExpression) SelfRenderingAggregateFunctionSqlAstExpression(org.hibernate.query.sqm.function.SelfRenderingAggregateFunctionSqlAstExpression) CaseSearchedExpression(org.hibernate.sql.ast.tree.expression.CaseSearchedExpression) SelfRenderingSqlFragmentExpression(org.hibernate.sql.ast.tree.expression.SelfRenderingSqlFragmentExpression) Expression(org.hibernate.sql.ast.tree.expression.Expression) SelfRenderingExpression(org.hibernate.sql.ast.tree.expression.SelfRenderingExpression) SqmExpression(org.hibernate.query.sqm.tree.expression.SqmExpression) CaseSimpleExpression(org.hibernate.sql.ast.tree.expression.CaseSimpleExpression) SqlSelectionExpression(org.hibernate.sql.ast.tree.expression.SqlSelectionExpression) ModifiedSubQueryExpression(org.hibernate.sql.ast.tree.expression.ModifiedSubQueryExpression) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) BasicEntityIdentifierMapping(org.hibernate.metamodel.mapping.BasicEntityIdentifierMapping) EmbeddableValuedModelPart(org.hibernate.metamodel.mapping.EmbeddableValuedModelPart) ModelPartContainer(org.hibernate.metamodel.mapping.ModelPartContainer) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 18 with PluralAttributeMapping

use of org.hibernate.metamodel.mapping.PluralAttributeMapping in project hibernate-orm by hibernate.

the class BaseSqmToSqlAstConverter method createLateralJoinExpression.

protected Expression createLateralJoinExpression(AbstractSqmSpecificPluralPartPath<?> pluralPartPath, boolean index, String functionName) {
    prepareReusablePath(pluralPartPath.getLhs(), () -> null);
    final PluralAttributeMapping pluralAttributeMapping = (PluralAttributeMapping) determineValueMapping(pluralPartPath.getPluralDomainPath());
    final FromClauseAccess parentFromClauseAccess = getFromClauseAccess();
    final TableGroup parentTableGroup = parentFromClauseAccess.findTableGroup(pluralPartPath.getNavigablePath().getParent());
    final CollectionPart collectionPart = index ? pluralAttributeMapping.getIndexDescriptor() : pluralAttributeMapping.getElementDescriptor();
    final ModelPart modelPart;
    if (collectionPart instanceof EntityAssociationMapping) {
        modelPart = ((EntityAssociationMapping) collectionPart).getKeyTargetMatchPart();
    } else {
        modelPart = collectionPart;
    }
    final int jdbcTypeCount = modelPart.getJdbcTypeCount();
    final String pathName = functionName + (index ? "_index" : "_element");
    final String identifierVariable = parentTableGroup.getPrimaryTableReference().getIdentificationVariable() + "_" + pathName;
    final NavigablePath queryPath = new NavigablePath(parentTableGroup.getNavigablePath(), pathName, identifierVariable);
    TableGroup lateralTableGroup = parentFromClauseAccess.findTableGroup(queryPath);
    if (lateralTableGroup == null) {
        final QuerySpec subQuerySpec = new QuerySpec(false);
        pushProcessingState(new SqlAstQueryPartProcessingStateImpl(subQuerySpec, getCurrentProcessingState(), this, currentClauseStack::getCurrent, false));
        try {
            final TableGroup tableGroup = pluralAttributeMapping.createRootTableGroup(true, pluralPartPath.getNavigablePath(), null, () -> subQuerySpec::applyPredicate, this, creationContext);
            pluralAttributeMapping.applyBaseRestrictions(subQuerySpec::applyPredicate, tableGroup, true, getLoadQueryInfluencers().getEnabledFilters(), null, this);
            getFromClauseAccess().registerTableGroup(pluralPartPath.getNavigablePath(), tableGroup);
            registerPluralTableGroupParts(tableGroup);
            subQuerySpec.getFromClause().addRoot(tableGroup);
            final List<String> columnNames = new ArrayList<>(jdbcTypeCount);
            final List<ColumnReference> resultColumnReferences = new ArrayList<>(jdbcTypeCount);
            final NavigablePath navigablePath = pluralPartPath.getNavigablePath();
            final Boolean max = functionName.equalsIgnoreCase("max") ? Boolean.TRUE : (functionName.equalsIgnoreCase("min") ? Boolean.FALSE : null);
            final AbstractSqmSelfRenderingFunctionDescriptor functionDescriptor = (AbstractSqmSelfRenderingFunctionDescriptor) creationContext.getSessionFactory().getQueryEngine().getSqmFunctionRegistry().findFunctionDescriptor(functionName);
            final List<ColumnReference> subQueryColumns = new ArrayList<>(jdbcTypeCount);
            modelPart.forEachSelectable((selectionIndex, selectionMapping) -> {
                final ColumnReference columnReference = new ColumnReference(tableGroup.resolveTableReference(navigablePath, selectionMapping.getContainingTableExpression()), selectionMapping, creationContext.getSessionFactory());
                final String columnName;
                if (selectionMapping.isFormula()) {
                    columnName = "col" + columnNames.size();
                } else {
                    columnName = selectionMapping.getSelectionExpression();
                }
                columnNames.add(columnName);
                subQueryColumns.add(columnReference);
                if (max != null) {
                    subQuerySpec.addSortSpecification(new SortSpecification(columnReference, max ? SortOrder.DESCENDING : SortOrder.ASCENDING));
                }
            });
            if (max != null) {
                for (int i = 0; i < subQueryColumns.size(); i++) {
                    subQuerySpec.getSelectClause().addSqlSelection(new SqlSelectionImpl(i + 1, i, subQueryColumns.get(i)));
                    resultColumnReferences.add(new ColumnReference(identifierVariable, columnNames.get(i), false, null, null, subQueryColumns.get(i).getJdbcMapping(), creationContext.getSessionFactory()));
                }
                subQuerySpec.setFetchClauseExpression(new QueryLiteral<>(1, basicType(Integer.class)), FetchClauseType.ROWS_ONLY);
            } else {
                final List<? extends SqlAstNode> arguments;
                if (jdbcTypeCount == 1) {
                    arguments = subQueryColumns;
                } else {
                    arguments = Collections.singletonList(new SqlTuple(subQueryColumns, modelPart));
                }
                final Expression expression = new SelfRenderingAggregateFunctionSqlAstExpression(functionDescriptor.getName(), functionDescriptor, arguments, null, (ReturnableType<?>) functionDescriptor.getReturnTypeResolver().resolveFunctionReturnType(() -> null, arguments).getJdbcMapping(), modelPart);
                subQuerySpec.getSelectClause().addSqlSelection(new SqlSelectionImpl(1, 0, expression));
                resultColumnReferences.add(new ColumnReference(identifierVariable, columnNames.get(0), false, null, null, expression.getExpressionType().getJdbcMappings().get(0), creationContext.getSessionFactory()));
            }
            subQuerySpec.applyPredicate(pluralAttributeMapping.getKeyDescriptor().generateJoinPredicate(parentFromClauseAccess.findTableGroup(pluralPartPath.getPluralDomainPath().getNavigablePath().getParent()), tableGroup, getSqlExpressionResolver(), creationContext));
            final String compatibleTableExpression;
            if (modelPart instanceof BasicValuedModelPart) {
                compatibleTableExpression = ((BasicValuedModelPart) modelPart).getContainingTableExpression();
            } else if (modelPart instanceof EmbeddableValuedModelPart) {
                compatibleTableExpression = ((EmbeddableValuedModelPart) modelPart).getContainingTableExpression();
            } else {
                compatibleTableExpression = null;
            }
            lateralTableGroup = new QueryPartTableGroup(queryPath, null, subQuerySpec, identifierVariable, columnNames, compatibleTableExpression, true, false, creationContext.getSessionFactory());
            if (currentlyProcessingJoin == null) {
                parentTableGroup.addTableGroupJoin(new TableGroupJoin(lateralTableGroup.getNavigablePath(), SqlAstJoinType.LEFT, lateralTableGroup));
            } else {
                // In case this is used in the ON condition, we must prepend this lateral join
                final TableGroup targetTableGroup;
                if (currentlyProcessingJoin.getLhs() == null) {
                    targetTableGroup = parentFromClauseAccess.getTableGroup(currentlyProcessingJoin.findRoot().getNavigablePath());
                } else {
                    targetTableGroup = parentFromClauseAccess.getTableGroup(currentlyProcessingJoin.getLhs().getNavigablePath());
                }
                // Many databases would support modelling this as nested table group join,
                // but at least SQL Server doesn't like that, saying that the correlated columns can't be "bound"
                // Since there is no dependency on the currentlyProcessingJoin, we can safely prepend this join
                targetTableGroup.prependTableGroupJoin(currentlyProcessingJoin.getNavigablePath(), new TableGroupJoin(lateralTableGroup.getNavigablePath(), SqlAstJoinType.LEFT, lateralTableGroup));
            }
            parentFromClauseAccess.registerTableGroup(lateralTableGroup.getNavigablePath(), lateralTableGroup);
            if (jdbcTypeCount == 1) {
                return new SelfRenderingFunctionSqlAstExpression(pathName, (sqlAppender, sqlAstArguments, walker) -> {
                    sqlAstArguments.get(0).accept(walker);
                }, resultColumnReferences, (ReturnableType<?>) resultColumnReferences.get(0).getJdbcMapping(), resultColumnReferences.get(0).getJdbcMapping());
            } else {
                return new SqlTuple(resultColumnReferences, modelPart);
            }
        } finally {
            popProcessingStateStack();
        }
    }
    final QueryPartTableReference tableReference = (QueryPartTableReference) lateralTableGroup.getPrimaryTableReference();
    if (jdbcTypeCount == 1) {
        final List<SqlSelection> sqlSelections = tableReference.getQueryPart().getFirstQuerySpec().getSelectClause().getSqlSelections();
        return new SelfRenderingFunctionSqlAstExpression(pathName, (sqlAppender, sqlAstArguments, walker) -> {
            sqlAstArguments.get(0).accept(walker);
        }, Collections.singletonList(new ColumnReference(identifierVariable, tableReference.getColumnNames().get(0), false, null, null, sqlSelections.get(0).getExpressionType().getJdbcMappings().get(0), creationContext.getSessionFactory())), (ReturnableType<?>) sqlSelections.get(0).getExpressionType().getJdbcMappings().get(0), sqlSelections.get(0).getExpressionType());
    } else {
        final List<ColumnReference> resultColumnReferences = new ArrayList<>(jdbcTypeCount);
        modelPart.forEachSelectable((selectionIndex, selectionMapping) -> resultColumnReferences.add(new ColumnReference(identifierVariable, tableReference.getColumnNames().get(selectionIndex), false, null, null, selectionMapping.getJdbcMapping(), creationContext.getSessionFactory())));
        return new SqlTuple(resultColumnReferences, modelPart);
    }
}
Also used : SelfRenderingAggregateFunctionSqlAstExpression(org.hibernate.query.sqm.function.SelfRenderingAggregateFunctionSqlAstExpression) NavigablePath(org.hibernate.query.spi.NavigablePath) ConvertibleModelPart(org.hibernate.metamodel.mapping.ConvertibleModelPart) ModelPart(org.hibernate.metamodel.mapping.ModelPart) EntityValuedModelPart(org.hibernate.metamodel.mapping.EntityValuedModelPart) BasicValuedModelPart(org.hibernate.metamodel.mapping.BasicValuedModelPart) EmbeddableValuedModelPart(org.hibernate.metamodel.mapping.EmbeddableValuedModelPart) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) ArrayList(java.util.ArrayList) SqlSelection(org.hibernate.sql.ast.spi.SqlSelection) AbstractSqmSelfRenderingFunctionDescriptor(org.hibernate.query.sqm.function.AbstractSqmSelfRenderingFunctionDescriptor) TableGroupJoin(org.hibernate.sql.ast.tree.from.TableGroupJoin) SqlAstQueryPartProcessingStateImpl(org.hibernate.query.sqm.sql.internal.SqlAstQueryPartProcessingStateImpl) EntityCollectionPart(org.hibernate.metamodel.mapping.internal.EntityCollectionPart) CollectionPart(org.hibernate.metamodel.mapping.CollectionPart) EmbeddedCollectionPart(org.hibernate.metamodel.mapping.internal.EmbeddedCollectionPart) VirtualTableGroup(org.hibernate.sql.ast.tree.from.VirtualTableGroup) LazyTableGroup(org.hibernate.sql.ast.tree.from.LazyTableGroup) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) CorrelatedTableGroup(org.hibernate.sql.ast.tree.from.CorrelatedTableGroup) CorrelatedPluralTableGroup(org.hibernate.sql.ast.tree.from.CorrelatedPluralTableGroup) PluralTableGroup(org.hibernate.sql.ast.tree.from.PluralTableGroup) QueryPartTableGroup(org.hibernate.sql.ast.tree.from.QueryPartTableGroup) BasicValuedModelPart(org.hibernate.metamodel.mapping.BasicValuedModelPart) EntityAssociationMapping(org.hibernate.metamodel.mapping.EntityAssociationMapping) QueryPartTableGroup(org.hibernate.sql.ast.tree.from.QueryPartTableGroup) FromClauseAccess(org.hibernate.sql.ast.spi.FromClauseAccess) SqmSortSpecification(org.hibernate.query.sqm.tree.select.SqmSortSpecification) SortSpecification(org.hibernate.sql.ast.tree.select.SortSpecification) BinaryArithmeticExpression(org.hibernate.sql.ast.tree.expression.BinaryArithmeticExpression) SqmModifiedSubQueryExpression(org.hibernate.query.sqm.tree.expression.SqmModifiedSubQueryExpression) SelfRenderingFunctionSqlAstExpression(org.hibernate.query.sqm.function.SelfRenderingFunctionSqlAstExpression) SelfRenderingAggregateFunctionSqlAstExpression(org.hibernate.query.sqm.function.SelfRenderingAggregateFunctionSqlAstExpression) CaseSearchedExpression(org.hibernate.sql.ast.tree.expression.CaseSearchedExpression) SelfRenderingSqlFragmentExpression(org.hibernate.sql.ast.tree.expression.SelfRenderingSqlFragmentExpression) Expression(org.hibernate.sql.ast.tree.expression.Expression) SelfRenderingExpression(org.hibernate.sql.ast.tree.expression.SelfRenderingExpression) SqmExpression(org.hibernate.query.sqm.tree.expression.SqmExpression) CaseSimpleExpression(org.hibernate.sql.ast.tree.expression.CaseSimpleExpression) SqlSelectionExpression(org.hibernate.sql.ast.tree.expression.SqlSelectionExpression) ModifiedSubQueryExpression(org.hibernate.sql.ast.tree.expression.ModifiedSubQueryExpression) EmbeddableValuedModelPart(org.hibernate.metamodel.mapping.EmbeddableValuedModelPart) SelfRenderingFunctionSqlAstExpression(org.hibernate.query.sqm.function.SelfRenderingFunctionSqlAstExpression) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple) SqlSelectionImpl(org.hibernate.sql.results.internal.SqlSelectionImpl) SqmQuerySpec(org.hibernate.query.sqm.tree.select.SqmQuerySpec) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec) QueryPartTableReference(org.hibernate.sql.ast.tree.from.QueryPartTableReference) ColumnReference(org.hibernate.sql.ast.tree.expression.ColumnReference)

Example 19 with PluralAttributeMapping

use of org.hibernate.metamodel.mapping.PluralAttributeMapping in project hibernate-orm by hibernate.

the class BaseSqmToSqlAstConverter method visitMapEntryFunction.

@Override
public Object visitMapEntryFunction(SqmMapEntryReference<?, ?> entryRef) {
    final SqmPath<?> mapPath = entryRef.getMapPath();
    prepareReusablePath(mapPath, () -> null);
    final NavigablePath mapNavigablePath = mapPath.getNavigablePath();
    final TableGroup tableGroup = getFromClauseAccess().resolveTableGroup(mapNavigablePath, (navigablePath) -> {
        final TableGroup parentTableGroup = getFromClauseAccess().getTableGroup(mapNavigablePath.getParent());
        final PluralAttributeMapping mapAttribute = (PluralAttributeMapping) parentTableGroup.getModelPart().findSubPart(mapNavigablePath.getLocalName(), null);
        final TableGroupJoin tableGroupJoin = mapAttribute.createTableGroupJoin(mapNavigablePath, parentTableGroup, null, SqlAstJoinType.INNER, false, false, sqlAliasBaseManager, getSqlExpressionResolver(), this, creationContext);
        parentTableGroup.addTableGroupJoin(tableGroupJoin);
        return tableGroupJoin.getJoinedGroup();
    });
    final PluralAttributeMapping mapDescriptor = (PluralAttributeMapping) tableGroup.getModelPart();
    final CollectionPart indexDescriptor = mapDescriptor.getIndexDescriptor();
    final NavigablePath indexNavigablePath = mapNavigablePath.append(indexDescriptor.getPartName());
    final DomainResult<Object> indexResult = indexDescriptor.createDomainResult(indexNavigablePath, tableGroup, null, this);
    final CollectionPart valueDescriptor = mapDescriptor.getElementDescriptor();
    final NavigablePath valueNavigablePath = mapNavigablePath.append(valueDescriptor.getPartName());
    final DomainResult<Object> valueResult = valueDescriptor.createDomainResult(valueNavigablePath, tableGroup, null, this);
    return new DomainResultProducer<Map.Entry<Object, Object>>() {

        @Override
        public DomainResult<Map.Entry<Object, Object>> createDomainResult(String resultVariable, DomainResultCreationState creationState) {
            final JavaType<Map.Entry<Object, Object>> mapEntryDescriptor = getTypeConfiguration().getJavaTypeRegistry().resolveDescriptor(Map.Entry.class);
            return new SqmMapEntryResult<>(indexResult, valueResult, resultVariable, mapEntryDescriptor);
        }

        @Override
        public void applySqlSelections(DomainResultCreationState creationState) {
            throw new UnsupportedOperationException();
        }
    };
}
Also used : NavigablePath(org.hibernate.query.spi.NavigablePath) VirtualTableGroup(org.hibernate.sql.ast.tree.from.VirtualTableGroup) LazyTableGroup(org.hibernate.sql.ast.tree.from.LazyTableGroup) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) CorrelatedTableGroup(org.hibernate.sql.ast.tree.from.CorrelatedTableGroup) CorrelatedPluralTableGroup(org.hibernate.sql.ast.tree.from.CorrelatedPluralTableGroup) PluralTableGroup(org.hibernate.sql.ast.tree.from.PluralTableGroup) QueryPartTableGroup(org.hibernate.sql.ast.tree.from.QueryPartTableGroup) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) TableGroupJoin(org.hibernate.sql.ast.tree.from.TableGroupJoin) DomainResultCreationState(org.hibernate.sql.results.graph.DomainResultCreationState) DomainResultProducer(org.hibernate.query.sqm.sql.internal.DomainResultProducer) SqmMapEntryResult(org.hibernate.query.sqm.sql.internal.SqmMapEntryResult) EntityCollectionPart(org.hibernate.metamodel.mapping.internal.EntityCollectionPart) CollectionPart(org.hibernate.metamodel.mapping.CollectionPart) EmbeddedCollectionPart(org.hibernate.metamodel.mapping.internal.EmbeddedCollectionPart) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) AbstractMap(java.util.AbstractMap) IdentityHashMap(java.util.IdentityHashMap) HashMap(java.util.HashMap)

Example 20 with PluralAttributeMapping

use of org.hibernate.metamodel.mapping.PluralAttributeMapping in project hibernate-orm by hibernate.

the class BaseSqmToSqlAstConverter method visitMemberOfPredicate.

@Override
public Predicate visitMemberOfPredicate(SqmMemberOfPredicate predicate) {
    final SqmPath<?> pluralPath = predicate.getPluralPath();
    prepareReusablePath(pluralPath, () -> null);
    final PluralAttributeMapping pluralAttributeMapping = (PluralAttributeMapping) determineValueMapping(pluralPath);
    if (pluralAttributeMapping.getElementDescriptor() instanceof EntityCollectionPart) {
        inferrableTypeAccessStack.push(() -> ((EntityCollectionPart) pluralAttributeMapping.getElementDescriptor()).getKeyTargetMatchPart());
    } else if (pluralAttributeMapping.getElementDescriptor() instanceof EmbeddedCollectionPart) {
        inferrableTypeAccessStack.push(pluralAttributeMapping::getElementDescriptor);
    } else {
        inferrableTypeAccessStack.push(() -> pluralAttributeMapping);
    }
    final Expression lhs;
    try {
        lhs = (Expression) predicate.getLeftHandExpression().accept(this);
    } finally {
        inferrableTypeAccessStack.pop();
    }
    final FromClauseAccess parentFromClauseAccess = getFromClauseAccess();
    final QuerySpec subQuerySpec = new QuerySpec(false);
    pushProcessingState(new SqlAstQueryPartProcessingStateImpl(subQuerySpec, getCurrentProcessingState(), this, currentClauseStack::getCurrent, false));
    try {
        final TableGroup tableGroup = pluralAttributeMapping.createRootTableGroup(true, pluralPath.getNavigablePath(), null, () -> subQuerySpec::applyPredicate, this, creationContext);
        pluralAttributeMapping.applyBaseRestrictions(subQuerySpec::applyPredicate, tableGroup, true, getLoadQueryInfluencers().getEnabledFilters(), null, this);
        getFromClauseAccess().registerTableGroup(pluralPath.getNavigablePath(), tableGroup);
        registerPluralTableGroupParts(tableGroup);
        subQuerySpec.getFromClause().addRoot(tableGroup);
        final CollectionPart elementDescriptor = pluralAttributeMapping.getElementDescriptor();
        if (elementDescriptor instanceof EntityCollectionPart) {
            ((EntityCollectionPart) elementDescriptor).getKeyTargetMatchPart().createDomainResult(pluralPath.getNavigablePath(), tableGroup, null, this);
        } else {
            elementDescriptor.createDomainResult(pluralPath.getNavigablePath(), tableGroup, null, this);
        }
        subQuerySpec.applyPredicate(pluralAttributeMapping.getKeyDescriptor().generateJoinPredicate(parentFromClauseAccess.findTableGroup(pluralPath.getNavigablePath().getParent()), tableGroup, getSqlExpressionResolver(), creationContext));
    } finally {
        popProcessingStateStack();
    }
    return new InSubQueryPredicate(lhs, subQuerySpec, predicate.isNegated(), getBooleanType());
}
Also used : SqlAstQueryPartProcessingStateImpl(org.hibernate.query.sqm.sql.internal.SqlAstQueryPartProcessingStateImpl) EntityCollectionPart(org.hibernate.metamodel.mapping.internal.EntityCollectionPart) VirtualTableGroup(org.hibernate.sql.ast.tree.from.VirtualTableGroup) LazyTableGroup(org.hibernate.sql.ast.tree.from.LazyTableGroup) TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) CorrelatedTableGroup(org.hibernate.sql.ast.tree.from.CorrelatedTableGroup) CorrelatedPluralTableGroup(org.hibernate.sql.ast.tree.from.CorrelatedPluralTableGroup) PluralTableGroup(org.hibernate.sql.ast.tree.from.PluralTableGroup) QueryPartTableGroup(org.hibernate.sql.ast.tree.from.QueryPartTableGroup) EmbeddedCollectionPart(org.hibernate.metamodel.mapping.internal.EmbeddedCollectionPart) FromClauseAccess(org.hibernate.sql.ast.spi.FromClauseAccess) BinaryArithmeticExpression(org.hibernate.sql.ast.tree.expression.BinaryArithmeticExpression) SqmModifiedSubQueryExpression(org.hibernate.query.sqm.tree.expression.SqmModifiedSubQueryExpression) SelfRenderingFunctionSqlAstExpression(org.hibernate.query.sqm.function.SelfRenderingFunctionSqlAstExpression) SelfRenderingAggregateFunctionSqlAstExpression(org.hibernate.query.sqm.function.SelfRenderingAggregateFunctionSqlAstExpression) CaseSearchedExpression(org.hibernate.sql.ast.tree.expression.CaseSearchedExpression) SelfRenderingSqlFragmentExpression(org.hibernate.sql.ast.tree.expression.SelfRenderingSqlFragmentExpression) Expression(org.hibernate.sql.ast.tree.expression.Expression) SelfRenderingExpression(org.hibernate.sql.ast.tree.expression.SelfRenderingExpression) SqmExpression(org.hibernate.query.sqm.tree.expression.SqmExpression) CaseSimpleExpression(org.hibernate.sql.ast.tree.expression.CaseSimpleExpression) SqlSelectionExpression(org.hibernate.sql.ast.tree.expression.SqlSelectionExpression) ModifiedSubQueryExpression(org.hibernate.sql.ast.tree.expression.ModifiedSubQueryExpression) InSubQueryPredicate(org.hibernate.sql.ast.tree.predicate.InSubQueryPredicate) SqmInSubQueryPredicate(org.hibernate.query.sqm.tree.predicate.SqmInSubQueryPredicate) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) SqmQuerySpec(org.hibernate.query.sqm.tree.select.SqmQuerySpec) QuerySpec(org.hibernate.sql.ast.tree.select.QuerySpec) EntityCollectionPart(org.hibernate.metamodel.mapping.internal.EntityCollectionPart) CollectionPart(org.hibernate.metamodel.mapping.CollectionPart) EmbeddedCollectionPart(org.hibernate.metamodel.mapping.internal.EmbeddedCollectionPart)

Aggregations

PluralAttributeMapping (org.hibernate.metamodel.mapping.PluralAttributeMapping)40 TableGroup (org.hibernate.sql.ast.tree.from.TableGroup)23 NavigablePath (org.hibernate.query.spi.NavigablePath)16 PluralTableGroup (org.hibernate.sql.ast.tree.from.PluralTableGroup)15 ArrayList (java.util.ArrayList)12 QuerySpec (org.hibernate.sql.ast.tree.select.QuerySpec)12 TableGroupJoin (org.hibernate.sql.ast.tree.from.TableGroupJoin)11 CollectionPart (org.hibernate.metamodel.mapping.CollectionPart)9 ModelPart (org.hibernate.metamodel.mapping.ModelPart)9 CorrelatedPluralTableGroup (org.hibernate.sql.ast.tree.from.CorrelatedPluralTableGroup)9 CorrelatedTableGroup (org.hibernate.sql.ast.tree.from.CorrelatedTableGroup)9 LazyTableGroup (org.hibernate.sql.ast.tree.from.LazyTableGroup)9 QueryPartTableGroup (org.hibernate.sql.ast.tree.from.QueryPartTableGroup)9 VirtualTableGroup (org.hibernate.sql.ast.tree.from.VirtualTableGroup)9 SelectStatement (org.hibernate.sql.ast.tree.select.SelectStatement)9 FetchTiming (org.hibernate.engine.FetchTiming)7 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)7 SqlAstQueryPartProcessingStateImpl (org.hibernate.query.sqm.sql.internal.SqlAstQueryPartProcessingStateImpl)7 SqlSelectionImpl (org.hibernate.sql.results.internal.SqlSelectionImpl)7 Map (java.util.Map)6