Search in sources :

Example 21 with AttributeMapping

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

the class XmlAccessTest method assertAccessType.

// uses the first getter of the tupelizer for the assertions
private void assertAccessType(SessionFactoryImplementor factory, Class<?> classUnderTest, AccessType accessType) {
    final EntityPersister entityDescriptor = factory.getRuntimeMetamodels().getMappingMetamodel().findEntityDescriptor(classUnderTest.getName());
    final Collection<AttributeMapping> attributeMappings = entityDescriptor.getAttributeMappings();
    final AttributeMapping attributeMapping = attributeMappings.iterator().next();
    final Getter accessGetter = attributeMapping.getPropertyAccess().getGetter();
    if (AccessType.FIELD.equals(accessType)) {
        assertTrue(accessGetter instanceof GetterFieldImpl, "Field access was expected.");
    } else {
        assertTrue(accessGetter instanceof GetterMethodImpl, "Property access was expected.");
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) GetterFieldImpl(org.hibernate.property.access.spi.GetterFieldImpl) Getter(org.hibernate.property.access.spi.Getter) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) GetterMethodImpl(org.hibernate.property.access.spi.GetterMethodImpl)

Example 22 with AttributeMapping

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

the class EnhancementAsProxyLazinessInterceptor method handleRead.

@Override
protected Object handleRead(Object target, String attributeName, Object value) {
    // it is illegal for this interceptor to still be attached to the entity after initialization
    if (isInitialized()) {
        throw new IllegalStateException("EnhancementAsProxyLazinessInterceptor interception on an initialized instance");
    }
    // - we already know the id, return that
    if (identifierAttributeNames.contains(attributeName)) {
        return extractIdValue(target, attributeName);
    }
    // Use `performWork` to group together multiple Session accesses
    return EnhancementHelper.performWork(this, (session, isTempSession) -> {
        final Object[] writtenValues;
        final EntityPersister entityPersister = session.getFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(getEntityName());
        if (writtenFieldNames != null && !writtenFieldNames.isEmpty()) {
            if (writtenFieldNames.contains(attributeName)) {
                // the requested attribute was one of the attributes explicitly set, we can just return the explicitly set value
                return entityPersister.getPropertyValue(target, attributeName);
            }
            // otherwise we want to save all of the explicitly set values in anticipation of
            // the force initialization below so that we can "replay" them after the
            // initialization
            writtenValues = new Object[writtenFieldNames.size()];
            int index = 0;
            for (String writtenFieldName : writtenFieldNames) {
                writtenValues[index] = entityPersister.getPropertyValue(target, writtenFieldName);
                index++;
            }
        } else {
            writtenValues = null;
        }
        final Object initializedValue = forceInitialize(target, attributeName, session, isTempSession);
        setInitialized();
        if (writtenValues != null) {
            // here is the replaying of the explicitly set values we prepared above
            for (String writtenFieldName : writtenFieldNames) {
                List<AttributeMapping> attributeMappings = entityPersister.getAttributeMappings();
                for (int index = 0; index < attributeMappings.size(); index++) {
                    if (writtenFieldName.contains(attributeMappings.get(index).getAttributeName())) {
                        entityPersister.setValue(target, index, writtenValues[index]);
                    }
                }
            }
            writtenFieldNames.clear();
        }
        return initializedValue;
    }, getEntityName(), attributeName);
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping)

Example 23 with AttributeMapping

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

the class Builders method attributeResult.

public static ResultBuilder attributeResult(String columnAlias, String entityName, String attributePath, SessionFactoryImplementor sessionFactory) {
    if (attributePath.contains(".")) {
        throw new NotYetImplementedFor6Exception("Support for defining a NativeQuery attribute result based on a composite path is not yet implemented");
    }
    final RuntimeMetamodels runtimeMetamodels = sessionFactory.getRuntimeMetamodels();
    final String fullEntityName = runtimeMetamodels.getMappingMetamodel().getImportedName(entityName);
    final EntityPersister entityMapping = runtimeMetamodels.getMappingMetamodel().findEntityDescriptor(fullEntityName);
    if (entityMapping == null) {
        throw new IllegalArgumentException("Could not locate entity mapping : " + fullEntityName);
    }
    final AttributeMapping attributeMapping = entityMapping.findAttributeMapping(attributePath);
    if (attributeMapping == null) {
        throw new IllegalArgumentException("Could not locate attribute mapping : " + fullEntityName + "." + attributePath);
    }
    if (attributeMapping instanceof SingularAttributeMapping) {
        final SingularAttributeMapping singularAttributeMapping = (SingularAttributeMapping) attributeMapping;
        return new DynamicResultBuilderAttribute(singularAttributeMapping, columnAlias, fullEntityName, attributePath);
    }
    throw new IllegalArgumentException(String.format(Locale.ROOT, "Specified attribute mapping [%s.%s] not a basic attribute: %s", fullEntityName, attributePath, attributeMapping));
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) DynamicResultBuilderAttribute(org.hibernate.query.results.dynamic.DynamicResultBuilderAttribute) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) ToOneAttributeMapping(org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping) SingularAttributeMapping(org.hibernate.metamodel.mapping.SingularAttributeMapping) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) NotYetImplementedFor6Exception(org.hibernate.NotYetImplementedFor6Exception) RuntimeMetamodels(org.hibernate.metamodel.RuntimeMetamodels) SingularAttributeMapping(org.hibernate.metamodel.mapping.SingularAttributeMapping)

