Search in sources :

Example 11 with MappingMetamodel

use of org.hibernate.metamodel.MappingMetamodel in project hibernate-orm by hibernate.

the class JpaMetamodelImpl method processJpa.

public void processJpa(MetadataImplementor bootMetamodel, MappingMetamodel mappingMetamodel, Map<Class<?>, String> entityProxyInterfaceMap, JpaStaticMetaModelPopulationSetting jpaStaticMetaModelPopulationSetting, JpaMetaModelPopulationSetting jpaMetaModelPopulationSetting, Collection<NamedEntityGraphDefinition> namedEntityGraphDefinitions, RuntimeModelCreationContext runtimeModelCreationContext) {
    bootMetamodel.getImports().forEach((k, v) -> this.nameToImportMap.put(k, new ImportInfo<>(v, null)));
    this.entityProxyInterfaceMap.putAll(entityProxyInterfaceMap);
    final MetadataContext context = new MetadataContext(this, mappingMetamodel, bootMetamodel, jpaStaticMetaModelPopulationSetting, jpaMetaModelPopulationSetting, runtimeModelCreationContext);
    for (PersistentClass entityBinding : bootMetamodel.getEntityBindings()) {
        locateOrBuildEntityType(entityBinding, context, typeConfiguration);
    }
    handleUnusedMappedSuperclasses(context, typeConfiguration);
    context.wrapUp();
    for (Map.Entry<String, IdentifiableDomainType<?>> entry : context.getIdentifiableTypesByName().entrySet()) {
        if (entry.getValue() instanceof EntityDomainType<?>) {
            this.jpaEntityTypeMap.put(entry.getKey(), (EntityDomainType<?>) entry.getValue());
        }
    }
    this.jpaManagedTypeMap.putAll(context.getEntityTypeMap());
    this.jpaManagedTypeMap.putAll(context.getMappedSuperclassTypeMap());
    switch(jpaMetaModelPopulationSetting) {
        case IGNORE_UNSUPPORTED:
            this.jpaManagedTypes.addAll(context.getEntityTypeMap().values());
            this.jpaManagedTypes.addAll(context.getMappedSuperclassTypeMap().values());
            break;
        case ENABLED:
            this.jpaManagedTypes.addAll(context.getIdentifiableTypesByName().values());
            break;
    }
    for (EmbeddableDomainType<?> embeddable : context.getEmbeddableTypeSet()) {
        switch(jpaMetaModelPopulationSetting) {
            case IGNORE_UNSUPPORTED:
                if (embeddable.getJavaType() != null && embeddable.getJavaType() != Map.class) {
                    this.jpaEmbeddables.add(embeddable);
                    this.jpaManagedTypes.add(embeddable);
                    if (!(embeddable.getExpressibleJavaType() instanceof EntityJavaType<?>)) {
                        this.jpaManagedTypeMap.put(embeddable.getJavaType(), embeddable);
                    }
                }
                break;
            case ENABLED:
                this.jpaEmbeddables.add(embeddable);
                this.jpaManagedTypes.add(embeddable);
                if (embeddable.getJavaType() != null && !(embeddable.getExpressibleJavaType() instanceof EntityJavaType<?>)) {
                    this.jpaManagedTypeMap.put(embeddable.getJavaType(), embeddable);
                }
                break;
            case DISABLED:
                if (embeddable.getJavaType() == null) {
                    throw new UnsupportedOperationException("ANY not supported");
                }
                if (!(embeddable.getExpressibleJavaType() instanceof EntityJavaType<?>)) {
                    this.jpaManagedTypeMap.put(embeddable.getJavaType(), embeddable);
                }
                break;
        }
    }
    final Consumer<PersistentAttribute<?, ?>> attributeConsumer = persistentAttribute -> {
        if (persistentAttribute.getJavaType() != null && persistentAttribute.getJavaType().isEnum()) {
            @SuppressWarnings("unchecked") final Class<Enum<?>> enumClass = (Class<Enum<?>>) persistentAttribute.getJavaType();
            final Enum<?>[] enumConstants = enumClass.getEnumConstants();
            for (Enum<?> enumConstant : enumConstants) {
                final String qualifiedEnumLiteral = enumConstant.getDeclaringClass().getSimpleName() + "." + enumConstant.name();
                this.allowedEnumLiteralTexts.computeIfAbsent(enumConstant.name(), k -> new HashMap<>()).put(enumClass, enumConstant);
                this.allowedEnumLiteralTexts.computeIfAbsent(qualifiedEnumLiteral, k -> new HashMap<>()).put(enumClass, enumConstant);
            }
        }
    };
    domainTypeStream(context).forEach(managedDomainType -> managedDomainType.visitAttributes(attributeConsumer));
    applyNamedEntityGraphs(namedEntityGraphDefinitions);
}
Also used : JpaStaticMetaModelPopulationSetting(org.hibernate.metamodel.internal.JpaStaticMetaModelPopulationSetting) EntityType(jakarta.persistence.metamodel.EntityType) Attribute(jakarta.persistence.metamodel.Attribute) ManagedDomainType(org.hibernate.metamodel.model.domain.ManagedDomainType) IdentifiableDomainType(org.hibernate.metamodel.model.domain.IdentifiableDomainType) JpaMetamodel(org.hibernate.metamodel.model.domain.JpaMetamodel) PersistentClass(org.hibernate.mapping.PersistentClass) Map(java.util.Map) SqmPolymorphicRootDescriptor(org.hibernate.query.sqm.tree.domain.SqmPolymorphicRootDescriptor) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) HEMLogging(org.hibernate.internal.HEMLogging) DynamicModelJavaType(org.hibernate.type.descriptor.java.spi.DynamicModelJavaType) TypeConfiguration(org.hibernate.type.spi.TypeConfiguration) Collection(java.util.Collection) ClassLoaderService(org.hibernate.boot.registry.classloading.spi.ClassLoaderService) JpaMetaModelPopulationSetting(org.hibernate.metamodel.internal.JpaMetaModelPopulationSetting) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) NamedAttributeNode(jakarta.persistence.NamedAttributeNode) StringHelper(org.hibernate.internal.util.StringHelper) Set(java.util.Set) MetadataContext(org.hibernate.metamodel.internal.MetadataContext) EntityGraph(jakarta.persistence.EntityGraph) EntityManagerMessageLogger(org.hibernate.internal.EntityManagerMessageLogger) Serializable(java.io.Serializable) MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) List(java.util.List) AttributeNodeImplementor(org.hibernate.graph.spi.AttributeNodeImplementor) Stream(java.util.stream.Stream) RuntimeModelCreationContext(org.hibernate.metamodel.spi.RuntimeModelCreationContext) JpaMetamodelImplementor(org.hibernate.metamodel.model.domain.spi.JpaMetamodelImplementor) EmbeddableType(jakarta.persistence.metamodel.EmbeddableType) NamedEntityGraphDefinition(org.hibernate.cfg.annotations.NamedEntityGraphDefinition) Queryable(org.hibernate.persister.entity.Queryable) RootGraphImpl(org.hibernate.graph.internal.RootGraphImpl) JavaType(org.hibernate.type.descriptor.java.JavaType) HashMap(java.util.HashMap) NamedSubgraph(jakarta.persistence.NamedSubgraph) MappedSuperclassDomainType(org.hibernate.metamodel.model.domain.MappedSuperclassDomainType) ArrayList(java.util.ArrayList) RootGraphImplementor(org.hibernate.graph.spi.RootGraphImplementor) HashSet(java.util.HashSet) NamedEntityGraph(jakarta.persistence.NamedEntityGraph) EntityDomainType(org.hibernate.metamodel.model.domain.EntityDomainType) PersistentAttribute(org.hibernate.metamodel.model.domain.PersistentAttribute) MetadataImplementor(org.hibernate.boot.spi.MetadataImplementor) MappedSuperclass(org.hibernate.mapping.MappedSuperclass) SubGraphImplementor(org.hibernate.graph.spi.SubGraphImplementor) ManagedType(jakarta.persistence.metamodel.ManagedType) EmbeddableDomainType(org.hibernate.metamodel.model.domain.EmbeddableDomainType) Consumer(java.util.function.Consumer) ObjectStreamException(java.io.ObjectStreamException) GraphImplementor(org.hibernate.graph.spi.GraphImplementor) TreeMap(java.util.TreeMap) JpaCompliance(org.hibernate.jpa.spi.JpaCompliance) ClassLoadingException(org.hibernate.boot.registry.classloading.spi.ClassLoadingException) EntityJavaType(org.hibernate.type.descriptor.java.spi.EntityJavaType) EntityJavaType(org.hibernate.type.descriptor.java.spi.EntityJavaType) IdentifiableDomainType(org.hibernate.metamodel.model.domain.IdentifiableDomainType) PersistentAttribute(org.hibernate.metamodel.model.domain.PersistentAttribute) PersistentClass(org.hibernate.mapping.PersistentClass) MetadataContext(org.hibernate.metamodel.internal.MetadataContext) EntityDomainType(org.hibernate.metamodel.model.domain.EntityDomainType) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) PersistentClass(org.hibernate.mapping.PersistentClass)

