Search in sources :

Example 6 with JavaTypeRegistry

use of org.hibernate.type.descriptor.java.spi.JavaTypeRegistry in project hibernate-orm by hibernate.

the class Converters method jpaAttributeConverter.

/**
 * Generates a BasicValueConverter based on an {@link AttributeConverter}
 */
public static <O, R> BasicValueConverter<O, R> jpaAttributeConverter(JavaType<R> relationalJtd, JavaType<O> domainJtd, Class<? extends AttributeConverter<O, R>> converterClass, SessionFactory factory) {
    final SessionFactoryImplementor sfi = (SessionFactoryImplementor) factory;
    final ManagedBeanRegistry beanRegistry = sfi.getServiceRegistry().getService(ManagedBeanRegistry.class);
    final ManagedBean<? extends AttributeConverter<O, R>> converterBean = beanRegistry.getBean(converterClass);
    final TypeConfiguration typeConfiguration = sfi.getTypeConfiguration();
    final JavaTypeRegistry jtdRegistry = typeConfiguration.getJavaTypeRegistry();
    final JavaType<? extends AttributeConverter<O, R>> converterJtd = jtdRegistry.getDescriptor(converterClass);
    return new JpaAttributeConverterImpl<>(converterBean, converterJtd, domainJtd, relationalJtd);
}
Also used : JavaTypeRegistry(org.hibernate.type.descriptor.java.spi.JavaTypeRegistry) ManagedBeanRegistry(org.hibernate.resource.beans.spi.ManagedBeanRegistry) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) JpaAttributeConverterImpl(org.hibernate.metamodel.model.convert.internal.JpaAttributeConverterImpl) TypeConfiguration(org.hibernate.type.spi.TypeConfiguration)

Example 7 with JavaTypeRegistry

use of org.hibernate.type.descriptor.java.spi.JavaTypeRegistry in project hibernate-orm by hibernate.

the class MappingModelCreationHelper method interpretElement.

private static CollectionPart interpretElement(Collection bootDescriptor, String tableExpression, CollectionPersister collectionDescriptor, String sqlAliasStem, Dialect dialect, MappingModelCreationProcess creationProcess) {
    final Value element = bootDescriptor.getElement();
    if (element instanceof BasicValue) {
        final BasicValue basicElement = (BasicValue) element;
        final SelectableMapping selectableMapping = SelectableMappingImpl.from(tableExpression, basicElement.getSelectables().get(0), basicElement.resolve().getJdbcMapping(), dialect, creationProcess.getSqmFunctionRegistry());
        return new BasicValuedCollectionPart(collectionDescriptor, CollectionPart.Nature.ELEMENT, basicElement.resolve().getValueConverter(), selectableMapping);
    }
    if (element instanceof Component) {
        final Component component = (Component) element;
        final CompositeType compositeType = (CompositeType) collectionDescriptor.getElementType();
        final EmbeddableMappingTypeImpl mappingType = EmbeddableMappingTypeImpl.from(component, compositeType, embeddableMappingType -> new EmbeddedCollectionPart(collectionDescriptor, CollectionPart.Nature.ELEMENT, embeddableMappingType, // parent-injection
        component.getParentProperty(), tableExpression, sqlAliasStem), creationProcess);
        return (CollectionPart) mappingType.getEmbeddedValueMapping();
    }
    if (element instanceof Any) {
        final Any anyBootMapping = (Any) element;
        final SessionFactoryImplementor sessionFactory = creationProcess.getCreationContext().getSessionFactory();
        final TypeConfiguration typeConfiguration = sessionFactory.getTypeConfiguration();
        final JavaTypeRegistry jtdRegistry = typeConfiguration.getJavaTypeRegistry();
        final JavaType<Object> baseJtd = jtdRegistry.getDescriptor(Object.class);
        return new DiscriminatedCollectionPart(CollectionPart.Nature.ELEMENT, collectionDescriptor, baseJtd, anyBootMapping, anyBootMapping.getType(), creationProcess);
    }
    if (element instanceof OneToMany || element instanceof ToOne) {
        final EntityType elementEntityType = (EntityType) collectionDescriptor.getElementType();
        final EntityPersister associatedEntity = creationProcess.getEntityPersister(elementEntityType.getAssociatedEntityName());
        final EntityCollectionPart elementDescriptor = new EntityCollectionPart(collectionDescriptor, CollectionPart.Nature.ELEMENT, bootDescriptor.getElement(), associatedEntity, creationProcess);
        creationProcess.registerInitializationCallback("PluralAttributeMapping( " + elementDescriptor.getNavigableRole() + ") - index descriptor", () -> {
            elementDescriptor.finishInitialization(collectionDescriptor, bootDescriptor, elementEntityType.getRHSUniqueKeyPropertyName(), creationProcess);
            return true;
        });
        return elementDescriptor;
    }
    throw new NotYetImplementedFor6Exception("Support for plural attributes with element type [" + element + "] not yet implemented");
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) SelectableMapping(org.hibernate.metamodel.mapping.SelectableMapping) SessionFactoryImplementor(org.hibernate.engine.spi.SessionFactoryImplementor) OneToMany(org.hibernate.mapping.OneToMany) Any(org.hibernate.mapping.Any) BasicValue(org.hibernate.mapping.BasicValue) EntityType(org.hibernate.type.EntityType) JavaTypeRegistry(org.hibernate.type.descriptor.java.spi.JavaTypeRegistry) 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) ToOne(org.hibernate.mapping.ToOne) OneToOne(org.hibernate.mapping.OneToOne) ManyToOne(org.hibernate.mapping.ManyToOne) NotYetImplementedFor6Exception(org.hibernate.NotYetImplementedFor6Exception) Component(org.hibernate.mapping.Component) CollectionPart(org.hibernate.metamodel.mapping.CollectionPart) TypeConfiguration(org.hibernate.type.spi.TypeConfiguration) CompositeType(org.hibernate.type.CompositeType)

