Search in sources :

Example 6 with EmbeddableMappingType

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

the class AbstractEmbeddableInitializer method applyMapsId.

private void applyMapsId(RowProcessingState processingState) {
    final SharedSessionContractImplementor session = processingState.getSession();
    if (embedded instanceof CompositeIdentifierMapping) {
        final CompositeIdentifierMapping cid = (CompositeIdentifierMapping) embedded;
        final EmbeddableMappingType mappedIdEmbeddable = cid.getMappedIdEmbeddableTypeDescriptor();
        if (cid.hasContainingClass()) {
            final EmbeddableMappingType virtualIdEmbeddable = embedded.getEmbeddableTypeDescriptor();
            if (virtualIdEmbeddable == mappedIdEmbeddable) {
                return;
            }
            virtualIdEmbeddable.forEachAttributeMapping((position, virtualIdAttribute) -> {
                final AttributeMapping mappedIdAttribute = mappedIdEmbeddable.getAttributeMapping(position);
                if (virtualIdAttribute instanceof ToOneAttributeMapping && !(mappedIdAttribute instanceof ToOneAttributeMapping)) {
                    final ToOneAttributeMapping toOneAttributeMapping = (ToOneAttributeMapping) virtualIdAttribute;
                    final ForeignKeyDescriptor fkDescriptor = toOneAttributeMapping.getForeignKeyDescriptor();
                    final Object associationKey = fkDescriptor.getAssociationKeyFromSide(rowState[position], toOneAttributeMapping.getSideNature().inverse(), session);
                    rowState[position] = associationKey;
                }
            });
        }
    }
}
Also used : ToOneAttributeMapping(org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) ToOneAttributeMapping(org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) CompositeIdentifierMapping(org.hibernate.metamodel.mapping.CompositeIdentifierMapping) EmbeddableMappingType(org.hibernate.metamodel.mapping.EmbeddableMappingType)

Example 7 with EmbeddableMappingType

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

the class FetchParent method resolveNavigablePath.

default NavigablePath resolveNavigablePath(Fetchable fetchable) {
    final String fetchableName = fetchable.getFetchableName();
    if (NavigablePath.IDENTIFIER_MAPPER_PROPERTY.equals(fetchableName)) {
        return new EntityIdentifierNavigablePath(getNavigablePath(), fetchableName);
    } else {
        final FetchableContainer referencedMappingContainer = getReferencedMappingContainer();
        final EntityMappingType fetchableEntityType = fetchable.findContainingEntityMapping();
        final EntityMappingType fetchParentType;
        if (referencedMappingContainer instanceof EmbeddableMappingType || referencedMappingContainer instanceof EmbeddableValuedModelPart) {
            fetchParentType = referencedMappingContainer.findContainingEntityMapping();
        } else if (referencedMappingContainer instanceof EntityMappingType) {
            fetchParentType = (EntityMappingType) referencedMappingContainer;
        } else {
            fetchParentType = fetchableEntityType;
        }
        if (fetchParentType != fetchableEntityType) {
            // todo (6.0): if the fetchParentType is a subtype of fetchableEntityType this shouldn't be necessary
            return getNavigablePath().treatAs(fetchableEntityType.getEntityName()).append(fetchableName);
        }
        return getNavigablePath().append(fetchableName);
    }
}
Also used : EntityIdentifierNavigablePath(org.hibernate.query.sqm.spi.EntityIdentifierNavigablePath) EmbeddableValuedModelPart(org.hibernate.metamodel.mapping.EmbeddableValuedModelPart) EmbeddableMappingType(org.hibernate.metamodel.mapping.EmbeddableMappingType) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType)

Example 8 with EmbeddableMappingType

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

the class EmbeddedComponentType method isMethodOf.