Example 12 with MappingMetamodel

use of org.hibernate.metamodel.MappingMetamodel in project hibernate-orm by hibernate.

the class EmbeddableValuedPathInterpretation method from.

/**
 * Static factory
 */
public static <T> EmbeddableValuedPathInterpretation<T> from(SqmEmbeddedValuedSimplePath<T> sqmPath, SqmToSqlAstConverter converter, SemanticQueryWalker sqmWalker, boolean jpaQueryComplianceEnabled) {
    TableGroup tableGroup = converter.getFromClauseAccess().findTableGroup(sqmPath.getLhs().getNavigablePath());
    EntityMappingType treatTarget = null;
    if (jpaQueryComplianceEnabled) {
        final MappingMetamodel mappingMetamodel = converter.getCreationContext().getSessionFactory().getRuntimeMetamodels().getMappingMetamodel();
        if (sqmPath.getLhs() instanceof SqmTreatedPath) {
            // noinspection rawtypes
            final EntityDomainType<?> treatTargetDomainType = ((SqmTreatedPath) sqmPath.getLhs()).getTreatTarget();
            treatTarget = mappingMetamodel.findEntityDescriptor(treatTargetDomainType.getHibernateEntityName());
        } else if (sqmPath.getLhs().getNodeType() instanceof EntityDomainType) {
            // noinspection rawtypes
            final EntityDomainType<?> entityDomainType = (EntityDomainType) sqmPath.getLhs().getNodeType();
            treatTarget = mappingMetamodel.findEntityDescriptor(entityDomainType.getHibernateEntityName());
        }
    }
    final EmbeddableValuedModelPart mapping = (EmbeddableValuedModelPart) tableGroup.getModelPart().findSubPart(sqmPath.getReferencedPathSource().getPathName(), treatTarget);
    return new EmbeddableValuedPathInterpretation<>(mapping.toSqlExpression(tableGroup, converter.getCurrentClauseStack().getCurrent(), converter, converter), sqmPath.getNavigablePath(), mapping, tableGroup);
}
Also used : TableGroup(org.hibernate.sql.ast.tree.from.TableGroup) MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) EmbeddableValuedModelPart(org.hibernate.metamodel.mapping.EmbeddableValuedModelPart) SqmTreatedPath(org.hibernate.query.sqm.tree.domain.SqmTreatedPath) EntityDomainType(org.hibernate.metamodel.model.domain.EntityDomainType) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType)

