Search in sources :

Example 1 with BasicValueConverter

use of org.hibernate.metamodel.model.convert.spi.BasicValueConverter in project hibernate-orm by hibernate.

the class MappingModelCreationHelper method buildBasicAttributeMapping.

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Non-identifier attributes
@SuppressWarnings("rawtypes")
public static BasicAttributeMapping buildBasicAttributeMapping(String attrName, NavigableRole navigableRole, int stateArrayPosition, Property bootProperty, ManagedMappingType declaringType, BasicType attrType, String tableExpression, String attrColumnName, boolean isAttrFormula, String readExpr, String writeExpr, String columnDefinition, Long length, Integer precision, Integer scale, PropertyAccess propertyAccess, CascadeStyle cascadeStyle, MappingModelCreationProcess creationProcess) {
    final Value value = bootProperty.getValue();
    final BasicValue.Resolution<?> resolution = ((Resolvable) value).resolve();
    final BasicValueConverter<?, ?> valueConverter = resolution.getValueConverter();
    final StateArrayContributorMetadataAccess attributeMetadataAccess = entityMappingType -> new StateArrayContributorMetadata() {

        private final MutabilityPlan mutabilityPlan = resolution.getMutabilityPlan();

        private final boolean nullable = value.isNullable();

        private final boolean insertable = bootProperty.isInsertable();

        private final boolean updateable = bootProperty.isUpdateable();

        private final boolean includeInOptimisticLocking = bootProperty.isOptimisticLocked();

        @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;
        }
    };
    final FetchTiming fetchTiming;
    final FetchStyle fetchStyle;
    if (declaringType instanceof EmbeddableMappingType) {
        if (bootProperty.isLazy()) {
            LOGGER.debugf("Attribute was declared lazy, but is part of an embeddable - `%s#%s` - LAZY will be ignored", declaringType.getNavigableRole().getFullPath(), bootProperty.getName());
        }
        fetchTiming = FetchTiming.IMMEDIATE;
        fetchStyle = FetchStyle.JOIN;
    } else {
        fetchTiming = bootProperty.isLazy() ? FetchTiming.DELAYED : FetchTiming.IMMEDIATE;
        fetchStyle = bootProperty.isLazy() ? FetchStyle.SELECT : FetchStyle.JOIN;
    }
    final ValueGeneration valueGeneration = bootProperty.getValueGenerationStrategy();
    if (valueConverter != null) {
        // we want to "decompose" the "type" into its various pieces as expected by the mapping
        assert valueConverter.getRelationalJavaType() == resolution.getRelationalJavaType();
        final BasicType<?> mappingBasicType = creationProcess.getCreationContext().getDomainModel().getTypeConfiguration().getBasicTypeRegistry().resolve(valueConverter.getRelationalJavaType(), resolution.getJdbcType());
        return new BasicAttributeMapping(attrName, navigableRole, stateArrayPosition, attributeMetadataAccess, fetchTiming, fetchStyle, tableExpression, attrColumnName, isAttrFormula, null, null, columnDefinition, length, precision, scale, valueConverter, mappingBasicType.getJdbcMapping(), declaringType, propertyAccess, valueGeneration);
    } else {
        return new BasicAttributeMapping(attrName, navigableRole, stateArrayPosition, attributeMetadataAccess, fetchTiming, fetchStyle, tableExpression, attrColumnName, isAttrFormula, readExpr, writeExpr, columnDefinition, length, precision, scale, null, attrType, declaringType, propertyAccess, valueGeneration);
    }
}
Also used : SortedSet(java.util.SortedSet) EntityPersister(org.hibernate.persister.entity.EntityPersister) Property(org.hibernate.mapping.Property) CompositeIdentifierMapping(org.hibernate.metamodel.mapping.CompositeIdentifierMapping) BasicType(org.hibernate.type.BasicType) CollectionIdentifierDescriptor(org.hibernate.metamodel.mapping.CollectionIdentifierDescriptor) Any(org.hibernate.mapping.Any) Joinable(org.hibernate.persister.entity.Joinable) PropertyAccess(org.hibernate.property.access.spi.PropertyAccess) ForeignKeyDirection(org.hibernate.type.ForeignKeyDirection) EntityMappingType(org.hibernate.metamodel.mapping.EntityMappingType) ToOne(org.hibernate.mapping.ToOne) NotYetImplementedFor6Exception(org.hibernate.NotYetImplementedFor6Exception) PluralAttributeMapping(org.hibernate.metamodel.mapping.PluralAttributeMapping) ImmutableMutabilityPlan(org.hibernate.type.descriptor.java.ImmutableMutabilityPlan) ForeignKeyDescriptor(org.hibernate.metamodel.mapping.ForeignKeyDescriptor) PersistentClass(org.hibernate.mapping.PersistentClass) TableGroupProducer(org.hibernate.sql.ast.tree.from.TableGroupProducer) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) CollectionPart(org.hibernate.metamodel.mapping.CollectionPart) StandardArraySemantics(org.hibernate.collection.internal.StandardArraySemantics) TypeConfiguration(org.hibernate.type.spi.TypeConfiguration) SimpleValue(org.hibernate.mapping.SimpleValue) OneToOne(org.hibernate.mapping.OneToOne) VirtualModelPart(org.hibernate.metamodel.mapping.VirtualModelPart) StringHelper(org.hibernate.internal.util.StringHelper) Value(org.hibernate.mapping.Value) ChainedPropertyAccessImpl(org.hibernate.property.access.internal.ChainedPropertyAccessImpl) Collection(org.hibernate.mapping.Collection) Serializable(java.io.Serializable) MappingMetamodel(org.hibernate.metamodel.MappingMetamodel) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) NavigableRole(org.hibernate.metamodel.model.domain.NavigableRole) List(java.util.List) OneToMany(org.hibernate.mapping.OneToMany) Dialect(org.hibernate.dialect.Dialect) CascadeStyle(org.hibernate.engine.spi.CascadeStyle) RuntimeModelCreationContext(org.hibernate.metamodel.spi.RuntimeModelCreationContext) MappingException(org.hibernate.MappingException) FetchMode(org.hibernate.FetchMode) SharedSessionContract(org.hibernate.SharedSessionContract) BasicValue(org.hibernate.mapping.BasicValue) CollectionPersister(org.hibernate.persister.collection.CollectionPersister) StandardIdentifierBagSemantics(org.hibernate.collection.internal.StandardIdentifierBagSemantics) CollectionMappingType(org.hibernate.metamodel.mapping.CollectionMappingType) SortedMap(java.util.SortedMap) BasicValuedModelPart(org.hibernate.metamodel.mapping.BasicValuedModelPart) MutabilityPlan(org.hibernate.type.descriptor.java.MutabilityPlan) SqlStringGenerationContext(org.hibernate.boot.model.relational.SqlStringGenerationContext) SelectableMappings(org.hibernate.metamodel.mapping.SelectableMappings) JdbcMapping(org.hibernate.metamodel.mapping.JdbcMapping) JavaType(org.hibernate.type.descriptor.java.JavaType) StandardBagSemantics(org.hibernate.collection.internal.StandardBagSemantics) SqlAliasStemHelper(org.hibernate.sql.ast.spi.SqlAliasStemHelper) EntityType(org.hibernate.type.EntityType) IndexedCollection(org.hibernate.mapping.IndexedCollection) ValueGeneration(org.hibernate.tuple.ValueGeneration) ModelPart(org.hibernate.metamodel.mapping.ModelPart) ComponentType(org.hibernate.type.ComponentType) CollectionSemantics(org.hibernate.collection.spi.CollectionSemantics) CompositeType(org.hibernate.type.CompositeType) ManagedMappingType(org.hibernate.metamodel.mapping.ManagedMappingType) SQLLoadableCollection(org.hibernate.persister.collection.SQLLoadableCollection) JavaTypeRegistry(org.hibernate.type.descriptor.java.spi.JavaTypeRegistry) FetchTiming(org.hibernate.engine.FetchTiming) ManyToOne(org.hibernate.mapping.ManyToOne) SortableValue(org.hibernate.mapping.SortableValue) Iterator(java.util.Iterator) EmbeddableMappingType(org.hibernate.metamodel.mapping.EmbeddableMappingType) ModelPartContainer(org.hibernate.metamodel.mapping.ModelPartContainer) Table(org.hibernate.mapping.Table) PropertyBasedMapping(org.hibernate.metamodel.mapping.PropertyBasedMapping) StateArrayContributorMetadataAccess(org.hibernate.metamodel.mapping.StateArrayContributorMetadataAccess) QueryableCollection(org.hibernate.persister.collection.QueryableCollection) FetchStyle(org.hibernate.engine.FetchStyle) Component(org.hibernate.mapping.Component) CollectionClassification(org.hibernate.metamodel.CollectionClassification) SelectableMapping(org.hibernate.metamodel.mapping.SelectableMapping) StateArrayContributorMetadata(org.hibernate.metamodel.mapping.StateArrayContributorMetadata) StandardListSemantics(org.hibernate.collection.internal.StandardListSemantics) Selectable(org.hibernate.mapping.Selectable) Resolvable(org.hibernate.mapping.Resolvable) EmbeddableValuedModelPart(org.hibernate.metamodel.mapping.EmbeddableValuedModelPart) BasicValueConverter(org.hibernate.metamodel.model.convert.spi.BasicValueConverter) Map(org.hibernate.mapping.Map) AssociationType(org.hibernate.type.AssociationType) Type(org.hibernate.type.Type) LOGGER(org.hibernate.metamodel.mapping.MappingModelCreationLogger.LOGGER) KeyValue(org.hibernate.mapping.KeyValue) StateArrayContributorMetadata(org.hibernate.metamodel.mapping.StateArrayContributorMetadata) Resolvable(org.hibernate.mapping.Resolvable) EmbeddableMappingType(org.hibernate.metamodel.mapping.EmbeddableMappingType) BasicValue(org.hibernate.mapping.BasicValue) FetchStyle(org.hibernate.engine.FetchStyle) ValueGeneration(org.hibernate.tuple.ValueGeneration) StateArrayContributorMetadataAccess(org.hibernate.metamodel.mapping.StateArrayContributorMetadataAccess) FetchTiming(org.hibernate.engine.FetchTiming) SimpleValue(org.hibernate.mapping.SimpleValue) Value(org.hibernate.mapping.Value) BasicValue(org.hibernate.mapping.BasicValue) SortableValue(org.hibernate.mapping.SortableValue) KeyValue(org.hibernate.mapping.KeyValue) ImmutableMutabilityPlan(org.hibernate.type.descriptor.java.ImmutableMutabilityPlan) MutabilityPlan(org.hibernate.type.descriptor.java.MutabilityPlan)