Example 8 with JavaTypeRegistry

use of org.hibernate.type.descriptor.java.spi.JavaTypeRegistry in project hibernate-orm by hibernate.

the class MappingModelCreationHelper method buildPluralAttributeMapping.

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

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

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

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

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

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

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

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

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

Example 9 with JavaTypeRegistry

use of org.hibernate.type.descriptor.java.spi.JavaTypeRegistry in project hibernate-orm by hibernate.

the class Util method resolveResultSetMappingClasses.

public static void resolveResultSetMappingClasses(Class[] resultSetMappingClasses, ResultSetMapping resultSetMapping, Consumer<String> querySpaceConsumer, ResultSetMappingResolutionContext context) {
    final MappingMetamodelImplementor mappingMetamodel = context.getSessionFactory().getRuntimeMetamodels().getMappingMetamodel();
    final JavaTypeRegistry javaTypeRegistry = mappingMetamodel.getTypeConfiguration().getJavaTypeRegistry();
    for (Class<?> resultSetMappingClass : resultSetMappingClasses) {
        final EntityPersister entityDescriptor = mappingMetamodel.findEntityDescriptor(resultSetMappingClass);
        if (entityDescriptor != null) {
            resultSetMapping.addResultBuilder(new EntityDomainResultBuilder(entityDescriptor));
            for (String querySpace : entityDescriptor.getSynchronizedQuerySpaces()) {
                querySpaceConsumer.accept(querySpace);
            }
        } else {
            final JavaType<?> basicType = javaTypeRegistry.getDescriptor(resultSetMappingClass);
            if (basicType != null) {
                resultSetMapping.addResultBuilder(new ScalarDomainResultBuilder<>(basicType));
            }
        }
    }
}
Also used : EntityPersister(org.hibernate.persister.entity.EntityPersister) JavaTypeRegistry(org.hibernate.type.descriptor.java.spi.JavaTypeRegistry) MappingMetamodelImplementor(org.hibernate.metamodel.spi.MappingMetamodelImplementor)

Example 10 with JavaTypeRegistry

use of org.hibernate.type.descriptor.java.spi.JavaTypeRegistry in project hibernate-orm by hibernate.

the class OutputsImpl method extractResults.