Example 13 with MappingMetamodel

use of org.hibernate.metamodel.MappingMetamodel in project hibernate-orm by hibernate.

the class AbstractEntityWithManyToManyTest method prepareTest.

@BeforeEach
protected void prepareTest(SessionFactoryScope scope) throws Exception {
    SessionFactoryImplementor sessionFactory = scope.getSessionFactory();
    MappingMetamodel domainModel = sessionFactory.getRuntimeMetamodels().getMappingMetamodel();
    isPlanContractsInverse = domainModel.getCollectionDescriptor(Plan.class.getName() + ".contracts").isInverse();
    try {
        domainModel.getCollectionDescriptor(Contract.class.getName() + ".plans");
        isPlanContractsBidirectional = true;
    } catch (IllegalArgumentException ex) {
        isPlanContractsBidirectional = false;
    }
    isPlanVersioned = sessionFactory.getMappingMetamodel().getEntityDescriptor(Plan.class.getName()).isVersioned();
    isContractVersioned = sessionFactory.getMappingMetamodel().getEntityDescriptor(Contract.class.getName()).isVersioned();
    sessionFactory.getStatistics().clear();
}
Also used : MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 14 with MappingMetamodel

use of org.hibernate.metamodel.MappingMetamodel in project hibernate-orm by hibernate.