Example 2 with BasicValueConverter

use of org.hibernate.metamodel.model.convert.spi.BasicValueConverter in project hibernate-orm by hibernate.

the class DynamicResultBuilderBasicConverted method buildResult.

@Override
public BasicResult<?> buildResult(JdbcValuesMetadata jdbcResultsMetadata, int resultPosition, BiFunction<String, String, DynamicFetchBuilderLegacy> legacyFetchResolver, DomainResultCreationState domainResultCreationState) {
    final TypeConfiguration typeConfiguration = domainResultCreationState.getSqlAstCreationState().getCreationContext().getSessionFactory().getTypeConfiguration();
    final SqlExpressionResolver sqlExpressionResolver = domainResultCreationState.getSqlAstCreationState().getSqlExpressionResolver();
    final SqlSelection sqlSelection = sqlExpressionResolver.resolveSqlSelection(sqlExpressionResolver.resolveSqlExpression(columnAlias, state -> {
        final int currentJdbcPosition = resultPosition + 1;
        final int jdbcPosition;
        if (columnAlias != null) {
            jdbcPosition = jdbcResultsMetadata.resolveColumnPosition(columnAlias);
        } else {
            jdbcPosition = currentJdbcPosition;
        }
        final BasicType<?> basicType = jdbcResultsMetadata.resolveType(jdbcPosition, basicValueConverter.getRelationalJavaType(), domainResultCreationState.getSqlAstCreationState().getCreationContext().getSessionFactory());
        final int valuesArrayPosition = ResultsHelper.jdbcPositionToValuesArrayPosition(jdbcPosition);
        return new ResultSetMappingSqlSelection(valuesArrayPosition, (BasicValuedMapping) basicType);
    }), basicValueConverter.getDomainJavaType(), typeConfiguration);
    return new BasicResult<>(sqlSelection.getValuesArrayPosition(), columnAlias, basicValueConverter.getDomainJavaType(), basicValueConverter);
}
Also used : DomainResultCreationState(org.hibernate.sql.results.graph.DomainResultCreationState) JpaAttributeConverterImpl(org.hibernate.metamodel.model.convert.internal.JpaAttributeConverterImpl) ProvidedInstanceManagedBeanImpl(org.hibernate.resource.beans.spi.ProvidedInstanceManagedBeanImpl) ResultSetMappingSqlSelection(org.hibernate.query.results.ResultSetMappingSqlSelection) TypeConfiguration(org.hibernate.type.spi.TypeConfiguration) BasicType(org.hibernate.type.BasicType) BiFunction(java.util.function.BiFunction) JavaType(org.hibernate.type.descriptor.java.JavaType) BasicValuedMapping(org.hibernate.metamodel.mapping.BasicValuedMapping) BasicResult(org.hibernate.sql.results.graph.basic.BasicResult) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) Objects(java.util.Objects) JdbcValuesMetadata(org.hibernate.sql.results.jdbc.spi.JdbcValuesMetadata) ResultsHelper(org.hibernate.query.results.ResultsHelper) ManagedBean(org.hibernate.resource.beans.spi.ManagedBean) ManagedBeanRegistry(org.hibernate.resource.beans.spi.ManagedBeanRegistry) BasicValueConverter(org.hibernate.metamodel.model.convert.spi.BasicValueConverter) AttributeConverter(jakarta.persistence.AttributeConverter) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) SqlSelection(org.hibernate.sql.ast.spi.SqlSelection) JavaTypeRegistry(org.hibernate.type.descriptor.java.spi.JavaTypeRegistry) BasicValuedMapping(org.hibernate.metamodel.mapping.BasicValuedMapping) BasicType(org.hibernate.type.BasicType) SqlExpressionResolver(org.hibernate.sql.ast.spi.SqlExpressionResolver) BasicResult(org.hibernate.sql.results.graph.basic.BasicResult) TypeConfiguration(org.hibernate.type.spi.TypeConfiguration) ResultSetMappingSqlSelection(org.hibernate.query.results.ResultSetMappingSqlSelection) ResultSetMappingSqlSelection(org.hibernate.query.results.ResultSetMappingSqlSelection) SqlSelection(org.hibernate.sql.ast.spi.SqlSelection)

