even code cleanups around MappingHelper and especially class instantiation

This commit is contained in:
Gavin King 2024-12-30 23:07:57 +01:00
parent eb56902842
commit a283fc982b
15 changed files with 165 additions and 340 deletions

View File

@ -47,10 +47,9 @@ public abstract class AbstractConverterDescriptor implements ConverterDescriptor
}
private AutoApplicableConverterDescriptor resolveAutoApplicableDescriptor(
Class<? extends AttributeConverter> converterClass,
Class<? extends AttributeConverter<?,?>> converterClass,
Boolean forceAutoApply) {
final boolean autoApply;
if ( forceAutoApply != null ) {
// if the caller explicitly specified whether to auto-apply, honor that
autoApply = forceAutoApply;

View File

@ -69,7 +69,6 @@ import org.hibernate.annotations.SortNatural;
import org.hibernate.annotations.SqlFragmentAlias;
import org.hibernate.annotations.Synchronize;
import org.hibernate.boot.model.IdentifierGeneratorDefinition;
import org.hibernate.boot.model.TypeDefinition;
import org.hibernate.boot.models.JpaAnnotations;
import org.hibernate.boot.models.annotations.internal.JoinColumnJpaAnnotation;
import org.hibernate.boot.models.annotations.internal.MapKeyColumnJpaAnnotation;
@ -113,7 +112,6 @@ import org.hibernate.resource.beans.spi.ManagedBean;
import org.hibernate.usertype.CompositeUserType;
import org.hibernate.usertype.UserCollectionType;
import jakarta.persistence.Access;
import jakarta.persistence.AttributeOverride;
import jakarta.persistence.AttributeOverrides;
@ -236,9 +234,6 @@ public abstract class CollectionBinder {
private SortNatural naturalSort;
private SortComparator comparatorSort;
private String explicitType;
private final Map<String,String> explicitTypeParameters = new HashMap<>();
protected CollectionBinder(
Supplier<ManagedBean<? extends UserCollectionType>> customTypeBeanResolver,
boolean isSortedCollection,
@ -855,17 +850,9 @@ public abstract class CollectionBinder {
final CollectionType typeAnnotation =
property.getAnnotationUsage( CollectionType.class,
buildingContext.getMetadataCollector().getSourceModelBuildingContext() );
if ( typeAnnotation != null ) {
binder = createBinderFromCustomTypeAnnotation( property, typeAnnotation, buildingContext );
// todo (6.0) - technically, these should no longer be needed
binder.explicitType = typeAnnotation.type().getName();
for ( Parameter param : typeAnnotation.parameters() ) {
binder.explicitTypeParameters.put( param.name(), param.value() );
}
}
else {
binder = createBinderAutomatically( property, buildingContext );
}
binder = typeAnnotation != null
? createBinderFromCustomTypeAnnotation( property, typeAnnotation, buildingContext )
: createBinderAutomatically( property, buildingContext );
binder.setIsHibernateExtensionMapping( isHibernateExtensionMapping );
return binder;
}
@ -1160,7 +1147,6 @@ public abstract class CollectionBinder {
collection.setMappedByProperty( mappedBy );
checkMapKeyColumn();
bindExplicitTypes();
//set laziness
defineFetchingStrategy();
collection.setMutable( isMutable() );
@ -1222,22 +1208,6 @@ public abstract class CollectionBinder {
collection.setQueryCacheLayout( queryCacheLayout );
}
private void bindExplicitTypes() {
// set explicit type information
final InFlightMetadataCollector metadataCollector = getMetadataCollector();
if ( explicitType != null ) {
final TypeDefinition typeDef = metadataCollector.getTypeDefinition( explicitType );
if ( typeDef == null ) {
collection.setTypeName( explicitType );
collection.setTypeParameters( explicitTypeParameters );
}
else {
collection.setTypeName( typeDef.getTypeImplementorClass().getName() );
collection.setTypeParameters( typeDef.getParameters() );
}
}
}
private void detectMappedByProblem(boolean isMappedBy) {
if ( isMappedBy ) {
if ( property.hasDirectAnnotationUsage( JoinColumn.class )
@ -1751,13 +1721,11 @@ public abstract class CollectionBinder {
}
private void bindFilters(boolean hasAssociationTable) {
property.forEachAnnotationUsage( Filter.class, sourceModelContext(), (usage) -> {
addFilter( hasAssociationTable, usage );
} );
property.forEachAnnotationUsage( Filter.class, sourceModelContext(),
usage -> addFilter( hasAssociationTable, usage ) );
property.forEachAnnotationUsage( FilterJoinTable.class, sourceModelContext(), (usage) -> {
addFilterJoinTable( hasAssociationTable, usage );
} );
property.forEachAnnotationUsage( FilterJoinTable.class, sourceModelContext(),
usage -> addFilterJoinTable( hasAssociationTable, usage ) );
}
private void addFilter(boolean hasAssociationTable, Filter filterAnnotation) {
@ -2510,9 +2478,8 @@ public abstract class CollectionBinder {
}
private void handleCheckConstraints(Table collectionTable) {
property.forEachAnnotationUsage( Check.class, sourceModelContext(), (usage) -> {
addCheckToCollection( collectionTable, usage );
} );
property.forEachAnnotationUsage( Check.class, sourceModelContext(),
usage -> addCheckToCollection( collectionTable, usage ) );
property.forEachAnnotationUsage( jakarta.persistence.JoinTable.class, sourceModelContext(), (usage) -> {
TableBinder.addTableCheck( collectionTable, usage.check() );
TableBinder.addTableComment( collectionTable, usage.comment() );

View File

@ -11,6 +11,7 @@ import org.hibernate.engine.jdbc.spi.JdbcServices;
import org.hibernate.metamodel.spi.ImplicitDiscriminatorStrategy;
import org.hibernate.type.AnyType;
import org.hibernate.type.MappingContext;
import org.hibernate.type.MetaType;
import org.hibernate.type.Type;
import java.util.HashMap;
@ -46,7 +47,6 @@ public class Any extends SimpleValue {
public Any(MetadataBuildingContext buildingContext, Table table, boolean annotations) {
super( buildingContext, table );
if ( ! annotations ) {
metaMapping = new MetaValue( this::applySelectableToSuper, buildingContext, table );
metaMapping.setTypeName( "string" );
@ -56,7 +56,6 @@ public class Any extends SimpleValue {
metaMapping = null;
keyMapping = null;
}
}
public Any(Any original) {
@ -85,15 +84,13 @@ public class Any extends SimpleValue {
}
public void addSelectable(Selectable selectable) {
if ( selectable == null ) {
return;
}
if ( selectable instanceof Column ) {
super.justAddColumn( (Column) selectable );
}
else {
super.justAddFormula( (Formula) selectable );
if ( selectable != null ) {
if ( selectable instanceof Column column ) {
super.justAddColumn( column );
}
else if ( selectable instanceof Formula formula ) {
super.justAddFormula( formula );
}
}
}
@ -134,32 +131,12 @@ public class Any extends SimpleValue {
@Override
public AnyType getType() throws MappingException {
if ( resolvedType == null ) {
final Type discriminatorType;
if ( discriminatorDescriptor != null ) {
discriminatorType = discriminatorDescriptor.getType();
}
else {
discriminatorType = metaMapping.getType();
}
final Type identifierType;
if ( keyDescriptor != null ) {
identifierType = keyDescriptor.getType();
}
else {
identifierType = keyMapping.getType();
}
resolvedType = MappingHelper.anyMapping(
discriminatorType,
identifierType,
metaValueToEntityNameMap,
implicitValueStrategy,
isLazy(),
getBuildingContext()
);
final Type discriminatorType =
discriminatorDescriptor != null ? discriminatorDescriptor.getType() : metaMapping.getType();
final Type identifierType = keyDescriptor != null ? keyDescriptor.getType() : keyMapping.getType();
final MetaType metaType = new MetaType( discriminatorType, implicitValueStrategy, metaValueToEntityNameMap );
resolvedType = new AnyType( getTypeConfiguration(), metaType, identifierType, isLazy() );
}
return resolvedType;
}
@ -181,7 +158,6 @@ public class Any extends SimpleValue {
private void applySelectableLocally(Selectable selectable) {
// note: adding column to meta or key mapping ultimately calls back into `#applySelectableToSuper`
// to add the column to the ANY super.
if ( discriminatorDescriptor == null && getColumnSpan() == 0 ) {
if ( selectable instanceof Column ) {
metaMapping.addColumn( (Column) selectable );
@ -214,9 +190,7 @@ public class Any extends SimpleValue {
return metaValueToEntityNameMap;
}
@SuppressWarnings( "rawtypes" )
public void setMetaValues(Map metaValueToEntityNameMap) {
//noinspection unchecked
public void setMetaValues(Map<Object,String> metaValueToEntityNameMap) {
this.metaValueToEntityNameMap = metaValueToEntityNameMap;
}
@ -242,8 +216,7 @@ public class Any extends SimpleValue {
}
@Override
public void setTypeUsingReflection(String className, String propertyName)
throws MappingException {
public void setTypeUsingReflection(String className, String propertyName) {
}
@Override
@ -258,10 +231,10 @@ public class Any extends SimpleValue {
public boolean isSame(Any other) {
return super.isSame( other )
&& Objects.equals( getTypeNameOrNull( keyMapping ), getTypeNameOrNull( other.keyMapping ) )
&& Objects.equals( getTypeNameOrNull( metaMapping ), getTypeNameOrNull( other.metaMapping ) )
&& Objects.equals( metaValueToEntityNameMap, other.metaValueToEntityNameMap )
&& lazy == other.lazy;
&& Objects.equals( getTypeNameOrNull( keyMapping ), getTypeNameOrNull( other.keyMapping ) )
&& Objects.equals( getTypeNameOrNull( metaMapping ), getTypeNameOrNull( other.metaMapping ) )
&& Objects.equals( metaValueToEntityNameMap, other.metaValueToEntityNameMap )
&& lazy == other.lazy;
}
private String getTypeNameOrNull(SimpleValue simpleValue) {
@ -277,18 +250,17 @@ public class Any extends SimpleValue {
}
private static String columnName(Column column, MetadataBuildingContext buildingContext) {
final JdbcServices jdbcServices = buildingContext
.getBootstrapContext()
.getServiceRegistry()
.requireService( JdbcServices.class );
final JdbcServices jdbcServices =
buildingContext.getBootstrapContext().getServiceRegistry()
.requireService( JdbcServices.class );
return column.getQuotedName( jdbcServices.getDialect() );
}
public void setDiscriminator(BasicValue discriminatorDescriptor) {
this.discriminatorDescriptor = discriminatorDescriptor;
if ( discriminatorDescriptor.getColumn() instanceof Column ) {
if ( discriminatorDescriptor.getColumn() instanceof Column column ) {
justAddColumn(
(Column) discriminatorDescriptor.getColumn(),
column,
discriminatorDescriptor.isColumnInsertable( 0 ),
discriminatorDescriptor.isColumnUpdateable( 0 )
);
@ -300,16 +272,14 @@ public class Any extends SimpleValue {
public void setDiscriminatorValueMappings(Map<Object, Class<?>> discriminatorValueMappings) {
metaValueToEntityNameMap = new HashMap<>();
discriminatorValueMappings.forEach( (value, entity) -> {
metaValueToEntityNameMap.put( value, entity.getName() );
} );
discriminatorValueMappings.forEach( (value, entity) -> metaValueToEntityNameMap.put( value, entity.getName() ) );
}
public void setKey(BasicValue keyDescriptor) {
this.keyDescriptor = keyDescriptor;
if ( keyDescriptor.getColumn() instanceof Column ) {
if ( keyDescriptor.getColumn() instanceof Column column ) {
justAddColumn(
(Column) keyDescriptor.getColumn(),
column,
keyDescriptor.isColumnInsertable( 0 ),
keyDescriptor.isColumnUpdateable( 0 )
);
@ -379,10 +349,8 @@ public class Any extends SimpleValue {
if ( columnName != null ) {
throw new MappingException( "ANY discriminator already contained column" );
}
super.addColumn( column );
this.columnName = columnName( column, getBuildingContext() );
selectableConsumer.accept( column );
column.setValue( this );
}
@ -392,10 +360,8 @@ public class Any extends SimpleValue {
if ( columnName != null ) {
throw new MappingException( "ANY discriminator already contained column" );
}
super.addColumn( column, isInsertable, isUpdatable );
this.columnName = columnName( column, getBuildingContext() );
selectableConsumer.accept( column );
column.setValue( this );
}
@ -405,10 +371,8 @@ public class Any extends SimpleValue {
if ( columnName != null ) {
throw new MappingException( "ANY discriminator already contained column" );
}
super.addFormula( formula );
columnName = formula.getFormula();
selectableConsumer.accept( formula );
}
@ -468,21 +432,18 @@ public class Any extends SimpleValue {
@Override
public void addColumn(Column column) {
super.addColumn( column );
selectableConsumer.accept( column );
}
@Override
public void addColumn(Column column, boolean isInsertable, boolean isUpdatable) {
super.addColumn( column, isInsertable, isUpdatable );
selectableConsumer.accept( column );
}
@Override
public void addFormula(Formula formula) {
super.addFormula( formula );
selectableConsumer.accept( formula );
}
}

View File

@ -7,16 +7,18 @@ package org.hibernate.mapping;
import java.util.function.Supplier;
import org.hibernate.MappingException;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.registry.classloading.spi.ClassLoadingException;
import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.resource.beans.spi.ManagedBean;
import org.hibernate.type.ArrayType;
import org.hibernate.type.BasicType;
import org.hibernate.type.CollectionType;
import org.hibernate.type.descriptor.java.JavaType;
import org.hibernate.type.descriptor.java.spi.PrimitiveJavaType;
import org.hibernate.usertype.UserCollectionType;
import static org.hibernate.mapping.MappingHelper.classForName;
/**
* An array mapping has a primary key consisting of the key columns + index column.
*
@ -47,16 +49,14 @@ public class Array extends List {
if ( elementClassName == null ) {
final org.hibernate.type.Type elementType = getElement().getType();
if ( isPrimitiveArray() ) {
return ( (PrimitiveJavaType<?>) ( (BasicType<?>) elementType ).getJavaTypeDescriptor() ).getPrimitiveClass();
final JavaType<?> javaTypeDescriptor = ((BasicType<?>) elementType).getJavaTypeDescriptor();
return ( (PrimitiveJavaType<?>) javaTypeDescriptor ).getPrimitiveClass();
}
return elementType.getReturnedClass();
}
else {
try {
return getMetadata().getMetadataBuildingOptions()
.getServiceRegistry()
.requireService( ClassLoaderService.class )
.classForName( elementClassName );
return classForName( elementClassName, getMetadata() );
}
catch (ClassLoadingException e) {
throw new MappingException( e );

View File

@ -899,7 +899,6 @@ public class BasicValue extends SimpleValue implements JdbcTypeIndicators, Resol
return resolution;
}
// see if the name is a UserType or BasicType implementor class name
final ClassLoaderService classLoaderService = serviceRegistry.requireService( ClassLoaderService.class );
try {
@ -907,12 +906,8 @@ public class BasicValue extends SimpleValue implements JdbcTypeIndicators, Resol
// if there are no local config params, register an implicit TypeDefinition for this custom type .
// later uses may find it and re-use its cacheable reference...
if ( isEmpty( localTypeParams ) ) {
final TypeDefinition implicitDefinition = new TypeDefinition(
name,
typeNamedClass,
null,
null
);
final TypeDefinition implicitDefinition =
new TypeDefinition( name, typeNamedClass, null, null );
context.getTypeDefinitionRegistry().register( implicitDefinition );
return implicitDefinition.resolve(
localTypeParams,

View File

@ -16,7 +16,6 @@ import java.util.function.Supplier;
import org.hibernate.FetchMode;
import org.hibernate.MappingException;
import org.hibernate.annotations.CacheLayout;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.collection.internal.CustomCollectionTypeSemantics;
@ -24,6 +23,7 @@ import org.hibernate.collection.spi.CollectionSemantics;
import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.internal.FilterConfiguration;
import org.hibernate.internal.util.PropertiesHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.jdbc.Expectation;
import org.hibernate.resource.beans.spi.ManagedBean;
@ -36,6 +36,8 @@ import org.hibernate.usertype.UserCollectionType;
import static org.hibernate.internal.util.collections.ArrayHelper.EMPTY_BOOLEAN_ARRAY;
import static org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle.expectationConstructor;
import static org.hibernate.mapping.MappingHelper.classForName;
import static org.hibernate.mapping.MappingHelper.createUserTypeBean;
/**
* A mapping model object representing a collection. Subclasses specialize to particular kinds of collection.
@ -228,11 +230,11 @@ public abstract class Collection implements Fetchable, Value, Filterable, SoftDe
public Comparator<?> getComparator() {
if ( comparator == null && comparatorClassName != null ) {
@SuppressWarnings("rawtypes")
final Class<? extends Comparator> clazz =
classForName( Comparator.class, comparatorClassName, getMetadata() );
try {
final ClassLoaderService classLoaderService = getMetadata().getMetadataBuildingOptions()
.getServiceRegistry()
.requireService( ClassLoaderService.class );
setComparator( (Comparator<?>) classLoaderService.classForName( comparatorClassName ).getConstructor().newInstance() );
comparator = clazz.getConstructor().newInstance();
}
catch (Exception e) {
throw new MappingException(
@ -469,23 +471,18 @@ public abstract class Collection implements Fetchable, Value, Filterable, SoftDe
collectionType = cachedCollectionType;
}
else if ( customTypeBeanResolver != null ) {
collectionType = new CustomCollectionType(
customTypeBeanResolver.get(),
role,
referencedPropertyName
);
collectionType = new CustomCollectionType( customTypeBeanResolver.get(), role, referencedPropertyName );
}
else if ( typeName == null ) {
collectionType = getDefaultCollectionType();
}
else {
collectionType = MappingHelper.customCollection(
typeName,
typeParameters,
role,
referencedPropertyName,
getMetadata()
);
final MetadataImplementor metadata = getMetadata();
final Class<? extends UserCollectionType> clazz =
classForName( UserCollectionType.class, typeName, metadata );
final ManagedBean<? extends UserCollectionType> userTypeBean =
createUserTypeBean( role, clazz, PropertiesHelper.map( typeParameters ), metadata );
collectionType = new CustomCollectionType( userTypeBean, role, referencedPropertyName );
}
return collectionType;
}
@ -542,14 +539,14 @@ public abstract class Collection implements Fetchable, Value, Filterable, SoftDe
public boolean isSame(Collection other) {
return this == other || isSame( key, other.key )
&& isSame( element, other.element )
&& Objects.equals( collectionTable, other.collectionTable )
&& Objects.equals( where, other.where )
&& Objects.equals( manyToManyWhere, other.manyToManyWhere )
&& Objects.equals( referencedPropertyName, other.referencedPropertyName )
&& Objects.equals( mappedByProperty, other.mappedByProperty )
&& Objects.equals( typeName, other.typeName )
&& Objects.equals( typeParameters, other.typeParameters );
&& isSame( element, other.element )
&& Objects.equals( collectionTable, other.collectionTable )
&& Objects.equals( where, other.where )
&& Objects.equals( manyToManyWhere, other.manyToManyWhere )
&& Objects.equals( referencedPropertyName, other.referencedPropertyName )
&& Objects.equals( mappedByProperty, other.mappedByProperty )
&& Objects.equals( typeName, other.typeName )
&& Objects.equals( typeParameters, other.typeParameters );
}
private void createForeignKeys() throws MappingException {

View File

@ -21,7 +21,6 @@ import org.hibernate.boot.model.relational.ExportableProducer;
import org.hibernate.boot.model.relational.QualifiedName;
import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.boot.model.source.internal.hbm.MappingDocument;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.registry.classloading.spi.ClassLoadingException;
import org.hibernate.boot.spi.BootstrapContext;
import org.hibernate.boot.spi.MetadataBuildingContext;
@ -60,6 +59,7 @@ import static java.util.stream.Collectors.toList;
import static org.hibernate.generator.EventType.INSERT;
import static org.hibernate.internal.util.StringHelper.qualify;
import static org.hibernate.mapping.MappingHelper.checkPropertyColumnDuplication;
import static org.hibernate.mapping.MappingHelper.classForName;
import static org.hibernate.metamodel.mapping.EntityDiscriminatorMapping.DISCRIMINATOR_ROLE_NAME;
/**
@ -333,24 +333,20 @@ public class Component extends SimpleValue implements MetaAttributable, Sortable
}
public Class<?> getComponentClass() throws MappingException {
Class<?> result = componentClass;
if ( result == null ) {
if ( componentClass == null ) {
if ( componentClassName == null ) {
return null;
}
else {
try {
result = componentClass = getMetadata()
.getMetadataBuildingOptions()
.getServiceRegistry()
.requireService( ClassLoaderService.class ).classForName( componentClassName );
componentClass = classForName( componentClassName, getMetadata() );
}
catch (ClassLoadingException e) {
throw new MappingException( "component class not found: " + componentClassName, e );
throw new MappingException( "Embeddable class not found: " + componentClassName, e );
}
}
}
return result;
return componentClass;
}
public PersistentClass getOwner() {
@ -389,12 +385,13 @@ public class Component extends SimpleValue implements MetaAttributable, Sortable
private CompositeUserType<?> createCompositeUserType(Component component) {
final BootstrapContext bootstrapContext = getBuildingContext().getBootstrapContext();
final Class<CompositeUserType<?>> customTypeClass =
bootstrapContext.getClassLoaderAccess().classForName( component.getTypeName() );
@SuppressWarnings("rawtypes")
final Class<? extends CompositeUserType> clazz =
classForName( CompositeUserType.class, component.getTypeName(), getMetadataCollector() );
return !getBuildingContext().getBuildingOptions().isAllowExtensionsInCdi()
? FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( customTypeClass )
? FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( clazz )
: bootstrapContext.getServiceRegistry().requireService( ManagedBeanRegistry.class )
.getBean( customTypeClass ).getBeanInstance();
.getBean( clazz ).getBeanInstance();
}
@Override

View File

@ -10,8 +10,7 @@ import java.util.Map;
import org.hibernate.MappingException;
import org.hibernate.annotations.NotFoundAction;
import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
import org.hibernate.type.ManyToOneType;
/**
* A mapping model object representing a {@linkplain jakarta.persistence.ManyToOne many-to-one association}.
@ -22,7 +21,7 @@ public class ManyToOne extends ToOne {
private boolean isLogicalOneToOne;
private NotFoundAction notFoundAction;
private transient Type resolvedType;
private transient ManyToOneType resolvedType;
public ManyToOne(MetadataBuildingContext buildingContext, Table table) {
super( buildingContext, table );
@ -39,21 +38,20 @@ public class ManyToOne extends ToOne {
return new ManyToOne( this );
}
public Type getType() throws MappingException {
public ManyToOneType getType() throws MappingException {
if ( resolvedType == null ) {
resolvedType = MappingHelper.manyToOne(
resolvedType = new ManyToOneType(
getTypeConfiguration(),
getReferencedEntityName(),
isReferenceToPrimaryKey(),
getReferencedPropertyName(),
getPropertyName(),
isLogicalOneToOne(),
isLazy(),
isUnwrapProxy(),
isIgnoreNotFound(),
getBuildingContext()
isLogicalOneToOne()
);
}
return resolvedType;
}
@ -101,7 +99,7 @@ public class ManyToOne extends ToOne {
final ForeignKey foreignKey = getTable().createForeignKey(
getForeignKeyName(),
getConstraintColumns(),
( (EntityType) getType() ).getAssociatedEntityName(),
getType().getAssociatedEntityName(),
getForeignKeyDefinition(),
getForeignKeyOptions(),
new ArrayList<>( property.getColumns() )

View File

@ -15,24 +15,13 @@ import org.hibernate.boot.model.internal.DelayedParameterizedTypeBean;
import org.hibernate.boot.registry.classloading.spi.ClassLoaderService;
import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.metamodel.spi.ImplicitDiscriminatorStrategy;
import org.hibernate.resource.beans.internal.FallbackBeanInstanceProducer;
import org.hibernate.resource.beans.spi.ManagedBean;
import org.hibernate.resource.beans.spi.ManagedBeanRegistry;
import org.hibernate.resource.beans.spi.ProvidedInstanceManagedBeanImpl;
import org.hibernate.type.AnyType;
import org.hibernate.type.CollectionType;
import org.hibernate.type.CustomCollectionType;
import org.hibernate.type.ForeignKeyDirection;
import org.hibernate.type.ManyToOneType;
import org.hibernate.type.MetaType;
import org.hibernate.type.OneToOneType;
import org.hibernate.type.SpecialOneToOneType;
import org.hibernate.type.Type;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserCollectionType;
import static org.hibernate.internal.util.PropertiesHelper.map;
import static org.hibernate.internal.util.collections.CollectionHelper.isNotEmpty;
/**
@ -45,18 +34,7 @@ public final class MappingHelper {
private MappingHelper() {
}
public static CollectionType customCollection(
String typeName,
Properties typeParameters,
String role,
String propertyRef,
MetadataImplementor metadata) {
final ManagedBean<? extends UserCollectionType> userTypeBean =
createUserTypeBean( role, classForName( typeName, metadata ), map( typeParameters ), metadata );
return new CustomCollectionType( userTypeBean, role, propertyRef );
}
private static ManagedBean<? extends UserCollectionType> createUserTypeBean(
public static ManagedBean<? extends UserCollectionType> createUserTypeBean(
String role,
Class<? extends UserCollectionType> userCollectionTypeClass,
Map<String, ?> parameters,
@ -100,18 +78,12 @@ public final class MappingHelper {
return managedBean;
}
private static Class<UserCollectionType> classForName(String typeName, MetadataImplementor metadata) {
return metadata.getMetadataBuildingOptions().getServiceRegistry()
.requireService( ClassLoaderService.class )
.classForName( typeName );
}
private static ManagedBeanRegistry getManagedBeanRegistry(MetadataImplementor metadata) {
return metadata.getMetadataBuildingOptions().getServiceRegistry()
.requireService( ManagedBeanRegistry.class );
}
public static void throwIgnoredCollectionTypeParameters(String role, Class<?> implementation) {
private static void throwIgnoredCollectionTypeParameters(String role, Class<?> implementation) {
throw new MappingException( "'@CollectionType' [" + role + "] specified parameters, but the implementation '"
+ implementation.getName() + "' does not implement 'ParameterizedType' which is used to inject them" );
}
@ -126,90 +98,6 @@ public final class MappingHelper {
}
}
public static AnyType anyMapping(
Type discriminatorType,
Type identifierType,
Map<Object, String> explicitValeMappings,
ImplicitDiscriminatorStrategy implicitValueStrategy,
boolean lazy,
MetadataBuildingContext buildingContext) {
final MetaType metaType = new MetaType( discriminatorType, implicitValueStrategy, explicitValeMappings );
return new AnyType( buildingContext.getBootstrapContext().getTypeConfiguration(), metaType, identifierType, lazy );
}
public static ManyToOneType manyToOne(
String referencedEntityName,
boolean referenceToPrimaryKey,
String referencedPropertyName,
String propertyName,
boolean isLogicalOneToOne,
boolean lazy,
boolean unwrapProxy,
boolean ignoreNotFound,
MetadataBuildingContext buildingContext) {
return new ManyToOneType(
buildingContext.getBootstrapContext().getTypeConfiguration(),
referencedEntityName,
referenceToPrimaryKey,
referencedPropertyName,
propertyName,
lazy,
unwrapProxy,
ignoreNotFound,
isLogicalOneToOne
);
}
public static SpecialOneToOneType specialOneToOne(
String referencedEntityName,
ForeignKeyDirection foreignKeyType,
boolean referenceToPrimaryKey,
String referencedPropertyName,
boolean lazy,
boolean unwrapProxy,
String owningEntityName,
String owningEntityPropertyName,
boolean constrained,
MetadataBuildingContext buildingContext) {
return new SpecialOneToOneType(
buildingContext.getBootstrapContext().getTypeConfiguration(),
referencedEntityName,
foreignKeyType,
referenceToPrimaryKey,
referencedPropertyName,
lazy,
unwrapProxy,
owningEntityName,
owningEntityPropertyName,
constrained
);
}
public static OneToOneType oneToOne(
String referencedEntityName,
ForeignKeyDirection foreignKeyType,
boolean referenceToPrimaryKey,
String referencedPropertyName,
boolean lazy,
boolean unwrapProxy,
String owningEntityName,
String owningEntityPropertyName,
boolean constrained,
MetadataBuildingContext buildingContext) {
return new OneToOneType(
buildingContext.getBootstrapContext().getTypeConfiguration(),
referencedEntityName,
foreignKeyType,
referenceToPrimaryKey,
referencedPropertyName,
lazy,
unwrapProxy,
owningEntityName,
owningEntityPropertyName,
constrained
);
}
private static ManagedBean<UserCollectionType> createLocalUserTypeBean(
String role,
Class<? extends UserCollectionType> implementation,
@ -240,4 +128,21 @@ public final class MappingHelper {
}
}
}
static Class<?> classForName(String typeName, MetadataImplementor metadata) {
return metadata.getMetadataBuildingOptions().getServiceRegistry()
.requireService( ClassLoaderService.class )
.classForName( typeName );
}
static <T> Class<? extends T> classForName(Class<T> supertype, String typeName, MetadataImplementor metadata) {
final Class<?> clazz = classForName( typeName, metadata );
if ( supertype.isAssignableFrom( clazz ) ) {
//noinspection unchecked
return (Class<? extends T>) clazz;
}
else {
throw new MappingException( "Class '" + typeName + "' does not implement '" + supertype.getName() + "'" );
}
}
}

View File

@ -13,7 +13,7 @@ import org.hibernate.annotations.NotFoundAction;
import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.internal.util.collections.ArrayHelper;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.type.EntityType;
import org.hibernate.type.ManyToOneType;
import org.hibernate.type.Type;
import org.hibernate.type.MappingContext;
@ -58,20 +58,6 @@ public class OneToMany implements Value {
return buildingContext.getBuildingOptions().getServiceRegistry();
}
private EntityType getEntityType() {
return MappingHelper.manyToOne(
getReferencedEntityName(),
true,
null,
null,
false,
false,
isIgnoreNotFound(),
false,
buildingContext
);
}
public PersistentClass getAssociatedClass() {
return associatedClass;
}
@ -121,7 +107,17 @@ public class OneToMany implements Value {
@Override
public Type getType() {
return getEntityType();
return new ManyToOneType(
buildingContext.getBootstrapContext().getTypeConfiguration(),
getReferencedEntityName(),
true,
null,
null,
false,
isIgnoreNotFound(),
false,
false
);
}
@Override

View File

@ -10,7 +10,8 @@ import java.util.Objects;
import org.hibernate.MappingException;
import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.type.ForeignKeyDirection;
import org.hibernate.type.Type;
import org.hibernate.type.OneToOneType;
import org.hibernate.type.SpecialOneToOneType;
/**
* A mapping model object representing a {@linkplain jakarta.persistence.OneToOne many-to-one association}.
@ -59,9 +60,10 @@ public class OneToOne extends ToOne {
return entityName;
}
public Type getType() throws MappingException {
public OneToOneType getType() throws MappingException {
if ( getColumnSpan()>0 ) {
return MappingHelper.specialOneToOne(
return new SpecialOneToOneType(
getTypeConfiguration(),
getReferencedEntityName(),
getForeignKeyType(),
isReferenceToPrimaryKey(),
@ -70,12 +72,12 @@ public class OneToOne extends ToOne {
isUnwrapProxy(),
getEntityName(),
getPropertyName(),
isConstrained(),
getBuildingContext()
isConstrained()
);
}
else {
return MappingHelper.oneToOne(
return new OneToOneType(
getTypeConfiguration(),
getReferencedEntityName(),
getForeignKeyType(),
isReferenceToPrimaryKey(),
@ -84,8 +86,7 @@ public class OneToOne extends ToOne {
isUnwrapProxy(),
entityName,
propertyName,
isConstrained(),
getBuildingContext()
isConstrained()
);
}
}
@ -99,17 +100,17 @@ public class OneToOne extends ToOne {
@Override
public List<Selectable> getVirtualSelectables() {
List<Selectable> selectables = super.getVirtualSelectables();
final List<Selectable> selectables = super.getVirtualSelectables();
if ( selectables.isEmpty() ) {
selectables = identifier.getSelectables();
return identifier.getSelectables();
}
return selectables;
}
public List<Column> getConstraintColumns() {
List<Column> columns = super.getColumns();
final List<Column> columns = super.getColumns();
if ( columns.isEmpty() ) {
columns = identifier.getColumns();
return identifier.getColumns();
}
return columns;
}
@ -177,11 +178,11 @@ public class OneToOne extends ToOne {
public boolean isSame(OneToOne other) {
return super.isSame( other )
&& Objects.equals( foreignKeyType, other.foreignKeyType )
&& isSame( identifier, other.identifier )
&& Objects.equals( propertyName, other.propertyName )
&& Objects.equals( entityName, other.entityName )
&& constrained == other.constrained;
&& Objects.equals( foreignKeyType, other.foreignKeyType )
&& isSame( identifier, other.identifier )
&& Objects.equals( propertyName, other.propertyName )
&& Objects.equals( entityName, other.entityName )
&& constrained == other.constrained;
}
public String getMappedByProperty() {

View File

@ -62,6 +62,7 @@ import static org.hibernate.boot.model.internal.GeneratorBinder.ASSIGNED_IDENTIF
import static org.hibernate.boot.model.relational.internal.SqlStringGenerationContextImpl.fromExplicit;
import static org.hibernate.internal.util.ReflectHelper.reflectedPropertyClass;
import static org.hibernate.internal.util.collections.ArrayHelper.toBooleanArray;
import static org.hibernate.mapping.MappingHelper.classForName;
/**
* A mapping model object that represents any value that maps to columns.
@ -282,9 +283,13 @@ public abstract class SimpleValue implements KeyValue {
void setAttributeConverterDescriptor(String typeName) {
final String converterClassName = typeName.substring( TYPE_NAME_PREFIX.length() );
this.attributeConverterDescriptor =
new ClassBasedConverterDescriptor( classLoaderService().classForName( converterClassName ),
false, getBuildingContext().getBootstrapContext().getClassmateContext() );
@SuppressWarnings("unchecked")
final Class<? extends AttributeConverter<?,?>> clazz =
(Class<? extends AttributeConverter<?,?>>)
classForName( AttributeConverter.class, converterClassName, getMetadata() );
attributeConverterDescriptor =
new ClassBasedConverterDescriptor( clazz, false,
getBuildingContext().getBootstrapContext().getClassmateContext() );
}
ClassLoaderService classLoaderService() {

View File

@ -72,7 +72,6 @@ public interface Value extends Serializable {
Type getType() throws MappingException;
/**
* @deprecated use {@link #getSelectableType(MappingContext, int)}
*/

View File

@ -7,7 +7,6 @@ package org.hibernate.query.internal;
import java.lang.reflect.ParameterizedType;
import java.util.function.Consumer;
import org.hibernate.boot.model.convert.internal.ConverterHelper;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.metamodel.mapping.BasicValuedMapping;
import org.hibernate.query.named.ResultMementoBasic;
@ -27,6 +26,8 @@ import org.hibernate.usertype.UserType;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.ColumnResult;
import static org.hibernate.boot.model.convert.internal.ConverterHelper.extractAttributeConverterParameterizedType;
/**
* Implementation of {@link ResultMementoBasic} for scalar (basic) results.
* <p>
@ -80,16 +81,17 @@ public class ResultMementoBasicStandard implements ResultMementoBasic {
builder = new CompleteResultBuilderBasicValuedStandard( explicitColumnName, null, null );
}
else if ( AttributeConverter.class.isAssignableFrom( definedType ) ) {
@SuppressWarnings("unchecked")
final Class<? extends AttributeConverter<?, ?>> converterClass =
(Class<? extends AttributeConverter<?, ?>>) definedType;
final ManagedBean<? extends AttributeConverter<?,?>> converterBean = sessionFactory.getServiceRegistry()
.requireService( ManagedBeanRegistry.class )
.getBean( converterClass );
final JavaType<? extends AttributeConverter<?,?>> converterJtd = typeConfiguration
.getJavaTypeRegistry()
.getDescriptor( converterClass );
final ManagedBean<? extends AttributeConverter<?,?>> converterBean =
sessionFactory.getServiceRegistry().requireService( ManagedBeanRegistry.class )
.getBean( converterClass );
final JavaType<? extends AttributeConverter<?,?>> converterJtd =
typeConfiguration.getJavaTypeRegistry().getDescriptor( converterClass );
final ParameterizedType parameterizedType = ConverterHelper.extractAttributeConverterParameterizedType( converterBean.getBeanClass() );
final ParameterizedType parameterizedType =
extractAttributeConverterParameterizedType( converterBean.getBeanClass() );
builder = new CompleteResultBuilderBasicValuedConverted(
explicitColumnName,
@ -104,7 +106,8 @@ public class ResultMementoBasicStandard implements ResultMementoBasic {
final JavaType<?> explicitJavaType;
// see if this is a registered BasicType...
final BasicType<Object> registeredBasicType = typeConfiguration.getBasicTypeRegistry().getRegisteredType( definedType.getName() );
final BasicType<Object> registeredBasicType =
typeConfiguration.getBasicTypeRegistry().getRegisteredType( definedType.getName() );
if ( registeredBasicType != null ) {
explicitType = registeredBasicType;
explicitJavaType = registeredBasicType.getJavaTypeDescriptor();

View File

@ -7,7 +7,6 @@ package org.hibernate.type;
import java.util.Iterator;
import java.util.Map;
import org.hibernate.HibernateException;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
@ -34,7 +33,6 @@ public class CustomCollectionType extends CollectionType {
String role,
String foreignKeyPropertyName) {
super(role, foreignKeyPropertyName );
userType = userTypeBean.getBeanInstance();
customLogging = userType instanceof LoggableUserType;
}
@ -50,8 +48,7 @@ public class CustomCollectionType extends CollectionType {
}
@Override
public PersistentCollection<?> instantiate(SharedSessionContractImplementor session, CollectionPersister persister, Object key)
throws HibernateException {
public PersistentCollection<?> instantiate(SharedSessionContractImplementor session, CollectionPersister persister, Object key) {
return userType.instantiate( session, persister );
}
@ -72,7 +69,7 @@ public class CustomCollectionType extends CollectionType {
@Override
public boolean contains(Object collection, Object entity, SharedSessionContractImplementor session) {
return userType.contains(collection, entity);
return userType.contains( collection, entity );
}
@Override
@ -81,14 +78,19 @@ public class CustomCollectionType extends CollectionType {
}
@Override
public Object replaceElements(Object original, Object target, Object owner, Map copyCache, SharedSessionContractImplementor session)
throws HibernateException {
CollectionPersister cp = session.getFactory().getRuntimeMetamodels().getMappingMetamodel().getCollectionDescriptor( getRole() );
return userType.replaceElements(original, target, cp, owner, copyCache, session);
public Object replaceElements(
Object original,
Object target,
Object owner,
Map<Object,Object> copyCache,
SharedSessionContractImplementor session) {
final CollectionPersister collectionDescriptor =
session.getFactory().getMappingMetamodel().getCollectionDescriptor( getRole() );
return userType.replaceElements( original, target, collectionDescriptor, owner, copyCache, session );
}
@Override
protected String renderLoggableString(Object value, SessionFactoryImplementor factory) throws HibernateException {
protected String renderLoggableString(Object value, SessionFactoryImplementor factory) {
if ( customLogging ) {
return ( (LoggableUserType) userType ).toLoggableString( value, factory );
}