the class MappingModelCreationHelper method buildPluralAttributeMapping.

@SuppressWarnings("rawtypes")
public static PluralAttributeMapping buildPluralAttributeMapping(String attrName, int stateArrayPosition, Property bootProperty, ManagedMappingType declaringType, PropertyAccess propertyAccess, CascadeStyle cascadeStyle, FetchMode fetchMode, MappingModelCreationProcess creationProcess) {
    final Collection bootValueMapping = (Collection) bootProperty.getValue();
    final RuntimeModelCreationContext creationContext = creationProcess.getCreationContext();
    final SessionFactoryImplementor sessionFactory = creationContext.getSessionFactory();
    final SqlStringGenerationContext sqlStringGenerationContext = sessionFactory.getSqlStringGenerationContext();
    final Dialect dialect = sqlStringGenerationContext.getDialect();
    final MappingMetamodel domainModel = creationContext.getDomainModel();
    final CollectionPersister collectionDescriptor = domainModel.findCollectionDescriptor(bootValueMapping.getRole());
    assert collectionDescriptor != null;
    final String tableExpression = ((Joinable) collectionDescriptor).getTableName();
    final String sqlAliasStem = SqlAliasStemHelper.INSTANCE.generateStemFromAttributeName(bootProperty.getName());
    final CollectionMappingType<?> collectionMappingType;
    final JavaTypeRegistry jtdRegistry = creationContext.getJavaTypeRegistry();
    final CollectionPart elementDescriptor = interpretElement(bootValueMapping, tableExpression, collectionDescriptor, sqlAliasStem, dialect, creationProcess);
    final CollectionPart indexDescriptor;
    CollectionIdentifierDescriptor identifierDescriptor = null;
    final CollectionSemantics<?, ?> collectionSemantics = collectionDescriptor.getCollectionSemantics();
    switch(collectionSemantics.getCollectionClassification()) {
        case ARRAY:
            {
                collectionMappingType = new CollectionMappingTypeImpl(jtdRegistry.getDescriptor(Object[].class), StandardArraySemantics.INSTANCE);
                final BasicValue index = (BasicValue) ((IndexedCollection) bootValueMapping).getIndex();
                final SelectableMapping selectableMapping = SelectableMappingImpl.from(tableExpression, index.getSelectables().get(0), creationContext.getTypeConfiguration().getBasicTypeForJavaType(Integer.class), dialect, creationProcess.getSqmFunctionRegistry());
                indexDescriptor = new BasicValuedCollectionPart(collectionDescriptor, CollectionPart.Nature.INDEX, // no converter
                null, selectableMapping);
                break;
            }
        case BAG:
            {
                collectionMappingType = new CollectionMappingTypeImpl(jtdRegistry.getDescriptor(java.util.Collection.class), StandardBagSemantics.INSTANCE);
                indexDescriptor = null;
                break;
            }
        case ID_BAG:
            {
                collectionMappingType = new CollectionMappingTypeImpl(jtdRegistry.getDescriptor(java.util.Collection.class), StandardIdentifierBagSemantics.INSTANCE);
                indexDescriptor = null;
                assert collectionDescriptor instanceof SQLLoadableCollection;
                final SQLLoadableCollection loadableCollection = (SQLLoadableCollection) collectionDescriptor;
                final String identifierColumnName = loadableCollection.getIdentifierColumnName();
                assert identifierColumnName != null;
                identifierDescriptor = new CollectionIdentifierDescriptorImpl(collectionDescriptor, tableExpression, identifierColumnName, (BasicType) loadableCollection.getIdentifierType());
                break;
            }
        case LIST:
            {
                final BasicValue index = (BasicValue) ((IndexedCollection) bootValueMapping).getIndex();
                final SelectableMapping selectableMapping = SelectableMappingImpl.from(tableExpression, index.getSelectables().get(0), creationContext.getTypeConfiguration().getBasicTypeForJavaType(Integer.class), dialect, creationProcess.getSqmFunctionRegistry());
                indexDescriptor = new BasicValuedCollectionPart(collectionDescriptor, CollectionPart.Nature.INDEX, // no converter
                null, selectableMapping);
                collectionMappingType = new CollectionMappingTypeImpl(jtdRegistry.getDescriptor(List.class), StandardListSemantics.INSTANCE);
                break;
            }
        case MAP:
        case ORDERED_MAP:
        case SORTED_MAP:
            {
                final Class<? extends java.util.Map> mapJavaType = collectionSemantics.getCollectionClassification() == CollectionClassification.SORTED_MAP ? SortedMap.class : java.util.Map.class;
                collectionMappingType = new CollectionMappingTypeImpl(jtdRegistry.getDescriptor(mapJavaType), collectionSemantics);
                final String mapKeyTableExpression;
                if (bootValueMapping instanceof Map && ((Map) bootValueMapping).getMapKeyPropertyName() != null) {
                    mapKeyTableExpression = getTableIdentifierExpression(((Map) bootValueMapping).getIndex().getTable(), creationProcess);
                } else {
                    mapKeyTableExpression = tableExpression;
                }
                indexDescriptor = interpretMapKey(bootValueMapping, collectionDescriptor, mapKeyTableExpression, sqlAliasStem, dialect, creationProcess);
                break;
            }
        case SET:
        case ORDERED_SET:
        case SORTED_SET:
            {
                final Class<? extends java.util.Set> setJavaType = collectionSemantics.getCollectionClassification() == CollectionClassification.SORTED_MAP ? SortedSet.class : java.util.Set.class;
                collectionMappingType = new CollectionMappingTypeImpl(jtdRegistry.getDescriptor(setJavaType), collectionSemantics);
                indexDescriptor = null;
                break;
            }
        default:
            {
                throw new MappingException("Unexpected CollectionClassification : " + collectionSemantics.getCollectionClassification());
            }
    }
    final StateArrayContributorMetadata contributorMetadata = new StateArrayContributorMetadata() {

        @Override
        public PropertyAccess getPropertyAccess() {
            return propertyAccess;
        }

        @Override
        public MutabilityPlan getMutabilityPlan() {
            return ImmutableMutabilityPlan.instance();
        }

        @Override
        public boolean isNullable() {
            return bootProperty.isOptional();
        }

        @Override
        public boolean isInsertable() {
            return bootProperty.isInsertable();
        }

        @Override
        public boolean isUpdatable() {
            return bootProperty.isUpdateable();
        }

        @Override
        public boolean isIncludedInDirtyChecking() {
            return false;
        }

        @Override
        public boolean isIncludedInOptimisticLocking() {
            return bootProperty.isOptimisticLocked();
        }

        @Override
        public CascadeStyle getCascadeStyle() {
            return cascadeStyle;
        }
    };
    final FetchStyle style = FetchOptionsHelper.determineFetchStyleByMetadata(fetchMode, collectionDescriptor.getCollectionType(), sessionFactory);
    final FetchTiming timing = FetchOptionsHelper.determineFetchTiming(style, collectionDescriptor.getCollectionType(), collectionDescriptor.isLazy(), collectionDescriptor.getRole(), sessionFactory);
    final PluralAttributeMappingImpl pluralAttributeMapping = new PluralAttributeMappingImpl(attrName, bootValueMapping, propertyAccess, entityMappingType -> contributorMetadata, collectionMappingType, stateArrayPosition, elementDescriptor, indexDescriptor, identifierDescriptor, timing, style, cascadeStyle, declaringType, collectionDescriptor);
    creationProcess.registerInitializationCallback("PluralAttributeMapping(" + bootValueMapping.getRole() + ")#finishInitialization", () -> {
        pluralAttributeMapping.finishInitialization(bootProperty, bootValueMapping, creationProcess);
        return true;
    });
    creationProcess.registerInitializationCallback("PluralAttributeMapping(" + bootValueMapping.getRole() + ") - key descriptor", () -> {
        interpretPluralAttributeMappingKeyDescriptor(pluralAttributeMapping, bootValueMapping, collectionDescriptor, declaringType, dialect, creationProcess);
        return true;
    });
    return pluralAttributeMapping;
}
Also used : SelectableMapping(org.hibernate.metamodel.mapping.SelectableMapping) SortedSet(java.util.SortedSet) SortedSet(java.util.SortedSet) BasicValue(org.hibernate.mapping.BasicValue) MappingException(org.hibernate.MappingException) JavaTypeRegistry(org.hibernate.type.descriptor.java.spi.JavaTypeRegistry) FetchStyle(org.hibernate.engine.FetchStyle) Dialect(org.hibernate.dialect.Dialect) List(java.util.List) CollectionPart(org.hibernate.metamodel.mapping.CollectionPart) SqlStringGenerationContext(org.hibernate.boot.model.relational.SqlStringGenerationContext) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) CollectionIdentifierDescriptor(org.hibernate.metamodel.mapping.CollectionIdentifierDescriptor) StateArrayContributorMetadata(org.hibernate.metamodel.mapping.StateArrayContributorMetadata) MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) SQLLoadableCollection(org.hibernate.persister.collection.SQLLoadableCollection) RuntimeModelCreationContext(org.hibernate.metamodel.spi.RuntimeModelCreationContext) Joinable(org.hibernate.persister.entity.Joinable) SortedMap(java.util.SortedMap) FetchTiming(org.hibernate.engine.FetchTiming) Collection(org.hibernate.mapping.Collection) IndexedCollection(org.hibernate.mapping.IndexedCollection) SQLLoadableCollection(org.hibernate.persister.collection.SQLLoadableCollection) QueryableCollection(org.hibernate.persister.collection.QueryableCollection) PersistentClass(org.hibernate.mapping.PersistentClass) IndexedCollection(org.hibernate.mapping.IndexedCollection) SortedMap(java.util.SortedMap) Map(org.hibernate.mapping.Map)