Example 3 with BasicValueConverter

use of org.hibernate.metamodel.model.convert.spi.BasicValueConverter in project hibernate-orm by hibernate.

the class SqmUtil method createJdbcParameterBindings.

// public static JdbcParameterBindings buildJdbcParameterBindings(
// SqmStatement sqmStatement,
// JdbcParameterBySqmParameterAccess sqmInterpretation,
// ExecutionContext executionContext) {
// final DomainParameterXref domainParameterXref = DomainParameterXref.from( sqmStatement );
// final Map<QueryParameterImplementor<?>, Map<SqmParameter, List<JdbcParameter>>> jdbcParamsXref =
// generateJdbcParamsXref( domainParameterXref, sqmInterpretation );
// return createJdbcParameterBindings(
// executionContext.getDomainParameterBindingContext().getQueryParameterBindings(),
// domainParameterXref,
// jdbcParamsXref,
// executionContext.getSession()
// );
// }
// public static JdbcParameterBindings buildJdbcParameterBindings(
// SqmStatement sqmStatement,
// Map<QueryParameterImplementor<?>, Map<SqmParameter, List<JdbcParameter>>> jdbcParamsXref,
// ExecutionContext executionContext) {
// final DomainParameterXref domainParameterXref = DomainParameterXref.from( sqmStatement );
// return createJdbcParameterBindings(
// executionContext.getDomainParameterBindingContext().getQueryParameterBindings(),
// domainParameterXref,
// jdbcParamsXref,
// executionContext.getSession()
// );
// }
// public static JdbcParameterBindings buildJdbcParameterBindings(
// DomainParameterXref domainParameterXref,
// Map<QueryParameterImplementor<?>, Map<SqmParameter, List<JdbcParameter>>> jdbcParamsXref,
// ExecutionContext executionContext) {
// return createJdbcParameterBindings(
// executionContext.getDomainParameterBindingContext().getQueryParameterBindings(),
// domainParameterXref,
// jdbcParamsXref,
// executionContext.getSession()
// );
// }
public static JdbcParameterBindings createJdbcParameterBindings(QueryParameterBindings domainParamBindings, DomainParameterXref domainParameterXref, Map<QueryParameterImplementor<?>, Map<SqmParameter<?>, List<List<JdbcParameter>>>> jdbcParamXref, MappingMetamodel domainModel, Function<NavigablePath, TableGroup> tableGroupLocator, SqmParameterMappingModelResolutionAccess mappingModelResolutionAccess, SharedSessionContractImplementor session) {
    final JdbcParameterBindings jdbcParameterBindings = new JdbcParameterBindingsImpl(domainParameterXref.getSqmParameterCount());
    for (Map.Entry<QueryParameterImplementor<?>, List<SqmParameter<?>>> entry : domainParameterXref.getSqmParamByQueryParam().entrySet()) {
        final QueryParameterImplementor<?> queryParam = entry.getKey();
        final List<SqmParameter<?>> sqmParameters = entry.getValue();
        final QueryParameterBinding<?> domainParamBinding = domainParamBindings.getBinding(queryParam);
        final Map<SqmParameter<?>, List<List<JdbcParameter>>> jdbcParamMap = jdbcParamXref.get(queryParam);
        for (SqmParameter<?> sqmParameter : sqmParameters) {
            final Bindable parameterType = determineParameterType(domainParamBinding, queryParam, sqmParameters, mappingModelResolutionAccess, session.getFactory());
            final List<List<JdbcParameter>> jdbcParamsBinds = jdbcParamMap.get(sqmParameter);
            if (jdbcParamsBinds == null) {
                // is replaced with an alias reference expression, which can happen for JPA Criteria queries
                continue;
            }
            if (!domainParamBinding.isBound()) {
                for (int i = 0; i < jdbcParamsBinds.size(); i++) {
                    final List<JdbcParameter> jdbcParams = jdbcParamsBinds.get(i);
                    parameterType.forEachJdbcType((position, jdbcType) -> {
                        jdbcParameterBindings.addBinding(jdbcParams.get(position), new JdbcParameterBindingImpl(jdbcType, null));
                    });
                }
            } else if (domainParamBinding.isMultiValued()) {
                final Collection<?> bindValues = domainParamBinding.getBindValues();
                final Iterator<?> valueItr = bindValues.iterator();
                // the original SqmParameter is the one we are processing.. create a binding for it..
                for (int i = 0; i < jdbcParamsBinds.size(); i++) {
                    final List<JdbcParameter> jdbcParams = jdbcParamsBinds.get(i);
                    createValueBindings(jdbcParameterBindings, queryParam, domainParamBinding, parameterType, jdbcParams, valueItr.next(), tableGroupLocator, session);
                }
                // an then one for each of the expansions
                final List<SqmParameter<?>> expansions = domainParameterXref.getExpansions(sqmParameter);
                assert expansions.size() == bindValues.size() - 1;
                int expansionPosition = 0;
                while (valueItr.hasNext()) {
                    final SqmParameter<?> expansionSqmParam = expansions.get(expansionPosition++);
                    final List<List<JdbcParameter>> jdbcParamBinds = jdbcParamMap.get(expansionSqmParam);
                    for (int i = 0; i < jdbcParamBinds.size(); i++) {
                        List<JdbcParameter> expansionJdbcParams = jdbcParamBinds.get(i);
                        createValueBindings(jdbcParameterBindings, queryParam, domainParamBinding, parameterType, expansionJdbcParams, valueItr.next(), tableGroupLocator, session);
                    }
                }
            } else if (domainParamBinding.getBindValue() == null) {
                for (int i = 0; i < jdbcParamsBinds.size(); i++) {
                    final List<JdbcParameter> jdbcParams = jdbcParamsBinds.get(i);
                    for (int j = 0; j < jdbcParams.size(); j++) {
                        final JdbcParameter jdbcParameter = jdbcParams.get(j);
                        jdbcParameterBindings.addBinding(jdbcParameter, new JdbcParameterBindingImpl(null, null));
                    }
                }
            } else {
                if (domainParamBinding.getType() instanceof AttributeConverterTypeAdapter || domainParamBinding.getType() instanceof ConvertibleModelPart) {
                    final BasicValueConverter valueConverter;
                    final JdbcMapping jdbcMapping;
                    if (domainParamBinding.getType() instanceof AttributeConverterTypeAdapter) {
                        final AttributeConverterTypeAdapter<?> adapter = (AttributeConverterTypeAdapter<?>) domainParamBinding.getType();
                        valueConverter = adapter.getAttributeConverter();
                        jdbcMapping = adapter.getJdbcMapping();
                    } else {
                        final ConvertibleModelPart convertibleModelPart = (ConvertibleModelPart) domainParamBinding.getType();
                        valueConverter = convertibleModelPart.getValueConverter();
                        jdbcMapping = convertibleModelPart.getJdbcMapping();
                    }
                    if (valueConverter != null) {
                        final Object convertedValue = valueConverter.toRelationalValue(domainParamBinding.getBindValue());
                        for (int i = 0; i < jdbcParamsBinds.size(); i++) {
                            final List<JdbcParameter> jdbcParams = jdbcParamsBinds.get(i);
                            assert jdbcParams.size() == 1;
                            final JdbcParameter jdbcParameter = jdbcParams.get(0);
                            jdbcParameterBindings.addBinding(jdbcParameter, new JdbcParameterBindingImpl(jdbcMapping, convertedValue));
                        }
                        continue;
                    }
                }
                final Object bindValue = domainParamBinding.getBindValue();
                for (int i = 0; i < jdbcParamsBinds.size(); i++) {
                    final List<JdbcParameter> jdbcParams = jdbcParamsBinds.get(i);
                    createValueBindings(jdbcParameterBindings, queryParam, domainParamBinding, parameterType, jdbcParams, bindValue, tableGroupLocator, session);
                }
            }
        }
    }
    return jdbcParameterBindings;
}
Also used : JdbcMapping(org.hibernate.metamodel.mapping.JdbcMapping) ConvertibleModelPart(org.hibernate.metamodel.mapping.ConvertibleModelPart) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) JdbcParameterBindingsImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingsImpl) JdbcParameter(org.hibernate.sql.ast.tree.expression.JdbcParameter) Bindable(org.hibernate.metamodel.mapping.Bindable) JdbcParameterBindingImpl(org.hibernate.sql.exec.internal.JdbcParameterBindingImpl) AttributeConverterTypeAdapter(org.hibernate.type.descriptor.converter.AttributeConverterTypeAdapter) QueryParameterImplementor(org.hibernate.query.spi.QueryParameterImplementor) Collection(java.util.Collection) SqmParameter(org.hibernate.query.sqm.tree.expression.SqmParameter) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap) JdbcParameterBindings(org.hibernate.sql.exec.spi.JdbcParameterBindings) BasicValueConverter(org.hibernate.metamodel.model.convert.spi.BasicValueConverter)

