Search in sources :

Example 31 with AttributeMapping

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

the class NonAggregatedIdentifierMappingImpl method getIdentifier.

@Override
public Object getIdentifier(Object entity) {
    if (hasContainingClass()) {
        final Object id = identifierValueMapper.getRepresentationStrategy().getInstantiator().instantiate(null, sessionFactory);
        final List<AttributeMapping> attributeMappings = getEmbeddableTypeDescriptor().getAttributeMappings();
        final List<AttributeMapping> idClassAttributeMappings = identifierValueMapper.getAttributeMappings();
        final Object[] propertyValues = new Object[attributeMappings.size()];
        for (int i = 0; i < propertyValues.length; i++) {
            final AttributeMapping attributeMapping = attributeMappings.get(i);
            final Object o = attributeMapping.getPropertyAccess().getGetter().get(entity);
            if (o == null) {
                final AttributeMapping idClassAttributeMapping = idClassAttributeMappings.get(i);
                if (idClassAttributeMapping.getPropertyAccess().getGetter().getReturnTypeClass().isPrimitive()) {
                    propertyValues[i] = idClassAttributeMapping.getExpressibleJavaType().getDefaultValue();
                } else {
                    propertyValues[i] = null;
                }
            } else // JPA 2 @MapsId + @IdClass points to the pk of the entity
            if (attributeMapping instanceof ToOneAttributeMapping && !(idClassAttributeMappings.get(i) instanceof ToOneAttributeMapping)) {
                final ToOneAttributeMapping toOneAttributeMapping = (ToOneAttributeMapping) attributeMapping;
                final ModelPart targetPart = toOneAttributeMapping.getForeignKeyDescriptor().getPart(toOneAttributeMapping.getSideNature().inverse());
                if (targetPart instanceof EntityIdentifierMapping) {
                    propertyValues[i] = ((EntityIdentifierMapping) targetPart).getIdentifier(o);
                } else {
                    propertyValues[i] = o;
                    assert false;
                }
            } else {
                propertyValues[i] = o;
            }
        }
        identifierValueMapper.setValues(id, propertyValues);
        return id;
    } else {
        return entity;
    }
}
Also used : ModelPart(org.hibernate.metamodel.mapping.ModelPart) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping)

Example 32 with AttributeMapping

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

the class NonAggregatedIdentifierMappingImpl method setIdentifier.

@Override
public void setIdentifier(Object entity, Object id, SharedSessionContractImplementor session) {
    final List<AttributeMapping> mappedIdAttributeMappings = identifierValueMapper.getAttributeMappings();
    final Object[] propertyValues = new Object[mappedIdAttributeMappings.size()];
    final SessionFactoryImplementor factory = session.getFactory();
    final EntityPersister entityDescriptor = factory.getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(entity.getClass());
    getEmbeddableTypeDescriptor().forEachAttributeMapping((position, attribute) -> {
        final AttributeMapping mappedIdAttributeMapping = mappedIdAttributeMappings.get(position);
        final Object o = mappedIdAttributeMapping.getPropertyAccess().getGetter().get(id);
        if (attribute instanceof ToOneAttributeMapping && !(mappedIdAttributeMapping instanceof ToOneAttributeMapping)) {
            final ToOneAttributeMapping toOneAttributeMapping = (ToOneAttributeMapping) attribute;
            final EntityPersister entityPersister = toOneAttributeMapping.getEntityMappingType().getEntityPersister();
            final EntityKey entityKey = session.generateEntityKey(o, entityPersister);
            final PersistenceContext persistenceContext = session.getPersistenceContext();
            // it is conceivable there is a proxy, so check that first
            propertyValues[position] = persistenceContext.getProxy(entityKey);
            if (propertyValues[position] == null) {
                // otherwise look for an initialized version
                propertyValues[position] = persistenceContext.getEntity(entityKey);
                if (propertyValues[position] == null) {
                    // get the association out of the entity itself
                    propertyValues[position] = entityDescriptor.getPropertyValue(entity, toOneAttributeMapping.getAttributeName());
                }
            }
        } else {
            propertyValues[position] = o;
        }
    });
    getEmbeddableTypeDescriptor().setValues(entity, propertyValues);
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) EntityKey(org.hibernate.engine.spi.EntityKey) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) PersistenceContext(org.hibernate.engine.spi.PersistenceContext)

Example 33 with AttributeMapping

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

the class NonAggregatedIdentifierMappingImpl method toSqlExpression.

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

Example 34 with AttributeMapping

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

the class EmbeddableMappingTypeImpl method forEachDisassembledJdbcValue.

@Override
public int forEachDisassembledJdbcValue(Object value, Clause clause, int offset, JdbcValuesConsumer valuesConsumer, SharedSessionContractImplementor session) {
    final Object[] values = (Object[]) value;
    int span = 0;
    for (int i = 0; i < attributeMappings.size(); i++) {
        final AttributeMapping mapping = attributeMappings.get(i);
        span += mapping.forEachDisassembledJdbcValue(values[i], clause, span + offset, valuesConsumer, session);
    }
    return span;
}
Also used : PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping)

Example 35 with AttributeMapping

use of org.hibernate.metamodel.mapping.AttributeMapping 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)

Aggregations

AttributeMapping (org.hibernate.metamodel.mapping.AttributeMapping)56 PluralAttributeMapping (org.hibernate.metamodel.mapping.PluralAttributeMapping)38 SingularAttributeMapping (org.hibernate.metamodel.mapping.SingularAttributeMapping)20 EmbeddedAttributeMapping (org.hibernate.metamodel.mapping.internal.EmbeddedAttributeMapping)19 ToOneAttributeMapping (org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping)19 EntityPersister (org.hibernate.persister.entity.EntityPersister)17 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)13 EntityIdentifierMapping (org.hibernate.metamodel.mapping.EntityIdentifierMapping)12 DiscriminatedAssociationAttributeMapping (org.hibernate.metamodel.mapping.internal.DiscriminatedAssociationAttributeMapping)12 EntityMappingType (org.hibernate.metamodel.mapping.EntityMappingType)10 Test (org.junit.jupiter.api.Test)9 ArrayList (java.util.ArrayList)8 EmbeddableMappingType (org.hibernate.metamodel.mapping.EmbeddableMappingType)8 ModelPart (org.hibernate.metamodel.mapping.ModelPart)7 Expression (org.hibernate.sql.ast.tree.expression.Expression)7 ForeignKeyDescriptor (org.hibernate.metamodel.mapping.ForeignKeyDescriptor)6 NonAggregatedIdentifierMapping (org.hibernate.metamodel.mapping.NonAggregatedIdentifierMapping)6 Fetchable (org.hibernate.sql.results.graph.Fetchable)6 CascadeStyle (org.hibernate.engine.spi.CascadeStyle)5 NavigablePath (org.hibernate.query.spi.NavigablePath)5