@Override
public boolean isMethodOf(Method method) {
    if (mappingModelPart() == null) {
        throw new IllegalStateException("EmbeddableValuedModelPart not known yet");
    }
    final EmbeddableMappingType embeddable = mappingModelPart().getEmbeddableTypeDescriptor();
    for (int i = 0; i < embeddable.getAttributeMappings().size(); i++) {
        final AttributeMapping attributeMapping = embeddable.getAttributeMapping(i);
        final Getter getter = attributeMapping.getPropertyAccess().getGetter();
        final Method getterMethod = getter.getMethod();
        if (getterMethod != null && getterMethod.equals(method)) {
            return true;
        }
    }
    return false;
}
Also used : Getter(org.hibernate.property.access.spi.Getter) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) Method(java.lang.reflect.Method) EmbeddableMappingType(org.hibernate.metamodel.mapping.EmbeddableMappingType)

Example 9 with EmbeddableMappingType

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

the class EmbeddableMappingTypeImpl method finishInitialization.

private boolean finishInitialization(Component bootDescriptor, CompositeType compositeType, String rootTableExpression, String[] rootTableKeyColumnNames, MappingModelCreationProcess creationProcess) {
    // for some reason I cannot get this to work, though only a single test fails - `CompositeElementTest`
    // return finishInitialization(
    // getNavigableRole(),
    // bootDescriptor,
    // compositeType,
    // rootTableExpression,
    // rootTableKeyColumnNames,
    // this,
    // representationStrategy,
    // (name, type) -> {},
    // (column, jdbcEnvironment) -> getTableIdentifierExpression(
    // column.getValue().getTable(),
    // jdbcEnvironment
    // ),
    // this::addAttribute,
    // () -> {
    // // We need the attribute mapping types to finish initialization first before we can build the column mappings
    // creationProcess.registerInitializationCallback(
    // "EmbeddableMappingType(" + getEmbeddedValueMapping().getNavigableRole().getFullPath() + ")#initColumnMappings",
    // this::initColumnMappings
    // );
    // },
    // creationProcess
    // );
    // todo (6.0) - get this ^^ to work, or drop the comment
    final SessionFactoryImplementor sessionFactory = creationProcess.getCreationContext().getSessionFactory();
    final TypeConfiguration typeConfiguration = sessionFactory.getTypeConfiguration();
    final JdbcServices jdbcServices = sessionFactory.getJdbcServices();
    final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment();
    final Dialect dialect = jdbcEnvironment.getDialect();
    final String baseTableExpression = valueMapping.getContainingTableExpression();
    final Type[] subtypes = compositeType.getSubtypes();
    int attributeIndex = 0;
    int columnPosition = 0;
    // Reset the attribute mappings that were added in previous attempts
    this.attributeMappings.clear();
    for (Property bootPropertyDescriptor : bootDescriptor.getProperties()) {
        final AttributeMapping attributeMapping;
        final Type subtype = subtypes[attributeIndex];
        if (subtype instanceof BasicType) {
            final BasicValue basicValue = (BasicValue) bootPropertyDescriptor.getValue();
            final Selectable selectable = basicValue.getColumn();
            final String containingTableExpression;
            final String columnExpression;
            if (rootTableKeyColumnNames == null) {
                if (selectable.isFormula()) {
                    columnExpression = selectable.getTemplate(dialect, creationProcess.getSqmFunctionRegistry());
                } else {
                    columnExpression = selectable.getText(dialect);
                }
                if (selectable instanceof Column) {
                    containingTableExpression = MappingModelCreationHelper.getTableIdentifierExpression(((Column) selectable).getValue().getTable(), creationProcess);
                } else {
                    containingTableExpression = baseTableExpression;
                }
            } else {
                containingTableExpression = rootTableExpression;
                columnExpression = rootTableKeyColumnNames[columnPosition];
            }
            final String columnDefinition;
            final Long length;
            final Integer precision;
            final Integer scale;
            if (selectable instanceof Column) {
                Column column = (Column) selectable;
                columnDefinition = column.getSqlType();
                length = column.getLength();
                precision = column.getPrecision();
                scale = column.getScale();
            } else {
                columnDefinition = null;
                length = null;
                precision = null;
                scale = null;
            }
            attributeMapping = MappingModelCreationHelper.buildBasicAttributeMapping(bootPropertyDescriptor.getName(), valueMapping.getNavigableRole().append(bootPropertyDescriptor.getName()), attributeIndex, bootPropertyDescriptor, this, (BasicType<?>) subtype, containingTableExpression, columnExpression, selectable.isFormula(), selectable.getCustomReadExpression(), selectable.getCustomWriteExpression(), columnDefinition, length, precision, scale, representationStrategy.resolvePropertyAccess(bootPropertyDescriptor), compositeType.getCascadeStyle(attributeIndex), creationProcess);
            columnPosition++;
        } else if (subtype instanceof AnyType) {
            final Any bootValueMapping = (Any) bootPropertyDescriptor.getValue();
            final AnyType anyType = (AnyType) subtype;
            final PropertyAccess propertyAccess = representationStrategy.resolvePropertyAccess(bootPropertyDescriptor);
            final boolean nullable = bootValueMapping.isNullable();
            final boolean insertable = bootPropertyDescriptor.isInsertable();
            final boolean updateable = bootPropertyDescriptor.isUpdateable();
            final boolean includeInOptimisticLocking = bootPropertyDescriptor.isOptimisticLocked();
            final CascadeStyle cascadeStyle = compositeType.getCascadeStyle(attributeIndex);
            final MutabilityPlan<?> mutabilityPlan;
            if (updateable) {
                mutabilityPlan = new MutabilityPlan<Object>() {

                    @Override
                    public boolean isMutable() {
                        return true;
                    }

                    @Override
                    public Object deepCopy(Object value) {
                        if (value == null) {
                            return null;
                        }
                        return anyType.deepCopy(value, creationProcess.getCreationContext().getSessionFactory());
                    }

                    @Override
                    public Serializable disassemble(Object value, SharedSessionContract session) {
                        throw new NotYetImplementedFor6Exception(getClass());
                    }

                    @Override
                    public Object assemble(Serializable cached, SharedSessionContract session) {
                        throw new NotYetImplementedFor6Exception(getClass());
                    }
                };
            } else {
                mutabilityPlan = ImmutableMutabilityPlan.INSTANCE;
            }
            final StateArrayContributorMetadataAccess attributeMetadataAccess = entityMappingType -> new StateArrayContributorMetadata() {

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

                @Override
                public MutabilityPlan<?> getMutabilityPlan() {
                    return mutabilityPlan;
                }

                @Override
                public boolean isNullable() {
                    return nullable;
                }

                @Override
                public boolean isInsertable() {
                    return insertable;
                }

                @Override
                public boolean isUpdatable() {
                    return updateable;
                }

                @Override
                public boolean isIncludedInDirtyChecking() {
                    // todo (6.0) : do not believe this is correct
                    return updateable;
                }

                @Override
                public boolean isIncludedInOptimisticLocking() {
                    return includeInOptimisticLocking;
                }

                @Override
                public CascadeStyle getCascadeStyle() {
                    return cascadeStyle;
                }
            };
            attributeMapping = new DiscriminatedAssociationAttributeMapping(valueMapping.getNavigableRole().append(bootPropertyDescriptor.getName()), typeConfiguration.getJavaTypeRegistry().getDescriptor(Object.class), this, attributeIndex, attributeMetadataAccess, bootPropertyDescriptor.isLazy() ? FetchTiming.DELAYED : FetchTiming.IMMEDIATE, propertyAccess, bootPropertyDescriptor, anyType, bootValueMapping, creationProcess);
        } else if (subtype instanceof CompositeType) {
            final CompositeType subCompositeType = (CompositeType) subtype;
            final int columnSpan = subCompositeType.getColumnSpan(sessionFactory);
            final String subTableExpression;
            final String[] subRootTableKeyColumnNames;
            if (rootTableKeyColumnNames == null) {
                subTableExpression = baseTableExpression;
                subRootTableKeyColumnNames = null;
            } else {
                subTableExpression = rootTableExpression;
                subRootTableKeyColumnNames = new String[columnSpan];
                System.arraycopy(rootTableKeyColumnNames, columnPosition, subRootTableKeyColumnNames, 0, columnSpan);
            }
            attributeMapping = MappingModelCreationHelper.buildEmbeddedAttributeMapping(bootPropertyDescriptor.getName(), attributeIndex, bootPropertyDescriptor, this, subCompositeType, subTableExpression, subRootTableKeyColumnNames, representationStrategy.resolvePropertyAccess(bootPropertyDescriptor), compositeType.getCascadeStyle(attributeIndex), creationProcess);
            columnPosition += columnSpan;
        } else if (subtype instanceof CollectionType) {
            final EntityPersister entityPersister = creationProcess.getEntityPersister(bootDescriptor.getOwner().getEntityName());
            attributeMapping = MappingModelCreationHelper.buildPluralAttributeMapping(bootPropertyDescriptor.getName(), attributeIndex, bootPropertyDescriptor, entityPersister, representationStrategy.resolvePropertyAccess(bootPropertyDescriptor), compositeType.getCascadeStyle(attributeIndex), compositeType.getFetchMode(attributeIndex), creationProcess);
        } else if (subtype instanceof EntityType) {
            final EntityPersister entityPersister = creationProcess.getEntityPersister(bootDescriptor.getOwner().getEntityName());
            attributeMapping = MappingModelCreationHelper.buildSingularAssociationAttributeMapping(bootPropertyDescriptor.getName(), valueMapping.getNavigableRole().append(bootPropertyDescriptor.getName()), attributeIndex, bootPropertyDescriptor, entityPersister, entityPersister, (EntityType) subtype, getRepresentationStrategy().resolvePropertyAccess(bootPropertyDescriptor), compositeType.getCascadeStyle(attributeIndex), creationProcess);
            columnPosition += bootPropertyDescriptor.getColumnSpan();
        } else {
            throw new MappingException(String.format(Locale.ROOT, "Unable to determine attribute nature : %s#%s", bootDescriptor.getOwner().getEntityName(), bootPropertyDescriptor.getName()));
        }
        addAttribute(attributeMapping);
        attributeIndex++;
    }
    // We need the attribute mapping types to finish initialization first before we can build the column mappings
    creationProcess.registerInitializationCallback("EmbeddableMappingType(" + getEmbeddedValueMapping().getNavigableRole().getFullPath() + ")#initColumnMappings", this::initColumnMappings);
    return true;
}
Also used : CascadeStyle(org.hibernate.engine.spi.CascadeStyle) EntityPersister(org.hibernate.persister.entity.EntityPersister) Serializable(java.io.Serializable) BasicType(org.hibernate.type.BasicType) SharedSessionContract(org.hibernate.SharedSessionContract) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) JdbcEnvironment(org.hibernate.engine.jdbc.env.spi.JdbcEnvironment) Any(org.hibernate.mapping.Any) BasicValue(org.hibernate.mapping.BasicValue) UnsupportedMappingException(org.hibernate.metamodel.UnsupportedMappingException) MappingException(org.hibernate.MappingException) Selectable(org.hibernate.mapping.Selectable) Column(org.hibernate.mapping.Column) CollectionType(org.hibernate.type.CollectionType) Dialect(org.hibernate.dialect.Dialect) ImmutableMutabilityPlan(org.hibernate.type.descriptor.java.ImmutableMutabilityPlan) MutabilityPlan(org.hibernate.type.descriptor.java.MutabilityPlan) Property(org.hibernate.mapping.Property) AnyType(org.hibernate.type.AnyType) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) StateArrayContributorMetadata(org.hibernate.metamodel.mapping.StateArrayContributorMetadata) PropertyAccess(org.hibernate.property.access.spi.PropertyAccess) EntityType(org.hibernate.type.EntityType) BasicType(org.hibernate.type.BasicType) AnyType(org.hibernate.type.AnyType) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) JavaType(org.hibernate.type.descriptor.java.JavaType) CollectionType(org.hibernate.type.CollectionType) EntityType(org.hibernate.type.EntityType) CompositeType(org.hibernate.type.CompositeType) ManagedMappingType(org.hibernate.metamodel.mapping.ManagedMappingType) EmbeddableMappingType(org.hibernate.metamodel.mapping.EmbeddableMappingType) Type(org.hibernate.type.Type) StateArrayContributorMetadataAccess(org.hibernate.metamodel.mapping.StateArrayContributorMetadataAccess) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) NotYetImplementedFor6Exception(org.hibernate.NotYetImplementedFor6Exception) TypeConfiguration(org.hibernate.type.spi.TypeConfiguration) CompositeType(org.hibernate.type.CompositeType)