Example 4 with BasicValueConverter

use of org.hibernate.metamodel.model.convert.spi.BasicValueConverter in project hibernate-orm by hibernate.

the class BasicTypeRegistry method resolveTypeReference.

private BasicType<?> resolveTypeReference(String name) {
    final BasicTypeReference<?> typeReference = typeReferencesByName.get(name);
    if (typeReference == null) {
        return null;
    }
    if (!name.equals(typeReference.getName())) {
        final BasicType<?> basicType = typesByName.get(typeReference.getName());
        if (basicType != null) {
            return basicType;
        }
    }
    final JavaType<Object> javaType = typeConfiguration.getJavaTypeRegistry().getDescriptor(typeReference.getBindableJavaType());
    final JdbcType jdbcType = typeConfiguration.getJdbcTypeRegistry().getDescriptor(typeReference.getSqlTypeCode());
    final BasicType<?> type;
    if (typeReference.getConverter() == null) {
        if (typeReference.isForceImmutable()) {
            type = new ImmutableNamedBasicTypeImpl<>(javaType, jdbcType, typeReference.getName());
        } else {
            type = new NamedBasicTypeImpl<>(javaType, jdbcType, typeReference.getName());
        }
    } else {
        if (typeReference.isForceImmutable()) {
            // noinspection unchecked
            type = new ImmutableConvertedBasicTypeImpl<>(javaType, jdbcType, typeReference.getName(), (BasicValueConverter<Object, ?>) typeReference.getConverter());
        } else {
            // noinspection unchecked
            type = new ConvertedBasicTypeImpl<>(javaType, jdbcType, typeReference.getName(), (BasicValueConverter<Object, ?>) typeReference.getConverter());
        }
    }
    primeRegistryEntry(type);
    typesByName.put(typeReference.getName(), type);
    typesByName.put(name, type);
    return type;
}
Also used : JdbcType(org.hibernate.type.descriptor.jdbc.JdbcType) BasicValueConverter(org.hibernate.metamodel.model.convert.spi.BasicValueConverter)