Example 15 with MappingMetamodel

use of org.hibernate.metamodel.MappingMetamodel in project hibernate-orm by hibernate.

the class BaseSqmToSqlAstConverter method determineValueMapping.

private MappingModelExpressible<?> determineValueMapping(SqmExpression<?> sqmExpression, FromClauseIndex fromClauseIndex) {
    if (sqmExpression instanceof SqmParameter) {
        return determineValueMapping((SqmParameter<?>) sqmExpression);
    } else if (sqmExpression instanceof SqmPath) {
        log.debugf("Determining mapping-model type for SqmPath : %s ", sqmExpression);
        final MappingMetamodel domainModel = creationContext.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel();
        return SqmMappingModelHelper.resolveMappingModelExpressible(sqmExpression, domainModel, fromClauseIndex::findTableGroup);
    } else // The model type of an enum literal is always inferred
    if (sqmExpression instanceof SqmEnumLiteral<?>) {
        final MappingModelExpressible<?> mappingModelExpressible = resolveInferredType();
        if (mappingModelExpressible != null) {
            return mappingModelExpressible;
        }
    } else if (sqmExpression instanceof SqmSubQuery<?>) {
        final SqmSubQuery<?> subQuery = (SqmSubQuery<?>) sqmExpression;
        final SqmSelectClause selectClause = subQuery.getQuerySpec().getSelectClause();
        if (selectClause.getSelections().size() == 1) {
            final SqmSelection<?> subQuerySelection = selectClause.getSelections().get(0);
            final SqmSelectableNode<?> selectableNode = subQuerySelection.getSelectableNode();
            if (selectableNode instanceof SqmExpression<?>) {
                return determineValueMapping((SqmExpression<?>) selectableNode, fromClauseIndex);
            }
            final SqmExpressible<?> selectionNodeType = subQuerySelection.getNodeType();
            if (selectionNodeType != null) {
                final MappingMetamodel domainModel = creationContext.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel();
                final MappingModelExpressible<?> expressible = domainModel.resolveMappingExpressible(selectionNodeType, this::findTableGroupByPath);
                if (expressible != null) {
                    return expressible;
                }
                try {
                    final MappingModelExpressible<?> mappingModelExpressible = resolveInferredType();
                    if (mappingModelExpressible != null) {
                        return mappingModelExpressible;
                    }
                } catch (Exception ignore) {
                    return null;
                }
            }
        }
    }
    log.debugf("Determining mapping-model type for generalized SqmExpression : %s", sqmExpression);
    final SqmExpressible<?> nodeType = sqmExpression.getNodeType();
    if (nodeType == null) {
        // We can't determine the type of the expression
        return null;
    }
    final MappingMetamodel domainModel = creationContext.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel();
    final MappingModelExpressible<?> valueMapping = domainModel.resolveMappingExpressible(nodeType, fromClauseIndex::getTableGroup);
    if (valueMapping == null) {
        final MappingModelExpressible<?> mappingModelExpressible = resolveInferredType();
        if (mappingModelExpressible != null) {
            return mappingModelExpressible;
        }
    }
    if (valueMapping == null) {
        // For literals it is totally possible that we can't figure out a mapping type
        if (sqmExpression instanceof SqmLiteral<?>) {
            return null;
        }
        throw new ConversionException("Could not determine ValueMapping for SqmExpression: " + sqmExpression);
    }
    return valueMapping;
}
Also used : SqmSubQuery(org.hibernate.query.sqm.tree.select.SqmSubQuery) SqmSelectableNode(org.hibernate.query.sqm.tree.select.SqmSelectableNode) MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) SqmSelection(org.hibernate.query.sqm.tree.select.SqmSelection) SqmSelectClause(org.hibernate.query.sqm.tree.select.SqmSelectClause) SelfInterpretingSqmPath(org.hibernate.query.sqm.sql.internal.SelfInterpretingSqmPath) SqmPath(org.hibernate.query.sqm.tree.domain.SqmPath) DiscriminatorSqmPath(org.hibernate.metamodel.model.domain.internal.DiscriminatorSqmPath) SqmEnumLiteral(org.hibernate.query.sqm.tree.expression.SqmEnumLiteral) MultipleBagFetchException(org.hibernate.loader.MultipleBagFetchException) SemanticException(org.hibernate.query.SemanticException) NotYetImplementedFor6Exception(org.hibernate.NotYetImplementedFor6Exception) SqlTreeCreationException(org.hibernate.sql.ast.SqlTreeCreationException) HibernateException(org.hibernate.HibernateException) QueryException(org.hibernate.QueryException) InterpretationException(org.hibernate.query.sqm.InterpretationException) SQLException(java.sql.SQLException) SqmExpressible(org.hibernate.query.sqm.SqmExpressible) MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) SqmExpression(org.hibernate.query.sqm.tree.expression.SqmExpression) SqmParameter(org.hibernate.query.sqm.tree.expression.SqmParameter) SqmLiteral(org.hibernate.query.sqm.tree.expression.SqmLiteral)