Example 10 with EmbeddableMappingType

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

the class BaseSqmToSqlAstConverter method visitTuple.

@Override
public Object visitTuple(SqmTuple<?> sqmTuple) {
    final List<SqmExpression<?>> groupedExpressions = sqmTuple.getGroupedExpressions();
    final int size = groupedExpressions.size();
    final List<Expression> expressions = new ArrayList<>(size);
    final MappingModelExpressible<?> mappingModelExpressible = resolveInferredType();
    final EmbeddableMappingType embeddableMappingType;
    if (mappingModelExpressible instanceof ValueMapping) {
        embeddableMappingType = (EmbeddableMappingType) ((ValueMapping) mappingModelExpressible).getMappedType();
    } else {
        embeddableMappingType = null;
    }
    if (embeddableMappingType == null) {
        try {
            inferrableTypeAccessStack.push(() -> null);
            for (int i = 0; i < size; i++) {
                expressions.add((Expression) groupedExpressions.get(i).accept(this));
            }
        } finally {
            inferrableTypeAccessStack.pop();
        }
    } else {
        for (int i = 0; i < size; i++) {
            final AttributeMapping attributeMapping = embeddableMappingType.getAttributeMappings().get(i);
            inferrableTypeAccessStack.push(() -> attributeMapping);
            try {
                expressions.add((Expression) groupedExpressions.get(i).accept(this));
            } finally {
                inferrableTypeAccessStack.pop();
            }
        }
    }
    final MappingModelExpressible<?> valueMapping;
    if (mappingModelExpressible != null) {
        valueMapping = mappingModelExpressible;
    } else {
        final SqmExpressible<?> expressible = sqmTuple.getExpressible();
        if (expressible instanceof MappingModelExpressible<?>) {
            valueMapping = (MappingModelExpressible<?>) expressible;
        } else {
            valueMapping = null;
        }
    }
    return new SqlTuple(expressions, valueMapping);
}
Also used : MappingModelExpressible(org.hibernate.metamodel.mapping.MappingModelExpressible) ArrayList(java.util.ArrayList) EmbeddableMappingType(org.hibernate.metamodel.mapping.EmbeddableMappingType) ValueMapping(org.hibernate.metamodel.mapping.ValueMapping) SqmExpression(org.hibernate.query.sqm.tree.expression.SqmExpression) 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) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) ToOneAttributeMapping(org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) SqlTuple(org.hibernate.sql.ast.tree.expression.SqlTuple)