protected List extractResults(ResultSet resultSet) {
    final DirectResultSetAccess resultSetAccess = new DirectResultSetAccess(context.getSession(), jdbcStatement, resultSet);
    final ProcedureCallImpl procedureCall = (ProcedureCallImpl) context;
    final ResultSetMapping resultSetMapping = procedureCall.getResultSetMapping();
    final JavaTypeRegistry javaTypeRegistry = context.getSession().getTypeConfiguration().getJavaTypeRegistry();
    procedureCall.getParameterBindings().visitBindings((parameterImplementor, queryParameterBinding) -> {
        ProcedureParameter parameter = (ProcedureParameter) parameterImplementor;
        if (parameter.getMode() == ParameterMode.INOUT) {
            final JavaType<?> basicType = javaTypeRegistry.getDescriptor(parameterImplementor.getParameterType());
            if (basicType != null) {
                resultSetMapping.addResultBuilder(new ScalarDomainResultBuilder<>(basicType));
            } else {
                throw new NotYetImplementedFor6Exception(getClass());
            }
        }
    });
    final ExecutionContext executionContext = new ExecutionContext() {

        private final Callback callback = new CallbackImpl();

        @Override
        public SharedSessionContractImplementor getSession() {
            return OutputsImpl.this.context.getSession();
        }

        @Override
        public QueryOptions getQueryOptions() {
            return new QueryOptionsAdapter() {

                @Override
                public Boolean isReadOnly() {
                    return false;
                }
            };
        }

        @Override
        public String getQueryIdentifier(String sql) {
            return sql;
        }

        @Override
        public QueryParameterBindings getQueryParameterBindings() {
            return QueryParameterBindings.NO_PARAM_BINDINGS;
        }

        @Override
        public Callback getCallback() {
            return callback;
        }
    };
    final JdbcValues jdbcValues = new JdbcValuesResultSetImpl(resultSetAccess, null, null, this.context.getQueryOptions(), resultSetMapping.resolve(resultSetAccess, getSessionFactory()), null, executionContext);
    final RowReader<Object[]> rowReader = (RowReader<Object[]>) ResultsHelper.createRowReader(executionContext, null, RowTransformerPassThruImpl.INSTANCE, jdbcValues);
    /*
		 * Processing options effectively are only used for entity loading.  Here we don't need these values.
		 */
    final JdbcValuesSourceProcessingOptions processingOptions = new JdbcValuesSourceProcessingOptions() {

        @Override
        public Object getEffectiveOptionalObject() {
            return null;
        }

        @Override
        public String getEffectiveOptionalEntityName() {
            return null;
        }

        @Override
        public Serializable getEffectiveOptionalId() {
            return null;
        }

        @Override
        public boolean shouldReturnProxies() {
            return true;
        }
    };
    final JdbcValuesSourceProcessingStateStandardImpl jdbcValuesSourceProcessingState = new JdbcValuesSourceProcessingStateStandardImpl(executionContext, processingOptions, executionContext::registerLoadingEntityEntry);
    try {
        final RowProcessingStateStandardImpl rowProcessingState = new RowProcessingStateStandardImpl(jdbcValuesSourceProcessingState, executionContext, rowReader, jdbcValues);
        final List results = new ArrayList<>();
        while (rowProcessingState.next()) {
            results.add(rowReader.readRow(rowProcessingState, processingOptions));
            rowProcessingState.finishRowProcessing();
        }
        return results;
    } finally // catch (SQLException e) {
    // throw context.getSession().getExceptionConverter().convert( e, "Error processing return rows" );
    // }
    {
        rowReader.finishUp(jdbcValuesSourceProcessingState);
        jdbcValuesSourceProcessingState.finishUp();
        jdbcValues.finishUp(this.context.getSession());
    }
}
Also used : ProcedureParameter(org.hibernate.query.procedure.ProcedureParameter) RowReader(org.hibernate.sql.results.spi.RowReader) JdbcValuesSourceProcessingOptions(org.hibernate.sql.results.jdbc.spi.JdbcValuesSourceProcessingOptions) JdbcValues(org.hibernate.sql.results.jdbc.spi.JdbcValues) CallbackImpl(org.hibernate.sql.exec.internal.CallbackImpl) ArrayList(java.util.ArrayList) JdbcValuesResultSetImpl(org.hibernate.sql.results.jdbc.internal.JdbcValuesResultSetImpl) JavaTypeRegistry(org.hibernate.type.descriptor.java.spi.JavaTypeRegistry) ExecutionContext(org.hibernate.sql.exec.spi.ExecutionContext) Callback(org.hibernate.sql.exec.spi.Callback) ResultSetMapping(org.hibernate.query.results.ResultSetMapping) DirectResultSetAccess(org.hibernate.sql.results.jdbc.internal.DirectResultSetAccess) JdbcValuesSourceProcessingStateStandardImpl(org.hibernate.sql.results.jdbc.internal.JdbcValuesSourceProcessingStateStandardImpl) QueryOptionsAdapter(org.hibernate.query.spi.QueryOptionsAdapter) NotYetImplementedFor6Exception(org.hibernate.NotYetImplementedFor6Exception) ArrayList(java.util.ArrayList) List(java.util.List) ProcedureCallImpl(org.hibernate.procedure.internal.ProcedureCallImpl) RowProcessingStateStandardImpl(org.hibernate.sql.results.internal.RowProcessingStateStandardImpl)

Aggregations

JavaTypeRegistry (org.hibernate.type.descriptor.java.spi.JavaTypeRegistry)12 TypeConfiguration (org.hibernate.type.spi.TypeConfiguration)7 SessionFactoryImplementor (org.hibernate.engine.spi.SessionFactoryImplementor)3 EntityPersister (org.hibernate.persister.entity.EntityPersister)3 List (java.util.List)2 NotYetImplementedFor6Exception (org.hibernate.NotYetImplementedFor6Exception)2 Dialect (org.hibernate.dialect.Dialect)2 BasicValue (org.hibernate.mapping.BasicValue)2 CollectionPart (org.hibernate.metamodel.mapping.CollectionPart)2 SelectableMapping (org.hibernate.metamodel.mapping.SelectableMapping)2 JdbcTypeRegistry (org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry)2 BigInteger (java.math.BigInteger)1 OffsetDateTime (java.time.OffsetDateTime)1 ZonedDateTime (java.time.ZonedDateTime)1 ArrayList (java.util.ArrayList)1 SortedMap (java.util.SortedMap)1 SortedSet (java.util.SortedSet)1 MappingException (org.hibernate.MappingException)1 MapKeyJavaType (org.hibernate.annotations.MapKeyJavaType)1 MapKeyJdbcType (org.hibernate.annotations.MapKeyJdbcType)1