Aggregations

MappingMetamodel (org.hibernate.metamodel.MappingMetamodel)25 Test (org.junit.jupiter.api.Test)13 EntityPersister (org.hibernate.persister.entity.EntityPersister)12 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)7 EntityMappingType (org.hibernate.metamodel.mapping.EntityMappingType)7 PluralAttributeMapping (org.hibernate.metamodel.mapping.PluralAttributeMapping)5 TableGroup (org.hibernate.sql.ast.tree.from.TableGroup)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 Map (java.util.Map)4 PersistentClass (org.hibernate.mapping.PersistentClass)4 AttributeMapping (org.hibernate.metamodel.mapping.AttributeMapping)4 EntityDomainType (org.hibernate.metamodel.model.domain.EntityDomainType)4 QueryException (org.hibernate.QueryException)3 EmbeddableMappingType (org.hibernate.metamodel.mapping.EmbeddableMappingType)3 JdbcMapping (org.hibernate.metamodel.mapping.JdbcMapping)3 MappingModelExpressible (org.hibernate.metamodel.mapping.MappingModelExpressible)3 NaturalIdMapping (org.hibernate.metamodel.mapping.NaturalIdMapping)3 DiscriminatorSqmPath (org.hibernate.metamodel.model.domain.internal.DiscriminatorSqmPath)3 Joinable (org.hibernate.persister.entity.Joinable)3