Aggregations

EmbeddableMappingType (org.hibernate.metamodel.mapping.EmbeddableMappingType)16 AttributeMapping (org.hibernate.metamodel.mapping.AttributeMapping)6 EntityPersister (org.hibernate.persister.entity.EntityPersister)4 Serializable (java.io.Serializable)3 MappingException (org.hibernate.MappingException)3 NotYetImplementedFor6Exception (org.hibernate.NotYetImplementedFor6Exception)3 SharedSessionContract (org.hibernate.SharedSessionContract)3 Dialect (org.hibernate.dialect.Dialect)3 CascadeStyle (org.hibernate.engine.spi.CascadeStyle)3 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)3 Any (org.hibernate.mapping.Any)3 BasicValue (org.hibernate.mapping.BasicValue)3 Property (org.hibernate.mapping.Property)3 Selectable (org.hibernate.mapping.Selectable)3 RuntimeMetamodels (org.hibernate.metamodel.RuntimeMetamodels)3 EntityMappingType (org.hibernate.metamodel.mapping.EntityMappingType)3 PluralAttributeMapping (org.hibernate.metamodel.mapping.PluralAttributeMapping)3 EmbeddedAttributeMapping (org.hibernate.metamodel.mapping.internal.EmbeddedAttributeMapping)3 Test (org.junit.jupiter.api.Test)3 JdbcEnvironment (org.hibernate.engine.jdbc.env.spi.JdbcEnvironment)2