Example 5 with BasicValueConverter

use of org.hibernate.metamodel.model.convert.spi.BasicValueConverter in project hibernate-orm by hibernate.

the class SmokeTests method testSimpleEntity.

@Test
public void testSimpleEntity(SessionFactoryScope scope) {
    final EntityPersister entityDescriptor = scope.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel().getEntityDescriptor(SimpleEntity.class);
    final JdbcTypeRegistry jdbcTypeRegistry = entityDescriptor.getFactory().getTypeConfiguration().getJdbcTypeRegistry();
    final EntityIdentifierMapping identifierMapping = entityDescriptor.getIdentifierMapping();
    assertThat(identifierMapping.getMappedType().getMappedJavaType().getJavaTypeClass(), sameInstance(Integer.class));
    {
        final ModelPart namePart = entityDescriptor.findSubPart("name");
        assert namePart instanceof BasicAttributeMapping;
        assert "mapping_simple_entity".equals(((BasicAttributeMapping) namePart).getContainingTableExpression());
        assert "name".equals(((BasicAttributeMapping) namePart).getSelectionExpression());
    }
    {
        final ModelPart genderPart = entityDescriptor.findSubPart("gender");
        assert genderPart instanceof BasicAttributeMapping;
        final BasicAttributeMapping genderAttrMapping = (BasicAttributeMapping) genderPart;
        assert "mapping_simple_entity".equals(genderAttrMapping.getContainingTableExpression());
        assert "gender".equals(genderAttrMapping.getSelectionExpression());
        assertThat(genderAttrMapping.getJavaType().getJavaTypeClass(), equalTo(Gender.class));
        final BasicValueConverter valueConverter = genderAttrMapping.getValueConverter();
        assertThat(valueConverter, instanceOf(OrdinalEnumValueConverter.class));
        assertThat(valueConverter.getDomainJavaType(), is(genderAttrMapping.getJavaType()));
        assertThat(valueConverter.getRelationalJavaType().getJavaTypeClass(), equalTo(Integer.class));
        assertThat(genderAttrMapping.getJdbcMapping().getJdbcType(), is(jdbcTypeRegistry.getDescriptor(Types.TINYINT)));
    }
    {
        final ModelPart part = entityDescriptor.findSubPart("gender2");
        assert part instanceof BasicAttributeMapping;
        final BasicAttributeMapping attrMapping = (BasicAttributeMapping) part;
        assert "mapping_simple_entity".equals(attrMapping.getContainingTableExpression());
        assert "gender2".equals(attrMapping.getSelectionExpression());
        assertThat(attrMapping.getJavaType().getJavaTypeClass(), equalTo(Gender.class));
        final BasicValueConverter valueConverter = attrMapping.getValueConverter();
        assertThat(valueConverter, instanceOf(NamedEnumValueConverter.class));
        assertThat(valueConverter.getDomainJavaType(), is(attrMapping.getJavaType()));
        assertThat(valueConverter.getRelationalJavaType().getJavaTypeClass(), equalTo(String.class));
        assertThat(attrMapping.getJdbcMapping().getJdbcType(), is(jdbcTypeRegistry.getDescriptor(Types.VARCHAR)));
    }
    {
        final ModelPart part = entityDescriptor.findSubPart("gender3");
        assert part instanceof BasicAttributeMapping;
        final BasicAttributeMapping attrMapping = (BasicAttributeMapping) part;
        assert "mapping_simple_entity".equals(attrMapping.getContainingTableExpression());
        assert "gender3".equals(attrMapping.getSelectionExpression());
        assertThat(attrMapping.getJavaType().getJavaTypeClass(), equalTo(Gender.class));
        final BasicValueConverter valueConverter = attrMapping.getValueConverter();
        assertThat(valueConverter, instanceOf(JpaAttributeConverter.class));
        assertThat(valueConverter.getDomainJavaType(), is(attrMapping.getJavaType()));
        assertThat(valueConverter.getRelationalJavaType().getJavaTypeClass(), equalTo(Character.class));
        assertThat(attrMapping.getJdbcMapping().getJdbcType(), is(jdbcTypeRegistry.getDescriptor(Types.CHAR)));
    }
    {
        final ModelPart part = entityDescriptor.findSubPart("component");
        assert part instanceof EmbeddedAttributeMapping;
        final EmbeddedAttributeMapping attrMapping = (EmbeddedAttributeMapping) part;
        assertThat(attrMapping.getContainingTableExpression(), is("mapping_simple_entity"));
        assertThat(attrMapping.getEmbeddableTypeDescriptor().getJdbcTypeCount(), is(4));
        assertThat(attrMapping.getEmbeddableTypeDescriptor().getSelectable(0).getSelectionExpression(), is("attribute1"));
        assertThat(attrMapping.getEmbeddableTypeDescriptor().getSelectable(1).getSelectionExpression(), is("attribute2"));
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) ModelPart(org.hibernate.metamodel.mapping.ModelPart) EmbeddedAttributeMapping(org.hibernate.metamodel.mapping.internal.EmbeddedAttributeMapping) BasicAttributeMapping(org.hibernate.metamodel.mapping.internal.BasicAttributeMapping) EntityIdentifierMapping(org.hibernate.metamodel.mapping.EntityIdentifierMapping) JdbcTypeRegistry(org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry) BasicValueConverter(org.hibernate.metamodel.model.convert.spi.BasicValueConverter) Test(org.junit.jupiter.api.Test)

Aggregations

BasicValueConverter (org.hibernate.metamodel.model.convert.spi.BasicValueConverter)6 Iterator (java.util.Iterator)2 List (java.util.List)2 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)2 JdbcMapping (org.hibernate.metamodel.mapping.JdbcMapping)2 ModelPart (org.hibernate.metamodel.mapping.ModelPart)2 BasicAttributeMapping (org.hibernate.metamodel.mapping.internal.BasicAttributeMapping)2 BasicType (org.hibernate.type.BasicType)2 JavaType (org.hibernate.type.descriptor.java.JavaType)2 JavaTypeRegistry (org.hibernate.type.descriptor.java.spi.JavaTypeRegistry)2 JdbcTypeRegistry (org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry)2 TypeConfiguration (org.hibernate.type.spi.TypeConfiguration)2 AttributeConverter (jakarta.persistence.AttributeConverter)1 Serializable (java.io.Serializable)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 IdentityHashMap (java.util.IdentityHashMap)1 Map (java.util.Map)1 Objects (java.util.Objects)1 SortedMap (java.util.SortedMap)1