Example 24 with AttributeMapping

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

the class BaseSqmToSqlAstConverter method transformDurationArithmetic.

private Object transformDurationArithmetic(SqmBinaryArithmetic<?> expression) {
    BinaryArithmeticOperator operator = expression.getOperator();
    // the expression tree
    switch(operator) {
        case ADD:
        case SUBTRACT:
            // the only legal binary operations involving
            // a duration with a date or timestamp are
            // addition and subtraction with the duration
            // on the right and the date or timestamp on
            // the left, producing a date or timestamp
            // 
            // ts + d or ts - d
            // 
            // the only legal binary operations involving
            // two durations are addition and subtraction,
            // producing a duration
            // 
            // d1 + d2
            // re-express addition of non-leaf duration
            // expressions to a date or timestamp as
            // addition of leaf durations to a date or
            // timestamp
            // ts + x * (d1 + d2) => (ts + x * d1) + x * d2
            // ts - x * (d1 + d2) => (ts - x * d1) - x * d2
            // ts + x * (d1 - d2) => (ts + x * d1) - x * d2
            // ts - x * (d1 - d2) => (ts - x * d1) + x * d2
            Expression timestamp = adjustedTimestamp;
            SqmExpressible<?> timestampType = adjustedTimestampType;
            adjustedTimestamp = toSqlExpression(expression.getLeftHandOperand().accept(this));
            JdbcMappingContainer type = adjustedTimestamp.getExpressionType();
            if (type instanceof SqmExpressible) {
                adjustedTimestampType = (SqmExpressible<?>) type;
            } else if (type instanceof AttributeMapping) {
                adjustedTimestampType = (SqmExpressible<?>) ((AttributeMapping) type).getMappedType();
            } else {
                // else we know it has not been transformed
                adjustedTimestampType = expression.getLeftHandOperand().getNodeType();
            }
            if (operator == SUBTRACT) {
                negativeAdjustment = !negativeAdjustment;
            }
            try {
                return expression.getRightHandOperand().accept(this);
            } finally {
                if (operator == SUBTRACT) {
                    negativeAdjustment = !negativeAdjustment;
                }
                adjustedTimestamp = timestamp;
                adjustedTimestampType = timestampType;
            }
        case MULTIPLY:
            // finally, we can multiply a duration on the
            // right by a scalar value on the left
            // scalar multiplication produces a duration
            // x * d
            // distribute scalar multiplication over the
            // terms, not forgetting the propagated scale
            // x * (d1 + d2) => x * d1 + x * d2
            // x * (d1 - d2) => x * d1 - x * d2
            // -x * (d1 + d2) => - x * d1 - x * d2
            // -x * (d1 - d2) => - x * d1 + x * d2
            Expression duration = toSqlExpression(expression.getLeftHandOperand().accept(this));
            Expression scale = adjustmentScale;
            boolean negate = negativeAdjustment;
            adjustmentScale = applyScale(duration);
            // was sucked into the scale
            negativeAdjustment = false;
            try {
                return expression.getRightHandOperand().accept(this);
            } finally {
                adjustmentScale = scale;
                negativeAdjustment = negate;
            }
        default:
            throw new SemanticException("illegal operator for a duration " + operator);
    }
}
Also used : JdbcMappingContainer(org.hibernate.metamodel.mapping.JdbcMappingContainer) SqmExpressible(org.hibernate.query.sqm.SqmExpressible) 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) BinaryArithmeticOperator(org.hibernate.query.sqm.BinaryArithmeticOperator) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) ToOneAttributeMapping(org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) SemanticException(org.hibernate.query.SemanticException)

Example 25 with AttributeMapping

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

the class AbstractEntityPersister method setPropertyValues.

@Override
public void setPropertyValues(Object object, Object[] values) {
    if (accessOptimizer != null) {
        accessOptimizer.setPropertyValues(object, values);
    } else {
        if (hasSubclasses()) {
            visitAttributeMappings(attribute -> {
                final int stateArrayPosition = ((StateArrayContributorMapping) attribute).getStateArrayPosition();
                final Object value = values[stateArrayPosition];
                if (value != UNFETCHED_PROPERTY) {
                    final Setter setter = attribute.getPropertyAccess().getSetter();
                    setter.set(object, value);
                }
            });
        } else {
            visitFetchables(fetchable -> {
                final AttributeMapping attribute = (AttributeMapping) fetchable;
                final int stateArrayPosition = ((StateArrayContributorMapping) attribute).getStateArrayPosition();
                final Object value = values[stateArrayPosition];
                if (value != UNFETCHED_PROPERTY) {
                    final Setter setter = attribute.getPropertyAccess().getSetter();
                    setter.set(object, value);
                }
            }, null);
        }
    }
}
Also used : StateArrayContributorMapping(org.hibernate.metamodel.mapping.StateArrayContributorMapping) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) EmbeddedAttributeMapping(org.hibernate.metamodel.mapping.internal.EmbeddedAttributeMapping) DiscriminatedAssociationAttributeMapping(org.hibernate.metamodel.mapping.internal.DiscriminatedAssociationAttributeMapping) ToOneAttributeMapping(org.hibernate.metamodel.mapping.internal.ToOneAttributeMapping) SingularAttributeMapping(org.hibernate.metamodel.mapping.SingularAttributeMapping) AttributeMapping(org.hibernate.metamodel.mapping.AttributeMapping) Setter(org.hibernate.property.access.spi.Setter)

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