From 84196c4b6c4e177d6b0c40701ea9b47e26c722c7 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 24 Aug 2025 21:21:41 +1000 Subject: [PATCH 1/5] fix javadoc code fragment in @PropertyRef --- .../hibernate/annotations/PropertyRef.java | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/annotations/PropertyRef.java b/hibernate-core/src/main/java/org/hibernate/annotations/PropertyRef.java index 58fe4a2c35df..eb496ee97fe3 100644 --- a/hibernate-core/src/main/java/org/hibernate/annotations/PropertyRef.java +++ b/hibernate-core/src/main/java/org/hibernate/annotations/PropertyRef.java @@ -18,40 +18,40 @@ * Allows to specify the target of a foreign-key using a "target attribute" as opposed to * join column(s). E.g. *
- *     {@code @Entity}
+ *     @Entity
  *     class Employee {
- *         {@code @Id}
+ *         @Id
  *         Integer id;
- *         {@code @Column(name="ssn") }
+ *         @Column(name="ssn")
  *         String socialSecurityNumber;
  *     }
- *     {@code @Entity}
+ *     @Entity
  *     class TaxDetails {
- *         {@code @Id Integer id;}
- *         {@code @OneToOne}
- *         {@code @PropertyRef("socialSecurityNumber")}
+ *         @Id Integer id;
+ *         @OneToOne
+ *         @PropertyRef("socialSecurityNumber")
  *         Employee employee;
  *     }
  * 
* Generally more useful with composite keys: *
- *     {@code @Embeddable}
+ *     @Embeddable
  *     class Name {
  *         String first;
  *         String last;
  *     }
- *     {@code @Entity}
+ *     @Entity
  *     class Employee {
- *         {@code @Id}
+ *         @Id
  *         Integer id;
- *         {@code @Embedded}
+ *         @Embedded
  *         Name name;
  *     }
- *     {@code @Entity}
+ *     @Entity
  *     class TaxDetails {
- *         {@code @Id Integer id;}
- *         {@code @OneToOne}
- *         {@code @PropertyRef("name")}
+ *         @Id Integer id;
+ *         @OneToOne
+ *         @PropertyRef("name")
  *         Employee employee;
  *     }
  * 
From ecd7a9193a386be78b51a3e692a2ddd35b8044cd Mon Sep 17 00:00:00 2001 From: Gavin King Date: Sun, 24 Aug 2025 21:21:25 +1000 Subject: [PATCH 2/5] use lots of 'var' in boot.model.internal --- .../AbstractEntityIdGeneratorResolver.java | 34 +- .../internal/AbstractPropertyHolder.java | 115 ++-- .../internal/AggregateComponentBinder.java | 148 ++--- .../AggregateComponentSecondPass.java | 48 +- .../boot/model/internal/AnnotatedColumn.java | 148 +++-- .../AnnotatedDiscriminatorColumn.java | 6 +- .../model/internal/AnnotatedJoinColumn.java | 44 +- .../model/internal/AnnotatedJoinColumns.java | 75 ++- .../boot/model/internal/AnnotationBinder.java | 69 +- .../boot/model/internal/AnnotationHelper.java | 25 +- .../boot/model/internal/AnyBinder.java | 79 ++- .../boot/model/internal/BasicValueBinder.java | 591 ++++++++---------- .../boot/model/internal/BinderHelper.java | 106 ++-- .../internal/ClassLoaderAccessLazyImpl.java | 33 - .../model/internal/ClassPropertyHolder.java | 98 ++- .../boot/model/internal/CollectionBinder.java | 571 ++++++++--------- .../internal/CollectionPropertyHolder.java | 4 +- .../model/internal/CollectionSecondPass.java | 5 +- .../boot/model/internal/ColumnsBuilder.java | 79 +-- .../internal/ComponentPropertyHolder.java | 73 +-- .../DialectOverridesAnnotationHelper.java | 67 +- .../DiscriminatorColumnSecondPass.java | 18 +- .../boot/model/internal/EmbeddableBinder.java | 157 +++-- .../boot/model/internal/EntityBinder.java | 325 +++++----- .../internal/FetchOverrideSecondPass.java | 12 +- .../boot/model/internal/FetchSecondPass.java | 2 +- .../boot/model/internal/FilterDefBinder.java | 21 +- .../internal/GeneratorAnnotationHelper.java | 40 +- .../boot/model/internal/GeneratorBinder.java | 93 ++- .../model/internal/GeneratorParameters.java | 21 +- .../boot/model/internal/IdBagBinder.java | 9 +- .../IdBagIdGeneratorResolverSecondPass.java | 123 ++-- .../IdGeneratorResolverSecondPass.java | 152 ++--- .../ImplicitToOneJoinTableSecondPass.java | 21 +- .../boot/model/internal/IndexBinder.java | 19 +- .../boot/model/internal/IndexColumn.java | 2 +- .../boot/model/internal/InheritanceState.java | 18 +- .../boot/model/internal/ListBinder.java | 6 +- .../boot/model/internal/MapBinder.java | 70 +-- .../boot/model/internal/NaturalIdBinder.java | 16 +- .../model/internal/OneToOneSecondPass.java | 57 +- .../boot/model/internal/PropertyBinder.java | 211 +++---- .../model/internal/PropertyContainer.java | 103 ++- .../model/internal/PropertyInferredData.java | 45 +- .../boot/model/internal/QueryBinder.java | 174 +++--- .../model/internal/QueryHintDefinition.java | 30 +- .../boot/model/internal/SoftDeleteHelper.java | 25 +- .../StrictIdGeneratorResolverSecondPass.java | 129 ++-- .../boot/model/internal/TableBinder.java | 12 +- .../model/internal/TimeZoneStorageHelper.java | 5 +- .../boot/model/internal/ToOneBinder.java | 109 ++-- .../model/internal/ToOneFkSecondPass.java | 15 +- 52 files changed, 2031 insertions(+), 2427 deletions(-) delete mode 100644 hibernate-core/src/main/java/org/hibernate/boot/model/internal/ClassLoaderAccessLazyImpl.java diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AbstractEntityIdGeneratorResolver.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AbstractEntityIdGeneratorResolver.java index fa3c7b089c5c..0365bb3ce3fa 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AbstractEntityIdGeneratorResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AbstractEntityIdGeneratorResolver.java @@ -6,27 +6,24 @@ import java.lang.annotation.Annotation; import java.util.HashMap; -import java.util.List; import java.util.Map; import org.hibernate.MappingException; import org.hibernate.annotations.IdGeneratorType; import org.hibernate.boot.model.IdentifierGeneratorDefinition; -import org.hibernate.boot.model.relational.Database; import org.hibernate.boot.spi.MetadataBuildingContext; -import org.hibernate.dialect.Dialect; -import org.hibernate.generator.Generator; -import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.mapping.Column; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.SimpleValue; import org.hibernate.models.spi.AnnotationTarget; -import org.hibernate.models.spi.ClassDetails; import org.hibernate.models.spi.MemberDetails; import jakarta.persistence.GeneratedValue; import static org.hibernate.boot.model.internal.GeneratorAnnotationHelper.handleIdGeneratorType; +import static org.hibernate.boot.model.internal.GeneratorAnnotationHelper.handleIdentityStrategy; +import static org.hibernate.boot.model.internal.GeneratorAnnotationHelper.locatePackageInfoDetails; +import static org.hibernate.boot.model.internal.GeneratorBinder.createGeneratorFrom; import static org.hibernate.boot.model.internal.GeneratorParameters.identityTablesString; import static org.hibernate.boot.model.internal.GeneratorStrategies.mapLegacyNamedGenerator; import static org.hibernate.id.IdentifierGenerator.ENTITY_NAME; @@ -35,6 +32,7 @@ import static org.hibernate.id.PersistentIdentifierGenerator.PK; import static org.hibernate.id.PersistentIdentifierGenerator.TABLE; import static org.hibernate.id.PersistentIdentifierGenerator.TABLES; +import static org.hibernate.internal.util.collections.CollectionHelper.size; /** * Template support for IdGeneratorResolver implementations dealing with entity identifiers @@ -65,7 +63,7 @@ public AbstractEntityIdGeneratorResolver( public final void doSecondPass(Map persistentClasses) throws MappingException { switch ( generatedValue.strategy() ) { case UUID -> handleUuidStrategy(); - case IDENTITY -> GeneratorAnnotationHelper.handleIdentityStrategy( idValue ); + case IDENTITY -> handleIdentityStrategy( idValue ); case SEQUENCE -> handleSequenceStrategy(); case TABLE -> handleTableStrategy(); case AUTO -> handleAutoStrategy(); @@ -134,7 +132,8 @@ protected boolean handleAsMetaAnnotated() { return true; } - final ClassDetails packageInfoDetails = GeneratorAnnotationHelper.locatePackageInfoDetails( idMember.getDeclaringType(), buildingContext ); + final var packageInfoDetails = + locatePackageInfoDetails( idMember.getDeclaringType(), buildingContext ); if ( packageInfoDetails != null ) { final Annotation fromPackage = findGeneratorAnnotation( packageInfoDetails ); if ( fromPackage != null ) { @@ -147,26 +146,23 @@ protected boolean handleAsMetaAnnotated() { } private Annotation findGeneratorAnnotation(AnnotationTarget annotationTarget) { - final List metaAnnotated = + final var metaAnnotated = annotationTarget.getMetaAnnotated( IdGeneratorType.class, buildingContext.getBootstrapContext().getModelsContext() ); - if ( CollectionHelper.size( metaAnnotated ) > 0 ) { - return metaAnnotated.get( 0 ); - } + return size( metaAnnotated ) > 0 ? metaAnnotated.get( 0 ) : null; - return null; } protected boolean handleAsLegacyGenerator() { // Handle a few legacy Hibernate generators... final String nameFromGeneratedValue = generatedValue.generator(); if ( !nameFromGeneratedValue.isBlank() ) { - final Class legacyNamedGenerator = + final var legacyNamedGenerator = mapLegacyNamedGenerator( nameFromGeneratedValue, idValue ); if ( legacyNamedGenerator != null ) { - final Map configuration = buildLegacyGeneratorConfig(); + final var configuration = buildLegacyGeneratorConfig(); //noinspection unchecked,rawtypes - GeneratorBinder.createGeneratorFrom( + createGeneratorFrom( new IdentifierGeneratorDefinition( nameFromGeneratedValue, legacyNamedGenerator.getName(), configuration ), idValue, @@ -181,15 +177,15 @@ protected boolean handleAsLegacyGenerator() { } private HashMap buildLegacyGeneratorConfig() { - final Database database = buildingContext.getMetadataCollector().getDatabase(); - final Dialect dialect = database.getDialect(); + final var database = buildingContext.getMetadataCollector().getDatabase(); + final var dialect = database.getDialect(); final HashMap configuration = new HashMap<>(); final String tableName = idValue.getTable().getQuotedName( dialect ); configuration.put( TABLE, tableName ); - final Column idColumn = (Column) idValue.getSelectables().get( 0); + final var idColumn = (Column) idValue.getSelectables().get( 0); final String idColumnName = idColumn.getQuotedName( dialect ); configuration.put( PK, idColumnName ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AbstractPropertyHolder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AbstractPropertyHolder.java index baf7fa0159f2..04877d3070a6 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AbstractPropertyHolder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AbstractPropertyHolder.java @@ -87,7 +87,7 @@ public abstract class AbstractPropertyHolder implements PropertyHolder { @Override public ConverterDescriptor resolveAttributeConverterDescriptor(MemberDetails attributeMember, boolean autoApply) { - final AttributeConversionInfo info = locateAttributeConversionInfo( attributeMember ); + final var info = locateAttributeConversionInfo( attributeMember ); if ( info != null ) { if ( info.isConversionDisabled() ) { return null; @@ -101,11 +101,13 @@ public ConverterDescriptor resolveAttributeConverterDescriptor(MemberDetail } } } - - return !autoApply ? null : context.getMetadataCollector() - .getConverterRegistry() - .getAttributeConverterAutoApplyHandler() - .findAutoApplyConverterForAttribute( attributeMember, context ); + else { + return autoApply + ? context.getMetadataCollector().getConverterRegistry() + .getAttributeConverterAutoApplyHandler() + .findAutoApplyConverterForAttribute( attributeMember, context ) + : null; + } } protected IllegalStateException buildExceptionFromInstantiationError(AttributeConversionInfo info, Exception e) { @@ -185,36 +187,36 @@ protected void setCurrentProperty(MemberDetails attributeMember) { // todo (jpa32) : some of this (association override handling esp) does the same work multiple times - consolidate if ( attributeMember == null ) { - this.currentPropertyColumnOverride = null; - this.currentPropertyColumnTransformerOverride = null; - this.currentPropertyJoinColumnOverride = null; - this.currentPropertyJoinTableOverride = null; - this.currentPropertyForeignKeyOverride = null; + currentPropertyColumnOverride = null; + currentPropertyColumnTransformerOverride = null; + currentPropertyJoinColumnOverride = null; + currentPropertyJoinTableOverride = null; + currentPropertyForeignKeyOverride = null; } else { - this.currentPropertyColumnOverride = buildColumnOverride( attributeMember, getPath(), context ); - if ( this.currentPropertyColumnOverride.isEmpty() ) { - this.currentPropertyColumnOverride = null; + currentPropertyColumnOverride = buildColumnOverride( attributeMember, getPath(), context ); + if ( currentPropertyColumnOverride.isEmpty() ) { + currentPropertyColumnOverride = null; } - this.currentPropertyColumnTransformerOverride = buildColumnTransformerOverride( attributeMember, context ); - if ( this.currentPropertyColumnTransformerOverride.isEmpty() ) { - this.currentPropertyColumnTransformerOverride = null; + currentPropertyColumnTransformerOverride = buildColumnTransformerOverride( attributeMember, context ); + if ( currentPropertyColumnTransformerOverride.isEmpty() ) { + currentPropertyColumnTransformerOverride = null; } - this.currentPropertyJoinColumnOverride = buildJoinColumnOverride( attributeMember, getPath(), context ); - if ( this.currentPropertyJoinColumnOverride.isEmpty() ) { - this.currentPropertyJoinColumnOverride = null; + currentPropertyJoinColumnOverride = buildJoinColumnOverride( attributeMember, getPath(), context ); + if ( currentPropertyJoinColumnOverride.isEmpty() ) { + currentPropertyJoinColumnOverride = null; } - this.currentPropertyJoinTableOverride = buildJoinTableOverride( attributeMember, getPath(), context ); - if ( this.currentPropertyJoinTableOverride.isEmpty() ) { - this.currentPropertyJoinTableOverride = null; + currentPropertyJoinTableOverride = buildJoinTableOverride( attributeMember, getPath(), context ); + if ( currentPropertyJoinTableOverride.isEmpty() ) { + currentPropertyJoinTableOverride = null; } - this.currentPropertyForeignKeyOverride = buildForeignKeyOverride( attributeMember, getPath(), context ); - if ( this.currentPropertyForeignKeyOverride.isEmpty() ) { - this.currentPropertyForeignKeyOverride = null; + currentPropertyForeignKeyOverride = buildForeignKeyOverride( attributeMember, getPath(), context ); + if ( currentPropertyForeignKeyOverride.isEmpty() ) { + currentPropertyForeignKeyOverride = null; } } } @@ -227,15 +229,11 @@ protected void setCurrentProperty(MemberDetails attributeMember) { */ @Override public Column[] getOverriddenColumn(String propertyName) { - final Column[] result = getExactOverriddenColumn( propertyName ); - if ( result == null ) { - if ( propertyName.contains( ".{element}." ) ) { - //support for non map collections where no prefix is needed - //TODO cache the underlying regexp - return getExactOverriddenColumn( propertyName.replace( ".{element}.", "." ) ); - } - } - return result; + final var overriddenColumn = getExactOverriddenColumn( propertyName ); + // support for non-map collections where no prefix is needed + return overriddenColumn == null && propertyName.contains( ".{element}." ) + ? getExactOverriddenColumn( propertyName.replace( ".{element}.", "." ) ) + : overriddenColumn; } @Override @@ -291,7 +289,9 @@ public JoinColumn[] getOverriddenJoinColumn(String propertyName) { //TODO cache the underlying regexp return getExactOverriddenJoinColumn( propertyName.replace( ".{element}.", "." ) ); } - return result; + else { + return result; + } } /** @@ -349,10 +349,9 @@ private ForeignKey getExactOverriddenForeignKey(String propertyName) { public JoinTable getJoinTable(MemberDetails attributeMember) { final String propertyName = qualify( getPath(), attributeMember.getName() ); final JoinTable result = getOverriddenJoinTable( propertyName ); - if ( result == null ) { - return attributeMember.getDirectAnnotationUsage( JoinTable.class ); - } - return result; + return result == null + ? attributeMember.getDirectAnnotationUsage( JoinTable.class ) + : result; } /** @@ -368,7 +367,9 @@ public JoinTable getOverriddenJoinTable(String propertyName) { //TODO cache the underlying regexp return getExactOverriddenJoinTable( propertyName.replace( ".{element}.", "." ) ); } - return result; + else { + return result; + } } /** @@ -435,12 +436,10 @@ private static Map buildColumnOverride( return result; } - final ModelsContext sourceModelContext = - context.getBootstrapContext().getModelsContext(); + final var modelContext = context.getBootstrapContext().getModelsContext(); final Map> columnOverrideMap = new HashMap<>(); - final AttributeOverride[] overrides = - element.getRepeatedAnnotationUsages( AttributeOverride.class, sourceModelContext ); + final var overrides = element.getRepeatedAnnotationUsages( AttributeOverride.class, modelContext ); if ( isNotEmpty( overrides ) ) { for ( AttributeOverride depAttr : overrides ) { final String qualifiedName = qualify( path, depAttr.name() ); @@ -459,7 +458,7 @@ private static Map buildColumnOverride( } } else if ( useColumnForTimeZoneStorage( element, context ) ) { - final Column column = createTemporalColumn( element, path, context ); + final var column = createTemporalColumn( element, path, context ); if ( isOffsetTimeClass( element ) ) { columnOverrideMap.put( path + "." + OffsetTimeCompositeUserType.LOCAL_TIME_NAME, @@ -472,7 +471,7 @@ else if ( useColumnForTimeZoneStorage( element, context ) ) { List.of( column ) ); } - final Column offsetColumn = createTimeZoneColumn( element, column, context ); + final var offsetColumn = createTimeZoneColumn( element, column, context ); columnOverrideMap.put( path + "." + AbstractTimeZoneStorageCompositeUserType.ZONE_OFFSET_NAME, List.of( offsetColumn ) @@ -489,11 +488,13 @@ private static Column createTimeZoneColumn( AnnotationTarget element, Column column, MetadataBuildingContext context) { - final TimeZoneColumn timeZoneColumn = element.getDirectAnnotationUsage( TimeZoneColumn.class ); - final ColumnJpaAnnotation created = JpaAnnotations.COLUMN.createUsage( context.getBootstrapContext().getModelsContext() ); - final String columnName = timeZoneColumn != null - ? timeZoneColumn.name() - : column.name() + "_tz"; + final var timeZoneColumn = element.getDirectAnnotationUsage( TimeZoneColumn.class ); + final ColumnJpaAnnotation created = + JpaAnnotations.COLUMN.createUsage( context.getBootstrapContext().getModelsContext() ); + final String columnName = + timeZoneColumn != null + ? timeZoneColumn.name() + : column.name() + "_tz"; created.name( columnName ); created.nullable( column.nullable() ); @@ -523,7 +524,7 @@ private static Column createTemporalColumn( MetadataBuildingContext context) { int precision; int secondPrecision; - final Column annotatedColumn = element.getDirectAnnotationUsage( Column.class ); + final var annotatedColumn = element.getDirectAnnotationUsage( Column.class ); if ( annotatedColumn != null ) { if ( isNotBlank( annotatedColumn.name() ) ) { return annotatedColumn; @@ -571,7 +572,7 @@ public MetadataBuildingContext getBuildingContext() { } private static Map buildColumnTransformerOverride(AnnotationTarget element, MetadataBuildingContext context) { - final ModelsContext sourceModelContext = context.getBootstrapContext().getModelsContext(); + final var sourceModelContext = context.getBootstrapContext().getModelsContext(); final Map columnOverride = new HashMap<>(); if ( element != null ) { element.forEachAnnotationUsage( ColumnTransformer.class, sourceModelContext, (usage) -> { @@ -584,7 +585,7 @@ private static Map buildColumnTransformerOverride(Ann private static Map buildJoinColumnOverride(AnnotationTarget element, String path, MetadataBuildingContext context) { final Map columnOverride = new HashMap<>(); if ( element != null ) { - for ( AssociationOverride override : buildAssociationOverrides( element, path, context ) ) { + for ( var override : buildAssociationOverrides( element, path, context ) ) { columnOverride.put( qualify( path, override.name() ), override.joinColumns() ); } } @@ -594,7 +595,7 @@ private static Map buildJoinColumnOverride(AnnotationTarge private static Map buildForeignKeyOverride(AnnotationTarget element, String path, MetadataBuildingContext context) { final Map foreignKeyOverride = new HashMap<>(); if ( element != null ) { - for ( AssociationOverride override : buildAssociationOverrides( element, path, context ) ) { + for ( var override : buildAssociationOverrides( element, path, context ) ) { foreignKeyOverride.put( qualify( path, override.name() ), override.foreignKey() ); } } @@ -608,7 +609,7 @@ private static AssociationOverride[] buildAssociationOverrides(AnnotationTarget private static Map buildJoinTableOverride(AnnotationTarget element, String path, MetadataBuildingContext context) { final Map result = new HashMap<>(); if ( element != null ) { - for ( AssociationOverride override : buildAssociationOverrides( element, path, context ) ) { + for ( var override : buildAssociationOverrides( element, path, context ) ) { if ( isEmpty( override.joinColumns() ) ) { result.put( qualify( path, override.name() ), override.joinTable() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AggregateComponentBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AggregateComponentBinder.java index f73e7ce84dc0..5d38b8f64992 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AggregateComponentBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AggregateComponentBinder.java @@ -4,25 +4,20 @@ */ package org.hibernate.boot.model.internal; -import java.util.List; import org.hibernate.annotations.JdbcTypeCode; import org.hibernate.annotations.Struct; -import org.hibernate.boot.model.relational.Database; import org.hibernate.boot.model.relational.QualifiedName; import org.hibernate.boot.model.relational.QualifiedNameImpl; import org.hibernate.boot.model.relational.QualifiedNameParser; -import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.PropertyData; import org.hibernate.mapping.AggregateColumn; -import org.hibernate.mapping.BasicValue; import org.hibernate.mapping.Component; import org.hibernate.models.spi.ClassDetails; import org.hibernate.models.spi.MemberDetails; import org.hibernate.type.SqlTypes; import org.hibernate.type.descriptor.java.spi.EmbeddableAggregateJavaType; -import org.hibernate.type.spi.TypeConfiguration; /** * Processes aggregate component annotations from Java classes and produces the Hibernate configuration-time metamodel, @@ -39,11 +34,12 @@ public static void processAggregate( ClassDetails componentClassDetails, AnnotatedColumns columns, MetadataBuildingContext context) { - if ( isAggregate( inferredData.getAttributeMember(), componentClassDetails, context ) ) { - final InFlightMetadataCollector metadataCollector = context.getMetadataCollector(); - final TypeConfiguration typeConfiguration = metadataCollector.getTypeConfiguration(); + if ( isAggregate( inferredData.getAttributeMember(), componentClassDetails ) ) { + final var metadataCollector = context.getMetadataCollector(); + final var typeConfiguration = metadataCollector.getTypeConfiguration(); // Determine a struct name if this is a struct through some means - final QualifiedName structQualifiedName = determineStructName( columns, inferredData, componentClassDetails, context ); + final QualifiedName structQualifiedName = + determineStructName( columns, inferredData, componentClassDetails, context ); final String structName = structQualifiedName == null ? null : structQualifiedName.render(); // We must register a special JavaType for the embeddable which can provide a recommended JdbcType @@ -55,8 +51,7 @@ public static void processAggregate( component.setStructColumnNames( determineStructAttributeNames( inferredData, componentClassDetails ) ); // Determine the aggregate column - final BasicValueBinder basicValueBinder = - new BasicValueBinder( BasicValueBinder.Kind.ATTRIBUTE, component, context ); + final var basicValueBinder = new BasicValueBinder( BasicValueBinder.Kind.ATTRIBUTE, component, context ); basicValueBinder.setReturnedClassName( inferredData.getClassOrElementType().getName() ); basicValueBinder.setColumns( columns ); basicValueBinder.setPersistentClassName( propertyHolder.getClassName() ); @@ -66,8 +61,8 @@ public static void processAggregate( inferredData.getDeclaringClass().getName(), null ); - final BasicValue propertyValue = basicValueBinder.make(); - final AggregateColumn aggregateColumn = (AggregateColumn) propertyValue.getColumn(); + final var propertyValue = basicValueBinder.make(); + final var aggregateColumn = (AggregateColumn) propertyValue.getColumn(); if ( structName != null && aggregateColumn.getSqlType() == null ) { if ( inferredData.getAttributeMember().isArray() || inferredData.getAttributeMember().isPlural() ) { aggregateColumn.setSqlTypeCode( getStructPluralSqlTypeCode( context ) ); @@ -102,19 +97,15 @@ public static void processAggregate( } private static int getStructPluralSqlTypeCode(MetadataBuildingContext context) { - final int arrayTypeCode = context.getPreferredSqlTypeCodeForArray(); - switch ( arrayTypeCode ) { - case SqlTypes.ARRAY: - return SqlTypes.STRUCT_ARRAY; - case SqlTypes.TABLE: - return SqlTypes.STRUCT_TABLE; - default: - throw new UnsupportedOperationException( "Dialect does not support structured array types: " + context.getMetadataCollector() - .getDatabase() - .getDialect() - .getClass() - .getName() ); - } + return switch ( context.getPreferredSqlTypeCodeForArray() ) { + case SqlTypes.ARRAY -> SqlTypes.STRUCT_ARRAY; + case SqlTypes.TABLE -> SqlTypes.STRUCT_TABLE; + default -> throw new UnsupportedOperationException( + "Dialect does not support structured array types: " + + context.getMetadataCollector().getDatabase() + .getDialect().getClass().getName() + ); + }; } private static QualifiedName determineStructName( @@ -122,44 +113,45 @@ private static QualifiedName determineStructName( PropertyData inferredData, ClassDetails returnedClassOrElement, MetadataBuildingContext context) { - final MemberDetails property = inferredData.getAttributeMember(); - if ( property != null ) { - final Struct struct = property.getDirectAnnotationUsage( Struct.class ); + final var memberDetails = inferredData.getAttributeMember(); + if ( memberDetails != null ) { + final var struct = memberDetails.getDirectAnnotationUsage( Struct.class ); if ( struct != null ) { return toQualifiedName( struct, context ); } - - final JdbcTypeCode jdbcTypeCodeAnn = property.getDirectAnnotationUsage( JdbcTypeCode.class ); - if ( jdbcTypeCodeAnn != null - && ( jdbcTypeCodeAnn.value() == SqlTypes.STRUCT - || jdbcTypeCodeAnn.value() == SqlTypes.STRUCT_ARRAY - || jdbcTypeCodeAnn.value() == SqlTypes.STRUCT_TABLE ) - && columns != null ) { - final List columnList = columns.getColumns(); - final String sqlType; - if ( columnList.size() == 1 && ( sqlType = columnList.get( 0 ).getSqlType() ) != null ) { - if ( sqlType.contains( "." ) ) { - return QualifiedNameParser.INSTANCE.parse( sqlType ); + else { + final var jdbcTypeCode = memberDetails.getDirectAnnotationUsage( JdbcTypeCode.class ); + if ( jdbcTypeCode != null + && ( jdbcTypeCode.value() == SqlTypes.STRUCT + || jdbcTypeCode.value() == SqlTypes.STRUCT_ARRAY + || jdbcTypeCode.value() == SqlTypes.STRUCT_TABLE ) + && columns != null ) { + final var columnList = columns.getColumns(); + if ( columnList.size() == 1 ) { + final String sqlType = columnList.get( 0 ).getSqlType(); + if ( sqlType != null ) { + if ( sqlType.contains( "." ) ) { + return QualifiedNameParser.INSTANCE.parse( sqlType ); + } + else { + return new QualifiedNameParser.NameParts( + null, + null, + context.getMetadataCollector().getDatabase().toIdentifier( sqlType ) + ); + } + } } - return new QualifiedNameParser.NameParts( - null, - null, - context.getMetadataCollector().getDatabase().toIdentifier( sqlType ) - ); } } } - final Struct struct = returnedClassOrElement.getDirectAnnotationUsage( Struct.class ); - if ( struct != null ) { - return toQualifiedName( struct, context ); - } - - return null; + final var struct = returnedClassOrElement.getDirectAnnotationUsage( Struct.class ); + return struct == null ? null : toQualifiedName( struct, context ); } private static QualifiedName toQualifiedName(Struct struct, MetadataBuildingContext context) { - final Database database = context.getMetadataCollector().getDatabase(); + final var database = context.getMetadataCollector().getDatabase(); return new QualifiedNameImpl( database.toIdentifier( struct.catalog() ), database.toIdentifier( struct.schema() ), @@ -168,51 +160,41 @@ private static QualifiedName toQualifiedName(Struct struct, MetadataBuildingCont } private static String[] determineStructAttributeNames(PropertyData inferredData, ClassDetails returnedClassOrElement) { - final MemberDetails property = inferredData.getAttributeMember(); - if ( property != null ) { - final Struct struct = property.getDirectAnnotationUsage( Struct.class ); + final var memberDetails = inferredData.getAttributeMember(); + if ( memberDetails != null ) { + final var struct = memberDetails.getDirectAnnotationUsage( Struct.class ); if ( struct != null ) { return struct.attributes(); } } - - final Struct struct = returnedClassOrElement.getDirectAnnotationUsage( Struct.class ); - if ( struct != null ) { - return struct.attributes(); - } - - return null; + final var struct = returnedClassOrElement.getDirectAnnotationUsage( Struct.class ); + return struct == null ? null : struct.attributes(); } - private static boolean isAggregate( - MemberDetails property, - ClassDetails returnedClass, - MetadataBuildingContext context) { + private static boolean isAggregate(MemberDetails property, ClassDetails returnedClass) { if ( property != null ) { if ( property.hasDirectAnnotationUsage( Struct.class ) ) { return true; } - - final JdbcTypeCode jdbcTypeCode = property.getDirectAnnotationUsage( JdbcTypeCode.class ); - if ( jdbcTypeCode != null ) { - switch ( jdbcTypeCode.value() ) { - case SqlTypes.STRUCT: - case SqlTypes.JSON: - case SqlTypes.SQLXML: - case SqlTypes.STRUCT_ARRAY: - case SqlTypes.STRUCT_TABLE: - case SqlTypes.JSON_ARRAY: - case SqlTypes.XML_ARRAY: { - return true; + else { + final var jdbcTypeCode = property.getDirectAnnotationUsage( JdbcTypeCode.class ); + if ( jdbcTypeCode != null ) { + switch ( jdbcTypeCode.value() ) { + case SqlTypes.STRUCT: + case SqlTypes.JSON: + case SqlTypes.SQLXML: + case SqlTypes.STRUCT_ARRAY: + case SqlTypes.STRUCT_TABLE: + case SqlTypes.JSON_ARRAY: + case SqlTypes.XML_ARRAY: + return true; } } } } - if ( returnedClass != null ) { - return returnedClass.hasDirectAnnotationUsage( Struct.class ); - } + return returnedClass != null + && returnedClass.hasDirectAnnotationUsage( Struct.class ); - return false; } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AggregateComponentSecondPass.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AggregateComponentSecondPass.java index 4b65007cef35..a7e728c5f587 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AggregateComponentSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AggregateComponentSecondPass.java @@ -13,14 +13,11 @@ import org.hibernate.MappingException; import org.hibernate.annotations.Comment; import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.boot.model.relational.Database; import org.hibernate.boot.model.relational.Namespace; import org.hibernate.boot.model.relational.QualifiedName; import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.SecondPass; -import org.hibernate.dialect.Dialect; -import org.hibernate.dialect.aggregate.AggregateSupport; import org.hibernate.internal.util.ReflectHelper; import org.hibernate.mapping.AggregateColumn; import org.hibernate.mapping.Collection; @@ -36,7 +33,6 @@ import org.hibernate.models.spi.ClassDetails; import org.hibernate.sql.Template; import org.hibernate.type.SqlTypes; -import org.hibernate.type.spi.TypeConfiguration; import static org.hibernate.internal.util.StringHelper.qualify; @@ -68,11 +64,11 @@ public AggregateComponentSecondPass( public void doSecondPass(Map persistentClasses) throws MappingException { validateComponent( component, qualify( propertyHolder.getPath(), propertyName ), isAggregateArray() ); - final InFlightMetadataCollector metadataCollector = context.getMetadataCollector(); - final TypeConfiguration typeConfiguration = metadataCollector.getTypeConfiguration(); - final Database database = metadataCollector.getDatabase(); - final Dialect dialect = database.getDialect(); - final AggregateSupport aggregateSupport = dialect.getAggregateSupport(); + final var metadataCollector = context.getMetadataCollector(); + final var typeConfiguration = metadataCollector.getTypeConfiguration(); + final var database = metadataCollector.getDatabase(); + final var dialect = database.getDialect(); + final var aggregateSupport = dialect.getAggregateSupport(); // Sort the component properties early to ensure the aggregated // columns respect the same order as the component's properties @@ -94,26 +90,23 @@ public void doSecondPass(Map persistentClasses) throws if ( !database.getDialect().supportsUserDefinedTypes() ) { throw new MappingException( "Database does not support user-defined types (remove '@Struct' annotation)" ); } - final UserDefinedObjectType udt = - new UserDefinedObjectType( "orm", namespace, structName.getObjectName() ); - final Comment comment = componentClassDetails.getDirectAnnotationUsage( Comment.class ); + final var udt = new UserDefinedObjectType( "orm", namespace, structName.getObjectName() ); + final var comment = componentClassDetails.getDirectAnnotationUsage( Comment.class ); if ( comment != null ) { udt.setComment( comment.value() ); } - for ( org.hibernate.mapping.Column aggregatedColumn : aggregatedColumns ) { + for ( var aggregatedColumn : aggregatedColumns ) { udt.addColumn( aggregatedColumn ); } - final UserDefinedObjectType registeredUdt = namespace.createUserDefinedType( - structName.getObjectName(), - name -> udt - ); + final var registeredUdt = namespace.createUserDefinedType( structName.getObjectName(), name -> udt ); if ( registeredUdt == udt ) { addAuxiliaryObjects = true; orderColumns( registeredUdt, originalOrder ); } else { addAuxiliaryObjects = - isAggregateArray() && namespace.locateUserDefinedArrayType( Identifier.toIdentifier( aggregateColumn.getSqlType() ) ) == null; + isAggregateArray() + && namespace.locateUserDefinedArrayType( Identifier.toIdentifier( aggregateColumn.getSqlType() ) ) == null; validateEqual( registeredUdt, udt ); } } @@ -121,12 +114,11 @@ public void doSecondPass(Map persistentClasses) throws addAuxiliaryObjects = true; } final String aggregateReadTemplate = aggregateColumn.getAggregateReadExpressionTemplate( dialect ); - final String aggregateReadExpression = aggregateReadTemplate.replace( - Template.TEMPLATE + ".", - "" - ); - final String aggregateAssignmentExpression = aggregateColumn.getAggregateAssignmentExpressionTemplate( dialect ) - .replace( Template.TEMPLATE + ".", "" ); + final String aggregateReadExpression = + aggregateReadTemplate.replace( Template.TEMPLATE + ".", "" ); + final String aggregateAssignmentExpression = + aggregateColumn.getAggregateAssignmentExpressionTemplate( dialect ) + .replace( Template.TEMPLATE + ".", "" ); if ( addAuxiliaryObjects ) { aggregateSupport.aggregateAuxiliaryDatabaseObjects( database.getDefaultNamespace(), @@ -144,7 +136,7 @@ public void doSecondPass(Map persistentClasses) throws ); // The following determines the custom read/write expression and write expression for aggregatedColumns - for ( org.hibernate.mapping.Column subColumn : aggregatedColumns ) { + for ( var subColumn : aggregatedColumns ) { final String selectableExpression = subColumn.getText( dialect ); final String customReadExpression; final String assignmentExpression = aggregateSupport.aggregateComponentAssignmentExpression( @@ -291,9 +283,9 @@ else if ( component.getInstantiatorPropertyNames() != null ) { addColumns( orderedColumns, properties.get( propertyIndex ).getValue() ); } } - final List reorderedColumn = context.getBuildingOptions() - .getColumnOrderingStrategy() - .orderUserDefinedTypeColumns( userDefinedType, context.getMetadataCollector() ); + final List reorderedColumn = + context.getBuildingOptions().getColumnOrderingStrategy() + .orderUserDefinedTypeColumns( userDefinedType, context.getMetadataCollector() ); userDefinedType.reorderColumns( reorderedColumn != null ? reorderedColumn : orderedColumns ); } else { diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedColumn.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedColumn.java index 6bf98fddaf22..dc4622e20c07 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedColumn.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedColumn.java @@ -35,7 +35,6 @@ import org.hibernate.mapping.Join; import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.Table; -import org.hibernate.models.spi.MemberDetails; import org.hibernate.models.spi.ModelsContext; import static org.hibernate.boot.model.internal.BinderHelper.getPath; @@ -46,7 +45,6 @@ import static org.hibernate.internal.util.StringHelper.isEmpty; import static org.hibernate.internal.util.StringHelper.isNotEmpty; import static org.hibernate.internal.util.StringHelper.nullIfBlank; -import static org.hibernate.internal.util.StringHelper.nullIfEmpty; import static org.hibernate.internal.util.collections.ArrayHelper.isEmpty; import static org.hibernate.internal.util.collections.CollectionHelper.isNotEmpty; @@ -370,13 +368,10 @@ boolean inferColumnNameIfPossible(String columnName, String propertyName, boolea private String resolveLogicalColumnName(String columnName, String propertyName) { final String baseColumnName = isNotEmpty( columnName ) ? columnName : inferColumnName( propertyName ); - if ( parent.getPropertyHolder() != null && parent.getPropertyHolder().isComponent() ) { - // see if we need to apply one-or-more @EmbeddedColumnNaming patterns - return applyEmbeddedColumnNaming( baseColumnName, (ComponentPropertyHolder) parent.getPropertyHolder() ); - } - else { - return baseColumnName; - } + return parent.getPropertyHolder() != null && parent.getPropertyHolder().isComponent() + // see if we need to apply one-or-more @EmbeddedColumnNaming patterns + ? applyEmbeddedColumnNaming( baseColumnName, (ComponentPropertyHolder) parent.getPropertyHolder() ) + : baseColumnName; } private String applyEmbeddedColumnNaming(String inferredColumnName, ComponentPropertyHolder propertyHolder) { @@ -393,7 +388,7 @@ private String applyEmbeddedColumnNaming(String inferredColumnName, ComponentPro ComponentPropertyHolder tester = propertyHolder; while ( tester.parent.isComponent() ) { - final ComponentPropertyHolder parentHolder = (ComponentPropertyHolder) tester.parent; + final var parentHolder = (ComponentPropertyHolder) tester.parent; final String parentColumnNamingPattern = parentHolder.getComponent().getColumnNamingPattern(); if ( isNotEmpty( parentColumnNamingPattern ) ) { // home_zip_code @@ -413,7 +408,7 @@ private String applyEmbeddedColumnNaming(String inferredColumnName, ComponentPro protected String processColumnName(String columnName, boolean applyNamingStrategy) { if ( applyNamingStrategy ) { - final Database database = getDatabase(); + final var database = getDatabase(); return getPhysicalNamingStrategy() .toPhysicalColumnName( database.toIdentifier( columnName ), database.getJdbcEnvironment() ) .render( database.getDialect() ); @@ -438,7 +433,7 @@ public AttributePath getAttributePath() { public boolean isCollectionElement() { // if the propertyHolder is a collection, assume the // @Column refers to the element column - final PropertyHolder propertyHolder = getParent().getPropertyHolder(); + final var propertyHolder = getParent().getPropertyHolder(); return !propertyHolder.isComponent() && !propertyHolder.isEntity(); } @@ -654,8 +649,8 @@ public static AnnotatedColumns buildColumnsFromAnnotations( ); } - public static AnnotatedColumns buildColumnsFromAnnotations( - jakarta.persistence.Column[] columns, + public static AnnotatedColumns buildColumnFromAnnotations( + jakarta.persistence.Column column, // Comment commentAnn, Nullability nullability, PropertyHolder propertyHolder, @@ -664,7 +659,9 @@ public static AnnotatedColumns buildColumnsFromAnnotations( Map secondaryTables, MetadataBuildingContext context) { return buildColumnsOrFormulaFromAnnotation( - columns, + column == null + ? null + : new jakarta.persistence.Column[] {column}, null, null, // commentAnn, @@ -688,7 +685,9 @@ public static AnnotatedColumns buildColumnOrFormulaFromAnnotation( Map secondaryTables, MetadataBuildingContext context) { return buildColumnsOrFormulaFromAnnotation( - column==null ? null : new jakarta.persistence.Column[] {column}, + column==null + ? null + : new jakarta.persistence.Column[] {column}, formulaAnn, fractionalSeconds, // commentAnn, @@ -714,12 +713,12 @@ public static AnnotatedColumns buildColumnsOrFormulaFromAnnotation( MetadataBuildingContext context) { if ( formulaAnn != null ) { - final AnnotatedColumns parent = new AnnotatedColumns(); + final var parent = new AnnotatedColumns(); parent.setPropertyHolder( propertyHolder ); parent.setPropertyName( getRelativePath( propertyHolder, inferredData.getPropertyName() ) ); parent.setBuildingContext( context ); parent.setJoins( secondaryTables ); //unnecessary - final AnnotatedColumn formulaColumn = new AnnotatedColumn(); + final var formulaColumn = new AnnotatedColumn(); formulaColumn.setFormula( formulaAnn.value() ); formulaColumn.setImplicit( false ); // formulaColumn.setBuildingContext( context ); @@ -729,7 +728,7 @@ public static AnnotatedColumns buildColumnsOrFormulaFromAnnotation( return parent; } else { - final jakarta.persistence.Column[] actualColumns = overrideColumns( columns, propertyHolder, inferredData ); + final var actualColumns = overrideColumns( columns, propertyHolder, inferredData ); if ( isEmpty( actualColumns ) ) { return buildImplicitColumn( fractionalSeconds, @@ -762,7 +761,7 @@ private static jakarta.persistence.Column[] overrideColumns( PropertyHolder propertyHolder, PropertyData inferredData ) { final String path = getPath( propertyHolder, inferredData ); - final jakarta.persistence.Column[] overriddenCols = propertyHolder.getOverriddenColumn( path ); + final var overriddenCols = propertyHolder.getOverriddenColumn( path ); if ( overriddenCols != null ) { //check for overridden first if ( columns != null && overriddenCols.length != columns.length ) { @@ -792,20 +791,13 @@ private static AnnotatedColumns buildExplicitColumns( MetadataBuildingContext context, jakarta.persistence.Column[] actualCols, FractionalSeconds fractionalSeconds) { - final AnnotatedColumns parent = new AnnotatedColumns(); + final var parent = new AnnotatedColumns(); parent.setPropertyHolder( propertyHolder ); parent.setPropertyName( getRelativePath( propertyHolder, inferredData.getPropertyName() ) ); parent.setJoins( secondaryTables ); parent.setBuildingContext( context ); - for ( jakarta.persistence.Column column : actualCols ) { - final Database database = context.getMetadataCollector().getDatabase(); - final String sqlType = getSqlType( context, column ); - final String tableName = getTableName( column, database ); -// final Identifier logicalName = database.getJdbcEnvironment() -// .getIdentifierHelper() -// .toIdentifier( column.table() ); -// final Identifier physicalName = physicalNamingStrategy.toPhysicalTableName( logicalName ); -// tableName = physicalName.render( database.getDialect() ); + final var database = context.getMetadataCollector().getDatabase(); + for ( var column : actualCols ) { buildColumn( // comment, propertyHolder, @@ -816,8 +808,8 @@ private static AnnotatedColumns buildExplicitColumns( database, column, fractionalSeconds, - sqlType, - tableName, + getSqlType( context, column ), + getTableName( column, database ), context.getBootstrapContext().getModelsContext() ); } @@ -856,7 +848,7 @@ private static AnnotatedColumn buildColumn( String tableName, ModelsContext sourceModelContext) { final String columnName = logicalColumnName( inferredData, suffixForDefaultColumnName, database, column ); - final AnnotatedColumn annotatedColumn = new AnnotatedColumn(); + final var annotatedColumn = new AnnotatedColumn(); annotatedColumn.setLogicalColumnName( columnName ); annotatedColumn.setImplicit( false ); annotatedColumn.setSqlType( sqlType ); @@ -867,10 +859,7 @@ private static AnnotatedColumn buildColumn( else { annotatedColumn.setPrecision( column.precision() ); // The passed annotation could also be a MapKeyColumn - Integer secondPrecision = column.annotationType() == jakarta.persistence.Column.class - ? column.secondPrecision() - : null; - annotatedColumn.setTemporalPrecision( secondPrecision == null || secondPrecision == -1 ? null : secondPrecision ); + annotatedColumn.setTemporalPrecision( temporalPrecision( column ) ); } annotatedColumn.setScale( column.scale() ); annotatedColumn.handleArrayLength( inferredData ); @@ -891,8 +880,18 @@ private static AnnotatedColumn buildColumn( return annotatedColumn; } + private static Integer temporalPrecision(jakarta.persistence.Column column) { + final Integer secondPrecision = + column.annotationType() == jakarta.persistence.Column.class + ? column.secondPrecision() + : null; + return secondPrecision == null || secondPrecision == -1 + ? null + : secondPrecision; + } + private void handleArrayLength(PropertyData inferredData) { - final Array arrayAnn = inferredData.getAttributeMember().getDirectAnnotationUsage( Array.class ); + final var arrayAnn = inferredData.getAttributeMember().getDirectAnnotationUsage( Array.class ); if ( arrayAnn != null ) { setArrayLength( arrayAnn.length() ); } @@ -904,7 +903,7 @@ private static String logicalColumnName( Database database, jakarta.persistence.Column column) { final String columnName = getColumnName( database, column ); - // NOTE : this is the logical column name, not the physical! + // NOTE: this is the logical column name, not the physical! return isEmpty( columnName ) && isNotEmpty( suffixForDefaultColumnName ) ? inferredData.getPropertyName() + suffixForDefaultColumnName : columnName; @@ -918,17 +917,17 @@ private static String getColumnName(Database database, jakarta.persistence.Colum } void applyColumnDefault(PropertyData inferredData, int length) { - final MemberDetails attributeMember = inferredData.getAttributeMember(); - if ( attributeMember != null ) { - final ColumnDefault columnDefault = getOverridableAnnotation( - attributeMember, + final var memberDetails = inferredData.getAttributeMember(); + if ( memberDetails != null ) { + final var columnDefault = getOverridableAnnotation( + memberDetails, ColumnDefault.class, getBuildingContext() ); if ( columnDefault != null ) { if ( length != 1 ) { throw new AnnotationException( "'@ColumnDefault' may only be applied to single-column mappings but '" - + attributeMember.getName() + "' maps to " + length + " columns" ); + + memberDetails.getName() + "' maps to " + length + " columns" ); } setDefaultValue( columnDefault.value() ); } @@ -939,17 +938,17 @@ void applyColumnDefault(PropertyData inferredData, int length) { } void applyGeneratedAs(PropertyData inferredData, int length) { - final MemberDetails attributeMember = inferredData.getAttributeMember(); - if ( attributeMember != null ) { - final GeneratedColumn generatedColumn = getOverridableAnnotation( - attributeMember, + final var memberDetails = inferredData.getAttributeMember(); + if ( memberDetails != null ) { + final var generatedColumn = getOverridableAnnotation( + memberDetails, GeneratedColumn.class, getBuildingContext() ); if ( generatedColumn != null ) { if (length!=1) { throw new AnnotationException("'@GeneratedColumn' may only be applied to single-column mappings but '" - + attributeMember.getName() + "' maps to " + length + " columns" ); + + memberDetails.getName() + "' maps to " + length + " columns" ); } setGeneratedAs( generatedColumn.value() ); } @@ -965,9 +964,9 @@ private void applyColumnCheckConstraint(jakarta.persistence.Column column) { void applyCheckConstraints(jakarta.persistence.CheckConstraint[] checkConstraintAnnotationUsages) { if ( isNotEmpty( checkConstraintAnnotationUsages ) ) { - for ( jakarta.persistence.CheckConstraint checkConstraintAnnotationUsage : checkConstraintAnnotationUsages ) { + for ( var checkConstraintAnnotationUsage : checkConstraintAnnotationUsages ) { addCheckConstraint( - nullIfEmpty( checkConstraintAnnotationUsage.name() ), + nullIfBlank( checkConstraintAnnotationUsage.name() ), checkConstraintAnnotationUsage.constraint(), checkConstraintAnnotationUsage.options() ); @@ -976,24 +975,24 @@ void applyCheckConstraints(jakarta.persistence.CheckConstraint[] checkConstraint } void applyCheckConstraint(PropertyData inferredData, int length) { - final MemberDetails attributeMember = inferredData.getAttributeMember(); - if ( attributeMember != null ) { + final var memberDetails = inferredData.getAttributeMember(); + if ( memberDetails != null ) { // if there are multiple annotations, they're not overrideable - final Checks checksAnn = attributeMember.getDirectAnnotationUsage( Checks.class ); + final var checksAnn = memberDetails.getDirectAnnotationUsage( Checks.class ); if ( checksAnn != null ) { - final Check[] checkAnns = checksAnn.value(); - for ( Check checkAnn : checkAnns ) { - addCheckConstraint( nullIfEmpty( checkAnn.name() ), checkAnn.constraints() ); + final var checkAnns = checksAnn.value(); + for ( var checkAnn : checkAnns ) { + addCheckConstraint( nullIfBlank( checkAnn.name() ), checkAnn.constraints() ); } } else { - final Check checkAnn = getOverridableAnnotation( attributeMember, Check.class, getBuildingContext() ); + final var checkAnn = getOverridableAnnotation( memberDetails, Check.class, getBuildingContext() ); if ( checkAnn != null ) { if ( length != 1 ) { throw new AnnotationException("'@Check' may only be applied to single-column mappings but '" - + attributeMember.getName() + "' maps to " + length + " columns (use a table-level '@Check')" ); + + memberDetails.getName() + "' maps to " + length + " columns (use a table-level '@Check')" ); } - addCheckConstraint( nullIfEmpty( checkAnn.name() ), checkAnn.constraints() ); + addCheckConstraint( nullIfBlank( checkAnn.name() ), checkAnn.constraints() ); } } } @@ -1008,29 +1007,24 @@ private void extractDataFromPropertyData( PropertyData inferredData, ModelsContext context) { if ( inferredData != null ) { - final MemberDetails attributeMember = inferredData.getAttributeMember(); - if ( attributeMember != null ) { + final var memberDetails = inferredData.getAttributeMember(); + if ( memberDetails != null ) { if ( propertyHolder.isComponent() ) { processColumnTransformerExpressions( propertyHolder.getOverriddenColumnTransformer( logicalColumnName ) ); } - - - attributeMember.forEachAnnotationUsage( ColumnTransformer.class, context, this::processColumnTransformerExpressions ); + memberDetails.forEachAnnotationUsage( ColumnTransformer.class, context, this::processColumnTransformerExpressions ); } } } private void processColumnTransformerExpressions(ColumnTransformer annotation) { - if ( annotation == null ) { - // nothing to process - return; - } - - final String targetColumnName = annotation.forColumn(); - if ( isBlank( targetColumnName ) - || targetColumnName.equals( logicalColumnName != null ? logicalColumnName : "" ) ) { - readExpression = nullIfBlank( annotation.read() ); - writeExpression = nullIfBlank( annotation.write() ); + if ( annotation != null ) { + final String targetColumnName = annotation.forColumn(); + if ( isBlank( targetColumnName ) + || targetColumnName.equals( logicalColumnName != null ? logicalColumnName : "" ) ) { + readExpression = nullIfBlank( annotation.read() ); + writeExpression = nullIfBlank( annotation.write() ); + } } } @@ -1043,7 +1037,7 @@ private static AnnotatedColumns buildImplicitColumn( // Comment comment, Nullability nullability, MetadataBuildingContext context) { - final AnnotatedColumns columns = new AnnotatedColumns(); + final var columns = new AnnotatedColumns(); columns.setPropertyHolder( propertyHolder ); columns.setPropertyName( getRelativePath( propertyHolder, inferredData.getPropertyName() ) ); columns.setBuildingContext( context ); @@ -1084,7 +1078,7 @@ private static AnnotatedColumns buildImplicitColumn( @Override public String toString() { - final StringBuilder string = new StringBuilder(); + final var string = new StringBuilder(); string.append( getClass().getSimpleName() ).append( "(" ); if ( isNotEmpty( formulaString ) ) { string.append( "formula='" ).append( formulaString ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedDiscriminatorColumn.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedDiscriminatorColumn.java index aad0988db2bc..3d7024a4dd21 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedDiscriminatorColumn.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedDiscriminatorColumn.java @@ -47,12 +47,12 @@ public static AnnotatedDiscriminatorColumn buildDiscriminatorColumn( Column columnOverride, String defaultColumnName, MetadataBuildingContext context) { - final AnnotatedColumns parent = new AnnotatedColumns(); + final var parent = new AnnotatedColumns(); parent.setBuildingContext( context ); - final AnnotatedDiscriminatorColumn column = new AnnotatedDiscriminatorColumn( defaultColumnName ); + final var column = new AnnotatedDiscriminatorColumn( defaultColumnName ); final DiscriminatorType discriminatorType; if ( discriminatorFormula != null ) { - final DiscriminatorType type = discriminatorFormula.discriminatorType(); + final var type = discriminatorFormula.discriminatorType(); if ( type == DiscriminatorType.STRING ) { discriminatorType = discriminatorColumn == null ? type : discriminatorColumn.discriminatorType(); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedJoinColumn.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedJoinColumn.java index e9d3a74f171a..e5c57d18d96e 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedJoinColumn.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedJoinColumn.java @@ -7,11 +7,7 @@ import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; import org.hibernate.annotations.JoinFormula; -import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.naming.ImplicitNamingStrategy; -import org.hibernate.boot.model.naming.ObjectNameNormalizer; -import org.hibernate.boot.model.relational.Database; -import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.PropertyData; import org.hibernate.mapping.Column; @@ -89,7 +85,7 @@ static AnnotatedJoinColumn buildJoinColumn( public static AnnotatedJoinColumn buildJoinFormula( JoinFormula joinFormula, AnnotatedJoinColumns parent) { - final AnnotatedJoinColumn formulaColumn = new AnnotatedJoinColumn(); + final var formulaColumn = new AnnotatedJoinColumn(); formulaColumn.setFormula( joinFormula.value() ); formulaColumn.setReferencedColumn( joinFormula.referencedColumnName() ); // formulaColumn.setContext( buildingContext ); @@ -130,7 +126,7 @@ private static AnnotatedJoinColumn explicitJoinColumn( AnnotatedJoinColumns parent, PropertyData inferredData, String defaultColumnSuffix) { - final AnnotatedJoinColumn column = new AnnotatedJoinColumn(); + final var column = new AnnotatedJoinColumn(); // column.setContext( context ); // column.setJoins( joins ); // column.setPropertyHolder( propertyHolder ); @@ -150,7 +146,7 @@ private static AnnotatedJoinColumn implicitJoinColumn( AnnotatedJoinColumns parent, PropertyData inferredData, String defaultColumnSuffix) { - final AnnotatedJoinColumn column = new AnnotatedJoinColumn(); + final var column = new AnnotatedJoinColumn(); // column.setContext( context ); // column.setJoins( joins ); // column.setPropertyHolder( propertyHolder ); @@ -178,6 +174,8 @@ public void applyJoinAnnotation(JoinColumn joinColumn, String defaultName) { else { setImplicit( false ); + final var context = getBuildingContext(); + final String name = joinColumn.name(); if ( !name.isBlank() ) { setLogicalColumnName( name ); @@ -185,7 +183,7 @@ public void applyJoinAnnotation(JoinColumn joinColumn, String defaultName) { final String columnDefinition = joinColumn.columnDefinition(); if ( !columnDefinition.isBlank() ) { - setSqlType( getBuildingContext().getObjectNameNormalizer().applyGlobalQuoting( columnDefinition ) ); + setSqlType( context.getObjectNameNormalizer().applyGlobalQuoting( columnDefinition ) ); } setNullable( joinColumn.nullable() ); @@ -202,11 +200,11 @@ public void applyJoinAnnotation(JoinColumn joinColumn, String defaultName) { setExplicitTableName( "" ); } else { - final Database database = getBuildingContext().getMetadataCollector().getDatabase(); - final Identifier logicalIdentifier = database.toIdentifier( table ); - final Identifier physicalIdentifier = getBuildingContext().getBuildingOptions() - .getPhysicalNamingStrategy() - .toPhysicalTableName( logicalIdentifier, database.getJdbcEnvironment() ); + final var database = context.getMetadataCollector().getDatabase(); + final var logicalIdentifier = database.toIdentifier( table ); + final var physicalIdentifier = + context.getBuildingOptions().getPhysicalNamingStrategy() + .toPhysicalTableName( logicalIdentifier, database.getJdbcEnvironment() ); setExplicitTableName( physicalIdentifier.render( database.getDialect() ) ); } } @@ -254,12 +252,12 @@ private static AnnotatedJoinColumn buildExplicitInheritanceJoinColumn( comment = joinColumn.comment(); } - final ObjectNameNormalizer normalizer = context.getObjectNameNormalizer(); + final var normalizer = context.getObjectNameNormalizer(); final String columnDef = columnDefinition.isBlank() ? null : normalizer.toDatabaseIdentifierText( columnDefinition ); final String logicalColumnName = normalizer.normalizeIdentifierQuotingAsString( columnName.isBlank() ? defaultColumnName : columnName ); - final AnnotatedJoinColumn column = new AnnotatedJoinColumn(); + final var column = new AnnotatedJoinColumn(); column.setSqlType( columnDef ); column.setLogicalColumnName( logicalColumnName ); column.setReferencedColumn( referencedColumnName ); @@ -279,8 +277,8 @@ private static AnnotatedJoinColumn buildImplicitInheritanceJoinColumn( AnnotatedJoinColumns parent, MetadataBuildingContext context, String defaultColumnName ) { - final AnnotatedJoinColumn column = new AnnotatedJoinColumn(); - final ObjectNameNormalizer normalizer = context.getObjectNameNormalizer(); + final var column = new AnnotatedJoinColumn(); + final var normalizer = context.getObjectNameNormalizer(); column.setLogicalColumnName( normalizer.normalizeIdentifierQuotingAsString( defaultColumnName ) ); // column.setPropertyHolder( propertyHolder ); // column.setJoins(joins); @@ -403,10 +401,11 @@ public void linkValueUsingAColumnCopy(Column column, SimpleValue value) { @Override protected void addColumnBinding(SimpleValue value) { if ( !getParent().hasMappedBy() ) { + final var context = getBuildingContext(); // was the column explicitly quoted in the mapping/annotation // TODO: in metamodel, we need to better split global quoting and explicit quoting w/ respect to logical names boolean isLogicalColumnQuoted = isQuoted( getLogicalColumnName() ); - final ObjectNameNormalizer normalizer = getBuildingContext().getObjectNameNormalizer(); + final var normalizer = context.getObjectNameNormalizer(); final String logicalColumnName = normalizer.normalizeIdentifierQuotingAsString( getLogicalColumnName() ); final String referencedColumn = normalizer.normalizeIdentifierQuotingAsString( getReferencedColumn() ); final String unquotedLogColName = unquote( logicalColumnName ); @@ -415,7 +414,7 @@ protected void addColumnBinding(SimpleValue value) { isNotEmpty( unquotedLogColName ) ? unquotedLogColName : getParent().getPropertyName() + '_' + unquotedRefColumn; - final InFlightMetadataCollector collector = getBuildingContext().getMetadataCollector(); + final var collector = context.getMetadataCollector(); final String logicalCollectionColumnName = collector.getDatabase().getJdbcEnvironment().getIdentifierHelper() .toIdentifier( collectionColName, isLogicalColumnQuoted ) @@ -471,9 +470,8 @@ static AnnotatedJoinColumn buildImplicitJoinTableJoinColumn( AnnotatedJoinColumns parent, PropertyHolder propertyHolder, PropertyData inferredData) { - final AnnotatedJoinColumn column = new AnnotatedJoinColumn(); + final var column = new AnnotatedJoinColumn(); column.setImplicit( true ); - // column.setPropertyHolder( propertyHolder ); // column.setPropertyName( getRelativePath( propertyHolder, propertyName ) ); // column.setJoins( secondaryTables ); @@ -489,7 +487,7 @@ static AnnotatedJoinColumn buildExplicitJoinTableJoinColumn( PropertyHolder propertyHolder, PropertyData inferredData, JoinColumn joinColumn) { - final AnnotatedJoinColumn column = new AnnotatedJoinColumn(); + final var column = new AnnotatedJoinColumn(); column.setImplicit( true ); // column.setPropertyHolder( propertyHolder ); // column.setPropertyName( getRelativePath( propertyHolder, propertyName ) ); @@ -505,7 +503,7 @@ static AnnotatedJoinColumn buildExplicitJoinTableJoinColumn( @Override public String toString() { - final StringBuilder string = new StringBuilder(); + final var string = new StringBuilder(); string.append( getClass().getSimpleName() ).append( "(" ); if ( isNotEmpty( getLogicalColumnName() ) ) { string.append( "column='" ).append( getLogicalColumnName() ).append( "'," ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedJoinColumns.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedJoinColumns.java index f2d0879e43ea..3ecc53d520c3 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedJoinColumns.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotatedJoinColumns.java @@ -25,16 +25,12 @@ import org.hibernate.boot.model.source.spi.AttributePath; import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.boot.spi.MetadataBuildingContext; -import org.hibernate.boot.spi.MetadataBuildingOptions; import org.hibernate.boot.spi.PropertyData; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; import org.hibernate.mapping.Column; import org.hibernate.mapping.Component; import org.hibernate.mapping.Join; -import org.hibernate.mapping.KeyValue; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; -import org.hibernate.mapping.Selectable; import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.Table; import org.hibernate.models.spi.MemberDetails; @@ -84,15 +80,15 @@ public static AnnotatedJoinColumns buildJoinColumnsOrFormulas( PropertyHolder propertyHolder, PropertyData inferredData, MetadataBuildingContext context) { - final AnnotatedJoinColumns parent = new AnnotatedJoinColumns(); + final var parent = new AnnotatedJoinColumns(); parent.setBuildingContext( context ); parent.setJoins( joins ); parent.setPropertyHolder( propertyHolder ); parent.setPropertyName( getRelativePath( propertyHolder, inferredData.getPropertyName() ) ); parent.setMappedBy( mappedBy ); - for ( JoinColumnOrFormula columnOrFormula : joinColumnOrFormulas ) { - final JoinFormula formula = columnOrFormula.formula(); - final JoinColumn column = columnOrFormula.column(); + for ( var columnOrFormula : joinColumnOrFormulas ) { + final var formula = columnOrFormula.formula(); + final var column = columnOrFormula.column(); final String annotationString = formula.value(); if ( isNotBlank( annotationString ) ) { AnnotatedJoinColumn.buildJoinFormula( formula, parent ); @@ -108,16 +104,15 @@ public static AnnotatedJoinColumns buildJoinColumnsOrFormulas( } private static void handlePropertyRef(MemberDetails attributeMember, AnnotatedJoinColumns parent) { - final PropertyRef propertyRefUsage = attributeMember.getDirectAnnotationUsage( PropertyRef.class ); - if ( propertyRefUsage == null ) { - return; - } - - final String referencedPropertyName = propertyRefUsage.value(); - if ( isBlank( referencedPropertyName ) ) { - throw new AnnotationException( "@PropertyRef did not specify target attribute name: " + attributeMember ); + final var propertyRefUsage = attributeMember.getDirectAnnotationUsage( PropertyRef.class ); + if ( propertyRefUsage != null ) { + final String referencedPropertyName = propertyRefUsage.value(); + if ( isBlank( referencedPropertyName ) ) { + throw new AnnotationException( + "@PropertyRef did not specify target attribute name: " + attributeMember ); + } + parent.referencedProperty = referencedPropertyName; } - parent.referencedProperty = referencedPropertyName; } static AnnotatedJoinColumns buildJoinColumnsWithFormula( @@ -126,7 +121,7 @@ static AnnotatedJoinColumns buildJoinColumnsWithFormula( PropertyHolder propertyHolder, PropertyData inferredData, MetadataBuildingContext context) { - final AnnotatedJoinColumns joinColumns = new AnnotatedJoinColumns(); + final var joinColumns = new AnnotatedJoinColumns(); joinColumns.setBuildingContext( context ); joinColumns.setJoins( secondaryTables ); joinColumns.setPropertyHolder( propertyHolder ); @@ -167,13 +162,12 @@ public static AnnotatedJoinColumns buildJoinColumnsWithDefaultColumnSuffix( final String path = qualify( propertyHolder.getPath(), propertyName ); final JoinColumn[] overrides = propertyHolder.getOverriddenJoinColumn( path ); final JoinColumn[] actualColumns = overrides == null ? joinColumns : overrides; - final AnnotatedJoinColumns parent = new AnnotatedJoinColumns(); + final var parent = new AnnotatedJoinColumns(); parent.setBuildingContext( context ); parent.setJoins( joins ); parent.setPropertyHolder( propertyHolder ); parent.setPropertyName( getRelativePath( propertyHolder, propertyName ) ); parent.setMappedBy( mappedBy ); - final MemberDetails memberDetails = inferredData.getAttributeMember(); if ( isEmpty( actualColumns ) ) { AnnotatedJoinColumn.buildJoinColumn( null, @@ -186,7 +180,7 @@ public static AnnotatedJoinColumns buildJoinColumnsWithDefaultColumnSuffix( } else { parent.setMappedBy( mappedBy ); - for ( JoinColumn actualColumn : actualColumns ) { + for ( var actualColumn : actualColumns ) { AnnotatedJoinColumn.buildJoinColumn( actualColumn, mappedBy, @@ -197,7 +191,7 @@ public static AnnotatedJoinColumns buildJoinColumnsWithDefaultColumnSuffix( ); } } - handlePropertyRef( memberDetails, parent ); + handlePropertyRef( inferredData.getAttributeMember(), parent ); return parent; } @@ -211,7 +205,7 @@ public static AnnotatedJoinColumns buildJoinTableJoinColumns( PropertyData inferredData, String mappedBy, MetadataBuildingContext context) { - final AnnotatedJoinColumns parent = new AnnotatedJoinColumns(); + final var parent = new AnnotatedJoinColumns(); parent.setBuildingContext( context ); parent.setJoins( secondaryTables ); parent.setPropertyHolder( propertyHolder ); @@ -221,7 +215,7 @@ public static AnnotatedJoinColumns buildJoinTableJoinColumns( AnnotatedJoinColumn.buildImplicitJoinTableJoinColumn( parent, propertyHolder, inferredData ); } else { - for ( JoinColumn joinColumn : joinColumns ) { + for ( var joinColumn : joinColumns ) { AnnotatedJoinColumn.buildExplicitJoinTableJoinColumn( parent, propertyHolder, inferredData, joinColumn ); } } @@ -230,8 +224,8 @@ public static AnnotatedJoinColumns buildJoinTableJoinColumns( } Property resolveMapsId() { - final PersistentClass persistentClass = getPropertyHolder().getPersistentClass(); - final KeyValue identifier = persistentClass.getIdentifier(); + final var persistentClass = getPropertyHolder().getPersistentClass(); + final var identifier = persistentClass.getIdentifier(); try { return identifier instanceof Component embeddedIdType ? embeddedIdType.getProperty( getMapsId() ) // an @EmbeddedId @@ -331,8 +325,9 @@ public ForeignKeyType getReferencedColumnsType(PersistentClass referencedEntity) return ForeignKeyType.IMPLICIT_PRIMARY_KEY_REFERENCE; //shortcut } - final AnnotatedJoinColumn firstColumn = columns.get( 0 ); - final Object columnOwner = findReferencedColumnOwner( referencedEntity, firstColumn, getBuildingContext() ); + final var firstColumn = columns.get( 0 ); + final var context = getBuildingContext(); + final Object columnOwner = findReferencedColumnOwner( referencedEntity, firstColumn, context ); if ( columnOwner == null ) { try { throw new MappingException( "A '@JoinColumn' references a column named '" @@ -348,14 +343,15 @@ public ForeignKeyType getReferencedColumnsType(PersistentClass referencedEntity) } final Table table = table( columnOwner ); // final List keyColumns = referencedEntity.getKey().getSelectables(); - final List keyColumns = table.getPrimaryKey() == null - ? referencedEntity.getKey().getSelectables() - : table.getPrimaryKey().getColumns(); + final var keyColumns = + table.getPrimaryKey() == null + ? referencedEntity.getKey().getSelectables() + : table.getPrimaryKey().getColumns(); boolean explicitColumnReference = false; - for ( AnnotatedJoinColumn column : columns ) { + for ( var column : columns ) { if ( !column.isReferenceImplicit() ) { explicitColumnReference = true; - if ( !keyColumns.contains( column( getBuildingContext(), table, column.getReferencedColumn() ) ) ) { + if ( !keyColumns.contains( column( context, table, column.getReferencedColumn() ) ) ) { // we have a column which does not belong to the PK return ForeignKeyType.NON_PRIMARY_KEY_REFERENCE; } @@ -399,10 +395,10 @@ private static Column column(MetadataBuildingContext context, Table table, Strin } String buildDefaultColumnName(PersistentClass referencedEntity, String logicalReferencedColumn) { - final MetadataBuildingOptions options = getBuildingContext().getBuildingOptions(); - final InFlightMetadataCollector collector = getBuildingContext().getMetadataCollector(); - final Database database = collector.getDatabase(); - final JdbcEnvironment jdbcEnvironment = database.getJdbcEnvironment(); + final var options = getBuildingContext().getBuildingOptions(); + final var collector = getBuildingContext().getMetadataCollector(); + final var database = collector.getDatabase(); + final var jdbcEnvironment = database.getJdbcEnvironment(); final Identifier columnIdentifier = columnIdentifier( referencedEntity, logicalReferencedColumn, @@ -596,7 +592,7 @@ public Identifier getReferencedColumnName() { final Property mappedByProperty = collector.getEntityBinding( getMappedByEntityName() ) .getProperty( getMappedByPropertyName() ); - final SimpleValue value = (SimpleValue) mappedByProperty.getValue(); + final var value = (SimpleValue) mappedByProperty.getValue(); if ( value.getSelectables().isEmpty() ) { throw new AnnotationException( String.format( @@ -608,8 +604,7 @@ public Identifier getReferencedColumnName() { ) ); } - final Selectable selectable = value.getSelectables().get( 0 ); - if ( !(selectable instanceof Column column) ) { + if ( !(value.getSelectables().get( 0 ) instanceof Column column) ) { throw new AnnotationException( String.format( Locale.ENGLISH, diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotationBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotationBinder.java index 47035204d9cf..f1b2ccb51473 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotationBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotationBinder.java @@ -18,7 +18,6 @@ import org.hibernate.annotations.EmbeddableInstantiatorRegistration; import org.hibernate.annotations.FetchMode; import org.hibernate.annotations.FetchProfile; -import org.hibernate.annotations.FetchProfile.FetchOverride; import org.hibernate.annotations.Imported; import org.hibernate.annotations.JavaTypeRegistration; import org.hibernate.annotations.JdbcTypeRegistration; @@ -28,9 +27,7 @@ import org.hibernate.boot.model.convert.spi.RegisteredConversion; import org.hibernate.boot.models.HibernateAnnotations; import org.hibernate.boot.models.JpaAnnotations; -import org.hibernate.boot.models.spi.GlobalRegistrations; import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; -import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.models.spi.AnnotationTarget; @@ -71,8 +68,8 @@ public final class AnnotationBinder { private AnnotationBinder() {} public static void bindDefaults(MetadataBuildingContext context) { - final InFlightMetadataCollector metadataCollector = context.getMetadataCollector(); - final GlobalRegistrations globalRegistrations = metadataCollector.getGlobalRegistrations(); + final var metadataCollector = context.getMetadataCollector(); + final var globalRegistrations = metadataCollector.getGlobalRegistrations(); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -130,29 +127,28 @@ private static ModelsContext modelsContext(MetadataBuildingContext context) { public static void bindPackage(ClassLoaderService cls, String packageName, MetadataBuildingContext context) { final Package pack = cls.packageForNameOrNull( packageName ); - if ( pack == null ) { - return; - } - final ClassDetails packageInfoClassDetails = - modelsContext( context ).getClassDetailsRegistry() - .resolveClassDetails( pack.getName() + ".package-info" ); + if ( pack != null ) { + final var packageInfo = + modelsContext( context ).getClassDetailsRegistry() + .resolveClassDetails( pack.getName() + ".package-info" ); - GeneratorBinder.registerGlobalGenerators( packageInfoClassDetails, context ); + GeneratorBinder.registerGlobalGenerators( packageInfo, context ); - bindTypeDescriptorRegistrations( packageInfoClassDetails, context ); - bindEmbeddableInstantiatorRegistrations( packageInfoClassDetails, context ); - bindUserTypeRegistrations( packageInfoClassDetails, context ); - bindCompositeUserTypeRegistrations( packageInfoClassDetails, context ); - bindConverterRegistrations( packageInfoClassDetails, context ); + bindTypeDescriptorRegistrations( packageInfo, context ); + bindEmbeddableInstantiatorRegistrations( packageInfo, context ); + bindUserTypeRegistrations( packageInfo, context ); + bindCompositeUserTypeRegistrations( packageInfo, context ); + bindConverterRegistrations( packageInfo, context ); - bindQueries( packageInfoClassDetails, context ); - bindFilterDefs( packageInfoClassDetails, context ); + bindQueries( packageInfo, context ); + bindFilterDefs( packageInfo, context ); - bindNamedEntityGraphs( packageInfoClassDetails, context ); + bindNamedEntityGraphs( packageInfo, context ); + } } private static void bindNamedEntityGraphs(ClassDetails packageInfoClassDetails, MetadataBuildingContext context) { - final InFlightMetadataCollector collector = context.getMetadataCollector(); + final var collector = context.getMetadataCollector(); packageInfoClassDetails.forEachRepeatedAnnotationUsages( HibernateAnnotations.NAMED_ENTITY_GRAPH, modelsContext( context ), @@ -170,7 +166,7 @@ public static void bindQueries(AnnotationTarget annotationTarget, MetadataBuildi } private static void bindNamedHibernateQueries(AnnotationTarget annotationTarget, MetadataBuildingContext context) { - final ModelsContext sourceModelContext = modelsContext( context ); + final var sourceModelContext = modelsContext( context ); annotationTarget.forEachRepeatedAnnotationUsages( HibernateAnnotations.NAMED_QUERY, @@ -186,7 +182,7 @@ private static void bindNamedHibernateQueries(AnnotationTarget annotationTarget, } private static void bindNamedJpaQueries(AnnotationTarget annotationTarget, MetadataBuildingContext context) { - final ModelsContext sourceModelContext = modelsContext( context ); + final var sourceModelContext = modelsContext( context ); annotationTarget.forEachRepeatedAnnotationUsages( JpaAnnotations.SQL_RESULT_SET_MAPPING, @@ -274,10 +270,9 @@ private static void detectMappedSuperclassProblems(ClassDetails annotatedClass) private static void bindTypeDescriptorRegistrations( AnnotationTarget annotatedElement, MetadataBuildingContext context) { - final ManagedBeanRegistry managedBeanRegistry = - context.getBootstrapContext().getManagedBeanRegistry(); + final var managedBeanRegistry = context.getBootstrapContext().getManagedBeanRegistry(); - final ModelsContext sourceModelContext = modelsContext( context ); + final var sourceModelContext = modelsContext( context ); annotatedElement.forEachAnnotationUsage( JavaTypeRegistration.class, sourceModelContext, (usage) -> { handleJavaTypeRegistration( context, managedBeanRegistry, usage ); @@ -403,7 +398,7 @@ public static void bindFetchProfilesForClass(AnnotationTarget annotatedClass, Me } public static void bindFetchProfilesForPackage(String packageName, MetadataBuildingContext context) { - final ClassDetails packageInfoClassDetails = + final var packageInfoClassDetails = context.getMetadataCollector().getClassDetailsRegistry() .findClassDetails( packageName + ".package-info" ); if ( packageInfoClassDetails != null ) { @@ -420,8 +415,7 @@ private static void bindFetchProfiles(AnnotationTarget annotatedElement, Metadat private static void bindFetchProfile(FetchProfile fetchProfile, MetadataBuildingContext context) { final String name = fetchProfile.name(); if ( reuseOrCreateFetchProfile( context, name ) ) { - final FetchOverride[] fetchOverrides = fetchProfile.fetchOverrides(); - for ( FetchOverride fetchOverride : fetchOverrides ) { + for ( var fetchOverride : fetchProfile.fetchOverrides() ) { final FetchType type = fetchOverride.fetch(); final FetchMode mode = fetchOverride.mode(); if ( type == FetchType.LAZY && mode == FetchMode.JOIN ) { @@ -441,11 +435,11 @@ private static void bindFetchProfile(FetchProfile fetchProfile, MetadataBuilding private static boolean reuseOrCreateFetchProfile(MetadataBuildingContext context, String name) { // We tolerate multiple @FetchProfile annotations for same named profile - var existing = context.getMetadataCollector().getFetchProfile( name ); + final var collector = context.getMetadataCollector(); + var existing = collector.getFetchProfile( name ); if ( existing == null ) { // no existing profile, so create a new one - context.getMetadataCollector() - .addFetchProfile( new org.hibernate.mapping.FetchProfile( name, ANNOTATIONS ) ); + collector.addFetchProfile( new org.hibernate.mapping.FetchProfile( name, ANNOTATIONS ) ); return true; } else { @@ -465,11 +459,11 @@ public static Map buildInheritanceStates( List orderedClasses, MetadataBuildingContext buildingContext) { final Map inheritanceStatePerClass = new HashMap<>( orderedClasses.size() ); - final InFlightMetadataCollector collector = buildingContext.getMetadataCollector(); + final var collector = buildingContext.getMetadataCollector(); for ( ClassDetails clazz : orderedClasses ) { - final InheritanceState superclassState = getSuperclassInheritanceState( clazz, inheritanceStatePerClass ); - final InheritanceState state = new InheritanceState( clazz, inheritanceStatePerClass, buildingContext ); - final AnnotatedClassType classType = collector.getClassType( clazz ); + final var superclassState = getSuperclassInheritanceState( clazz, inheritanceStatePerClass ); + final var state = new InheritanceState( clazz, inheritanceStatePerClass, buildingContext ); + final var classType = collector.getClassType( clazz ); if ( classType == EMBEDDABLE && !clazz.hasDirectAnnotationUsage( Imported.class ) ) { final String className = clazz.getName(); collector.addImport( unqualify( className ), className ); @@ -477,8 +471,7 @@ public static Map buildInheritanceStates( if ( superclassState != null ) { //the classes are ordered thus preventing an NPE superclassState.setHasSiblings( true ); - final InheritanceState superEntityState = - getInheritanceStateOfSuperEntity( clazz, inheritanceStatePerClass ); + final var superEntityState = getInheritanceStateOfSuperEntity( clazz, inheritanceStatePerClass ); if ( superEntityState != null ) { state.setHasParents( true ); if ( classType == EMBEDDABLE ) { diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotationHelper.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotationHelper.java index 84bdd534a2d5..a2f4d4141df5 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotationHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnnotationHelper.java @@ -8,7 +8,6 @@ import org.hibernate.annotations.Parameter; import org.hibernate.boot.model.convert.spi.ConverterDescriptor; -import org.hibernate.boot.spi.BootstrapContext; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.dialect.Dialect; import org.hibernate.metamodel.mapping.JdbcMapping; @@ -16,9 +15,7 @@ import org.hibernate.resource.beans.spi.ManagedBean; import org.hibernate.type.BasicType; import org.hibernate.type.CustomType; -import org.hibernate.type.descriptor.converter.spi.JpaAttributeConverter; import org.hibernate.type.descriptor.java.JavaType; -import org.hibernate.type.descriptor.java.spi.JavaTypeRegistry; import org.hibernate.type.descriptor.jdbc.JdbcType; import org.hibernate.type.descriptor.jdbc.JdbcTypeIndicators; import org.hibernate.type.internal.ConvertedBasicTypeImpl; @@ -36,14 +33,14 @@ public class AnnotationHelper { public static HashMap extractParameterMap(Parameter[] parameters) { final HashMap paramMap = mapOfSize( parameters.length ); - for ( Parameter parameter : parameters ) { + for ( var parameter : parameters ) { paramMap.put( parameter.name(), parameter.value() ); } return paramMap; } public static JdbcMapping resolveUserType(Class> userTypeClass, MetadataBuildingContext context) { - final BootstrapContext bootstrapContext = context.getBootstrapContext(); + final var bootstrapContext = context.getBootstrapContext(); final UserType userType = context.getBuildingOptions().isAllowExtensionsInCdi() ? bootstrapContext.getManagedBeanRegistry().getBean( userTypeClass ).getBeanInstance() @@ -54,13 +51,13 @@ public static JdbcMapping resolveUserType(Class> userTypeClass, Meta public static JdbcMapping resolveAttributeConverter( Class> type, MetadataBuildingContext context) { - final BootstrapContext bootstrapContext = context.getBootstrapContext(); - final TypeConfiguration typeConfiguration = bootstrapContext.getTypeConfiguration(); + final var bootstrapContext = context.getBootstrapContext(); + final var typeConfiguration = bootstrapContext.getTypeConfiguration(); final var bean = bootstrapContext.getManagedBeanRegistry().getBean( type ); @SuppressWarnings("unchecked") final var castBean = (ManagedBean>) bean; - final JavaTypeRegistry registry = typeConfiguration.getJavaTypeRegistry(); - final JpaAttributeConverter valueConverter = createJpaAttributeConverter( castBean, registry ); + final var registry = typeConfiguration.getJavaTypeRegistry(); + final var valueConverter = createJpaAttributeConverter( castBean, registry ); return new ConvertedBasicTypeImpl<>( ConverterDescriptor.TYPE_NAME_PREFIX + valueConverter.getConverterJavaType().getTypeName(), @@ -76,8 +73,8 @@ public static JdbcMapping resolveAttributeConverter( } public static BasicType resolveBasicType(Class type, MetadataBuildingContext context) { - final TypeConfiguration typeConfiguration = context.getBootstrapContext().getTypeConfiguration(); - final JavaType jtd = typeConfiguration.getJavaTypeRegistry().findDescriptor( type ); + final var typeConfiguration = context.getBootstrapContext().getTypeConfiguration(); + final var jtd = typeConfiguration.getJavaTypeRegistry().findDescriptor( type ); if ( jtd != null ) { final JdbcType jdbcType = jtd.getRecommendedJdbcType( new JdbcTypeIndicators() { @@ -125,9 +122,9 @@ public Dialect getDialect() { } public static JdbcMapping resolveJavaType(Class> type, MetadataBuildingContext context) { - final TypeConfiguration typeConfiguration = context.getBootstrapContext().getTypeConfiguration(); - final JavaType jtd = getJavaType( type, context, typeConfiguration ); - final JdbcType jdbcType = jtd.getRecommendedJdbcType( typeConfiguration.getCurrentBaseSqlTypeIndicators() ); + final var typeConfiguration = context.getBootstrapContext().getTypeConfiguration(); + final var jtd = getJavaType( type, context, typeConfiguration ); + final var jdbcType = jtd.getRecommendedJdbcType( typeConfiguration.getCurrentBaseSqlTypeIndicators() ); return typeConfiguration.getBasicTypeRegistry().resolve( jtd, jdbcType ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnyBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnyBinder.java index e450604b0031..86fdc4371061 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnyBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AnyBinder.java @@ -9,7 +9,6 @@ import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; -import org.hibernate.annotations.AnyDiscriminator; import org.hibernate.annotations.AnyDiscriminatorImplicitValues; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; @@ -25,11 +24,9 @@ import org.hibernate.metamodel.internal.FullNameImplicitDiscriminatorStrategy; import org.hibernate.metamodel.internal.ShortNameImplicitDiscriminatorStrategy; import org.hibernate.metamodel.spi.ImplicitDiscriminatorStrategy; -import org.hibernate.models.spi.MemberDetails; import jakarta.persistence.Column; import jakarta.persistence.FetchType; -import jakarta.persistence.JoinTable; import static org.hibernate.boot.model.internal.BinderHelper.aggregateCascadeTypes; import static org.hibernate.boot.model.internal.DialectOverridesAnnotationHelper.getOverridableAnnotation; @@ -45,10 +42,10 @@ static void bindAny( boolean isIdentifierMapper, MetadataBuildingContext context, AnnotatedJoinColumns joinColumns) { - final MemberDetails property = inferredData.getAttributeMember(); + final var memberDetails = inferredData.getAttributeMember(); //check validity - if ( property.hasDirectAnnotationUsage( Columns.class ) ) { + if ( memberDetails.hasDirectAnnotationUsage( Columns.class ) ) { throw new AnnotationException( String.format( Locale.ROOT, @@ -59,9 +56,9 @@ static void bindAny( ); } - final Cascade hibernateCascade = property.getDirectAnnotationUsage( Cascade.class ); - final OnDelete onDeleteAnn = property.getDirectAnnotationUsage( OnDelete.class ); - final JoinTable assocTable = propertyHolder.getJoinTable( property ); + final var hibernateCascade = memberDetails.getDirectAnnotationUsage( Cascade.class ); + final var onDeleteAnn = memberDetails.getDirectAnnotationUsage( OnDelete.class ); + final var assocTable = propertyHolder.getJoinTable( memberDetails ); if ( assocTable != null ) { final Join join = propertyHolder.addJoin( assocTable, false ); for ( AnnotatedJoinColumn joinColumn : joinColumns.getJoinColumns() ) { @@ -92,8 +89,8 @@ private static void bindAny( EntityBinder entityBinder, boolean isIdentifierMapper, MetadataBuildingContext context) { - final MemberDetails property = inferredData.getAttributeMember(); - final org.hibernate.annotations.Any any = property.getDirectAnnotationUsage( org.hibernate.annotations.Any.class ); + final var memberDetails = inferredData.getAttributeMember(); + final var any = memberDetails.getDirectAnnotationUsage( org.hibernate.annotations.Any.class ); if ( any == null ) { throw new AssertionFailure( "Missing @Any annotation: " + getPath( propertyHolder, inferredData ) ); } @@ -101,8 +98,8 @@ private static void bindAny( final boolean lazy = any.fetch() == FetchType.LAZY; final boolean optional = any.optional(); final Any value = BinderHelper.buildAnyValue( - property.getDirectAnnotationUsage( Column.class ), - getOverridableAnnotation( property, Formula.class, context ), + memberDetails.getDirectAnnotationUsage( Column.class ), + getOverridableAnnotation( memberDetails, Formula.class, context ), columns, inferredData, onDeleteAction, @@ -114,13 +111,14 @@ private static void bindAny( context ); - final AnyDiscriminator anyDiscriminator = property.getDirectAnnotationUsage( AnyDiscriminator.class ); - final AnyDiscriminatorImplicitValues anyDiscriminatorImplicitValues = property.getDirectAnnotationUsage( AnyDiscriminatorImplicitValues.class ); + final var anyDiscriminatorImplicitValues = + memberDetails.getDirectAnnotationUsage( AnyDiscriminatorImplicitValues.class ); if ( anyDiscriminatorImplicitValues != null ) { - value.setImplicitDiscriminatorValueStrategy( resolveImplicitDiscriminatorStrategy( anyDiscriminatorImplicitValues, context ) ); + value.setImplicitDiscriminatorValueStrategy( + resolveImplicitDiscriminatorStrategy( anyDiscriminatorImplicitValues, context ) ); } - final PropertyBinder binder = new PropertyBinder(); + final var binder = new PropertyBinder(); binder.setName( inferredData.getPropertyName() ); binder.setValue( value ); binder.setLazy( lazy ); @@ -133,7 +131,7 @@ private static void bindAny( binder.setCascade( cascadeStrategy ); binder.setBuildingContext( context ); binder.setHolder( propertyHolder ); - binder.setMemberDetails( property ); + binder.setMemberDetails( memberDetails ); binder.setEntityBinder( entityBinder ); Property prop = binder.makeProperty(); prop.setOptional( optional && value.isNullable() ); @@ -145,32 +143,25 @@ private static void bindAny( public static ImplicitDiscriminatorStrategy resolveImplicitDiscriminatorStrategy( AnyDiscriminatorImplicitValues anyDiscriminatorImplicitValues, MetadataBuildingContext context) { - final AnyDiscriminatorImplicitValues.Strategy strategy = anyDiscriminatorImplicitValues.value(); - - if ( strategy == AnyDiscriminatorImplicitValues.Strategy.FULL_NAME ) { - return FullNameImplicitDiscriminatorStrategy.FULL_NAME_STRATEGY; - } - - if ( strategy == AnyDiscriminatorImplicitValues.Strategy.SHORT_NAME ) { - return ShortNameImplicitDiscriminatorStrategy.SHORT_NAME_STRATEGY; - } - - assert strategy == AnyDiscriminatorImplicitValues.Strategy.CUSTOM; - - final Class customStrategy = anyDiscriminatorImplicitValues.implementation(); - - if ( ImplicitDiscriminatorStrategy.class.equals( customStrategy ) ) { - return null; - } - - if ( FullNameImplicitDiscriminatorStrategy.class.equals( customStrategy ) ) { - return FullNameImplicitDiscriminatorStrategy.FULL_NAME_STRATEGY; - } - - if ( ShortNameImplicitDiscriminatorStrategy.class.equals( customStrategy ) ) { - return ShortNameImplicitDiscriminatorStrategy.SHORT_NAME_STRATEGY; - } - - return context.getBootstrapContext().getCustomTypeProducer().produceBeanInstance( customStrategy ); + return switch ( anyDiscriminatorImplicitValues.value() ) { + case FULL_NAME -> FullNameImplicitDiscriminatorStrategy.FULL_NAME_STRATEGY; + case SHORT_NAME -> ShortNameImplicitDiscriminatorStrategy.SHORT_NAME_STRATEGY; + case CUSTOM -> { + final var customStrategy = anyDiscriminatorImplicitValues.implementation(); + if ( ImplicitDiscriminatorStrategy.class.equals( customStrategy ) ) { + yield null; + } + else if ( FullNameImplicitDiscriminatorStrategy.class.equals( customStrategy ) ) { + yield FullNameImplicitDiscriminatorStrategy.FULL_NAME_STRATEGY; + } + else if ( ShortNameImplicitDiscriminatorStrategy.class.equals( customStrategy ) ) { + yield ShortNameImplicitDiscriminatorStrategy.SHORT_NAME_STRATEGY; + } + else { + yield context.getBootstrapContext().getCustomTypeProducer() + .produceBeanInstance( customStrategy ); + } + } + }; } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BasicValueBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BasicValueBinder.java index 86123b42ac2d..e950c3256743 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BasicValueBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BasicValueBinder.java @@ -40,21 +40,17 @@ import org.hibernate.mapping.Component; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Table; -import org.hibernate.models.spi.ClassDetails; import org.hibernate.models.spi.MemberDetails; import org.hibernate.models.spi.ModelsContext; import org.hibernate.models.spi.TypeDetails; import org.hibernate.resource.beans.internal.FallbackBeanInstanceProducer; import org.hibernate.resource.beans.spi.ManagedBeanRegistry; -import org.hibernate.type.BasicType; import org.hibernate.type.descriptor.java.BasicJavaType; import org.hibernate.type.descriptor.java.Immutability; import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan; -import org.hibernate.type.descriptor.java.JavaType; import org.hibernate.type.descriptor.java.MutabilityPlan; import org.hibernate.type.descriptor.jdbc.JdbcType; import org.hibernate.type.descriptor.jdbc.JdbcTypeIndicators; -import org.hibernate.type.descriptor.jdbc.spi.JdbcTypeRegistry; import org.hibernate.type.internal.ParameterizedTypeImpl; import org.hibernate.type.spi.TypeConfiguration; import org.hibernate.usertype.DynamicParameterizedType; @@ -63,7 +59,6 @@ import java.lang.annotation.Annotation; import java.util.Collection; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.function.Function; @@ -185,9 +180,9 @@ public boolean isLob() { } if ( explicitJdbcTypeAccess != null ) { - final JdbcType type = explicitJdbcTypeAccess.apply( getTypeConfiguration() ); - if ( type != null ) { - return type.isLob(); + final var jdbcType = explicitJdbcTypeAccess.apply( getTypeConfiguration() ); + if ( jdbcType != null ) { + return jdbcType.isLob(); } } return false; @@ -252,8 +247,8 @@ public boolean isNationalized() { return true; } else if ( explicitJdbcTypeAccess != null ) { - final JdbcType type = explicitJdbcTypeAccess.apply( getTypeConfiguration() ); - return type != null && type.isNationalized(); + final var jdbcType = explicitJdbcTypeAccess.apply( getTypeConfiguration() ); + return jdbcType != null && jdbcType.isNationalized(); } else { return false; @@ -318,33 +313,35 @@ public void setType( // throw new AssertionFailure( "Expecting just one column, but found `" + Arrays.toString( columns ) + "`" ); // } - final TypeDetails modelClassDetails = isArray ? value.getElementType() : typeDetails; + final var modelClassDetails = isArray ? value.getElementType() : typeDetails; if ( kind != Kind.LIST_INDEX && kind != Kind.MAP_KEY ) { isLob = value.hasDirectAnnotationUsage( Lob.class ); } + final var modelContext = getSourceModelContext(); + if ( getDialect().getNationalizationSupport() == NationalizationSupport.EXPLICIT ) { isNationalized = buildingContext.getBuildingOptions().useNationalizedCharacterData() - || value.locateAnnotationUsage( Nationalized.class, getSourceModelContext() ) != null; + || value.locateAnnotationUsage( Nationalized.class, modelContext ) != null; } if ( converterDescriptor != null ) { applyJpaConverter( value, converterDescriptor ); } - final Class> userTypeImpl = - kind.mappingAccess.customType( value, getSourceModelContext() ); + final var userTypeImpl = + kind.mappingAccess.customType( value, modelContext ); if ( userTypeImpl != null ) { applyExplicitType( userTypeImpl, - kind.mappingAccess.customTypeParameters( value, getSourceModelContext() ) ); + kind.mappingAccess.customTypeParameters( value, modelContext ) ); // An explicit custom UserType has top precedence when we get to BasicValue resolution. return; } else if ( modelClassDetails != null ) { - final ClassDetails rawClassDetails = modelClassDetails.determineRawClass(); - final Class basicClass = rawClassDetails.toJavaClass(); - final Class> registeredUserTypeImpl = + final var rawClassDetails = modelClassDetails.determineRawClass(); + final var basicClass = rawClassDetails.toJavaClass(); + final var registeredUserTypeImpl = getMetadataCollector().findRegisteredUserType( basicClass ); if ( registeredUserTypeImpl != null ) { applyExplicitType( registeredUserTypeImpl, emptyMap() ); @@ -386,41 +383,32 @@ private void applyExplicitType(Class> impl, Map null; + final var modelContext = getSourceModelContext(); + explicitJavaTypeAccess = typeConfiguration -> { - final CollectionIdJavaClass javaClassAnn = attribute.locateAnnotationUsage( - CollectionIdJavaClass.class, - getSourceModelContext() - ); - if ( javaClassAnn != null ) { - return (BasicJavaType) buildingContext - .getBootstrapContext() - .getTypeConfiguration() - .getJavaTypeRegistry() - .getDescriptor( javaClassAnn.idType() ); + final var idJavaClass = attribute.locateAnnotationUsage( CollectionIdJavaClass.class, modelContext ); + if ( idJavaClass != null ) { + return (BasicJavaType) + buildingContext.getBootstrapContext().getTypeConfiguration() + .getJavaTypeRegistry().getDescriptor( idJavaClass.idType() ); } - final CollectionIdJavaType javaTypeAnn = attribute.locateAnnotationUsage( - CollectionIdJavaType.class, - getSourceModelContext() - ); - if ( javaTypeAnn != null ) { - final Class> javaTypeClass = javaTypeAnn.value(); - if ( javaTypeClass != null ) { - if ( useDeferredBeanContainerAccess ) { - return FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( javaTypeClass ); - } - else { - return beanRegistry.getBean( javaTypeClass ).getBeanInstance(); - } + final var idJavaType = attribute.locateAnnotationUsage( CollectionIdJavaType.class, modelContext ); + if ( idJavaType != null ) { + final var basicJavaTypeClass = idJavaType.value(); + if ( basicJavaTypeClass != null ) { + return useDeferredBeanContainerAccess + ? FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( basicJavaTypeClass ) + : beanRegistry.getBean( basicJavaTypeClass ).getBeanInstance(); } } @@ -428,24 +416,19 @@ private void prepareCollectionId(MemberDetails attribute) { }; explicitJdbcTypeAccess = typeConfiguration -> { - final CollectionIdJdbcType jdbcTypeAnn = - attribute.locateAnnotationUsage( CollectionIdJdbcType.class, getSourceModelContext() ); - if ( jdbcTypeAnn != null ) { - final Class jdbcTypeClass = jdbcTypeAnn.value(); + final var idJdbcType = attribute.locateAnnotationUsage( CollectionIdJdbcType.class, modelContext ); + if ( idJdbcType != null ) { + final var jdbcTypeClass = idJdbcType.value(); if ( jdbcTypeClass != null ) { - if ( useDeferredBeanContainerAccess ) { - return FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( jdbcTypeClass ); - } - else { - return beanRegistry.getBean( jdbcTypeClass ).getBeanInstance(); - } + return useDeferredBeanContainerAccess + ? FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( jdbcTypeClass ) + : beanRegistry.getBean( jdbcTypeClass ).getBeanInstance(); } } - final CollectionIdJdbcTypeCode jdbcTypeCodeAnn = - attribute.locateAnnotationUsage( CollectionIdJdbcTypeCode.class, getSourceModelContext() ); - if ( jdbcTypeCodeAnn != null ) { - final int code = jdbcTypeCodeAnn.value(); + final var idJdbcTypeCode = attribute.locateAnnotationUsage( CollectionIdJdbcTypeCode.class, modelContext ); + if ( idJdbcTypeCode != null ) { + final int code = idJdbcTypeCode.value(); if ( code != Integer.MIN_VALUE ) { return getDescriptor( typeConfiguration, code ); } @@ -455,10 +438,9 @@ private void prepareCollectionId(MemberDetails attribute) { }; explicitMutabilityAccess = typeConfiguration -> { - final CollectionIdMutability mutabilityAnn = - attribute.locateAnnotationUsage( CollectionIdMutability.class, getSourceModelContext() ); - if ( mutabilityAnn != null ) { - final Class> mutabilityClass = mutabilityAnn.value(); + final var idMutability = attribute.locateAnnotationUsage( CollectionIdMutability.class, modelContext ); + if ( idMutability != null ) { + final var mutabilityClass = idMutability.value(); if ( mutabilityClass != null ) { return resolveMutability( mutabilityClass ); } @@ -466,14 +448,12 @@ private void prepareCollectionId(MemberDetails attribute) { // see if the value's type Class is annotated with mutability-related annotations if ( implicitJavaTypeAccess != null ) { - final Class attributeType = - ReflectHelper.getClass( implicitJavaTypeAccess.apply( typeConfiguration ) ); + final var attributeType = ReflectHelper.getClass( implicitJavaTypeAccess.apply( typeConfiguration ) ); if ( attributeType != null ) { - final Mutability attributeTypeMutabilityAnn = attributeType.getAnnotation( Mutability.class ); - if ( attributeTypeMutabilityAnn != null ) { - return resolveMutability( attributeTypeMutabilityAnn.value() ); + final var attributeTypeMutability = attributeType.getAnnotation( Mutability.class ); + if ( attributeTypeMutability != null ) { + return resolveMutability( attributeTypeMutability.value() ); } - if ( attributeType.isAnnotationPresent( Immutable.class ) ) { return ImmutableMutabilityPlan.instance(); } @@ -482,26 +462,23 @@ private void prepareCollectionId(MemberDetails attribute) { // if there is a converter, check it for mutability-related annotations if ( converterDescriptor != null ) { - final Mutability converterMutabilityAnn = - converterDescriptor.getAttributeConverterClass().getAnnotation( Mutability.class ); - if ( converterMutabilityAnn != null ) { - return resolveMutability( converterMutabilityAnn.value() ); + final var attributeConverterClass = converterDescriptor.getAttributeConverterClass(); + final var converterMutability = attributeConverterClass.getAnnotation( Mutability.class ); + if ( converterMutability != null ) { + return resolveMutability( converterMutability.value() ); } - - if ( converterDescriptor.getAttributeConverterClass().isAnnotationPresent( Immutable.class ) ) { + if ( attributeConverterClass.isAnnotationPresent( Immutable.class ) ) { return ImmutableMutabilityPlan.instance(); } } // if there is a UserType, see if its Class is annotated with mutability-related annotations - final Class> customTypeImpl = - Kind.ATTRIBUTE.mappingAccess.customType( attribute, getSourceModelContext() ); + final var customTypeImpl = Kind.ATTRIBUTE.mappingAccess.customType( attribute, modelContext ); if ( customTypeImpl != null ) { - final Mutability customTypeMutabilityAnn = customTypeImpl.getAnnotation( Mutability.class ); - if ( customTypeMutabilityAnn != null ) { - return resolveMutability( customTypeMutabilityAnn.value() ); + final var customTypeMutability = customTypeImpl.getAnnotation( Mutability.class ); + if ( customTypeMutability != null ) { + return resolveMutability( customTypeMutability.value() ); } - if ( customTypeImpl.isAnnotationPresent( Immutable.class ) ) { return ImmutableMutabilityPlan.instance(); } @@ -523,47 +500,39 @@ private ManagedBeanRegistry getManagedBeanRegistry() { private void prepareMapKey( MemberDetails attribute, TypeDetails explicitMapKeyTypeDetails) { - final TypeDetails mapKeyClass = + final var mapKeyClass = explicitMapKeyTypeDetails == null ? attribute.getMapKeyType() : explicitMapKeyTypeDetails; - implicitJavaTypeAccess = typeConfiguration -> { - final ClassDetails rawKeyClassDetails = mapKeyClass.determineRawClass(); - return rawKeyClassDetails.toJavaClass(); - }; + implicitJavaTypeAccess = typeConfiguration -> mapKeyClass.determineRawClass().toJavaClass(); - final MapKeyEnumerated mapKeyEnumeratedAnn = - attribute.getDirectAnnotationUsage( MapKeyEnumerated.class ); - if ( mapKeyEnumeratedAnn != null ) { - enumType = mapKeyEnumeratedAnn.value(); + final var mapKeyEnumerated = attribute.getDirectAnnotationUsage( MapKeyEnumerated.class ); + if ( mapKeyEnumerated != null ) { + enumType = mapKeyEnumerated.value(); } //noinspection deprecation - final MapKeyTemporal mapKeyTemporalAnn = - attribute.getDirectAnnotationUsage( MapKeyTemporal.class ); - if ( mapKeyTemporalAnn != null ) { - temporalPrecision = mapKeyTemporalAnn.value(); + final var mapKeyTemporal = attribute.getDirectAnnotationUsage( MapKeyTemporal.class ); + if ( mapKeyTemporal != null ) { + temporalPrecision = mapKeyTemporal.value(); } final boolean useDeferredBeanContainerAccess = useDeferredBeanContainerAccess(); + final var modelContext = getSourceModelContext(); + explicitJdbcTypeAccess = typeConfiguration -> { - final MapKeyJdbcType jdbcTypeAnn = - attribute.locateAnnotationUsage( MapKeyJdbcType.class, getSourceModelContext() ); - if ( jdbcTypeAnn != null ) { - final Class jdbcTypeClass = jdbcTypeAnn.value(); + final var mapKeyJdbcType = attribute.locateAnnotationUsage( MapKeyJdbcType.class, modelContext ); + if ( mapKeyJdbcType != null ) { + final var jdbcTypeClass = mapKeyJdbcType.value(); if ( jdbcTypeClass != null ) { - if ( useDeferredBeanContainerAccess ) { - return FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( jdbcTypeClass ); - } - else { - return getManagedBeanRegistry().getBean( jdbcTypeClass ).getBeanInstance(); - } + return useDeferredBeanContainerAccess + ? FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( jdbcTypeClass ) + : getManagedBeanRegistry().getBean( jdbcTypeClass ).getBeanInstance(); } } - final MapKeyJdbcTypeCode jdbcTypeCodeAnn = - attribute.locateAnnotationUsage( MapKeyJdbcTypeCode.class, getSourceModelContext() ); + final var jdbcTypeCodeAnn = attribute.locateAnnotationUsage( MapKeyJdbcTypeCode.class, modelContext ); if ( jdbcTypeCodeAnn != null ) { final int jdbcTypeCode = jdbcTypeCodeAnn.value(); if ( jdbcTypeCode != Integer.MIN_VALUE ) { @@ -575,21 +544,17 @@ private void prepareMapKey( }; explicitJavaTypeAccess = typeConfiguration -> { - final MapKeyJavaType javaTypeAnn = - attribute.locateAnnotationUsage( MapKeyJavaType.class, getSourceModelContext() ); - if ( javaTypeAnn != null ) { - final Class> javaTypeClass = javaTypeAnn.value(); - if ( javaTypeClass != null ) { - if ( useDeferredBeanContainerAccess ) { - return FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( javaTypeClass ); - } - else { - return getManagedBeanRegistry().getBean( javaTypeClass ).getBeanInstance(); - } + final var mapKeyJavaType = attribute.locateAnnotationUsage( MapKeyJavaType.class, modelContext ); + if ( mapKeyJavaType != null ) { + final var basicJavaTypeClass = mapKeyJavaType.value(); + if ( basicJavaTypeClass != null ) { + return useDeferredBeanContainerAccess + ? FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( basicJavaTypeClass ) + : getManagedBeanRegistry().getBean( basicJavaTypeClass ).getBeanInstance(); } } - final MapKeyClass mapKeyClassAnn = attribute.getDirectAnnotationUsage( MapKeyClass.class ); + final var mapKeyClassAnn = attribute.getDirectAnnotationUsage( MapKeyClass.class ); if ( mapKeyClassAnn != null ) { return (BasicJavaType) typeConfiguration.getJavaTypeRegistry() @@ -601,10 +566,9 @@ private void prepareMapKey( }; explicitMutabilityAccess = typeConfiguration -> { - final MapKeyMutability mutabilityAnn = - attribute.locateAnnotationUsage( MapKeyMutability.class, getSourceModelContext() ); + final var mutabilityAnn = attribute.locateAnnotationUsage( MapKeyMutability.class, modelContext ); if ( mutabilityAnn != null ) { - final Class> mutabilityClass = mutabilityAnn.value(); + final var mutabilityClass = mutabilityAnn.value(); if ( mutabilityClass != null ) { return resolveMutability( mutabilityClass ); } @@ -612,14 +576,12 @@ private void prepareMapKey( // see if the value's Java Class is annotated with mutability-related annotations if ( implicitJavaTypeAccess != null ) { - final Class attributeType = - ReflectHelper.getClass( implicitJavaTypeAccess.apply( typeConfiguration ) ); + final var attributeType = ReflectHelper.getClass( implicitJavaTypeAccess.apply( typeConfiguration ) ); if ( attributeType != null ) { - final Mutability attributeTypeMutabilityAnn = attributeType.getAnnotation( Mutability.class ); + final var attributeTypeMutabilityAnn = attributeType.getAnnotation( Mutability.class ); if ( attributeTypeMutabilityAnn != null ) { return resolveMutability( attributeTypeMutabilityAnn.value() ); } - if ( attributeType.isAnnotationPresent( Immutable.class ) ) { return ImmutableMutabilityPlan.instance(); } @@ -628,26 +590,23 @@ private void prepareMapKey( // if the value is converted, see if converter Class is annotated with mutability-related annotations if ( converterDescriptor != null ) { - final Mutability converterMutabilityAnn = - converterDescriptor.getAttributeConverterClass().getAnnotation( Mutability.class ); - if ( converterMutabilityAnn != null ) { - return resolveMutability( converterMutabilityAnn.value() ); + final var attributeConverterClass = converterDescriptor.getAttributeConverterClass(); + final var converterMutability = attributeConverterClass.getAnnotation( Mutability.class ); + if ( converterMutability != null ) { + return resolveMutability( converterMutability.value() ); } - - if ( converterDescriptor.getAttributeConverterClass().isAnnotationPresent( Immutable.class ) ) { + if ( attributeConverterClass.isAnnotationPresent( Immutable.class ) ) { return ImmutableMutabilityPlan.instance(); } } // if there is a UserType, see if its Class is annotated with mutability-related annotations - final Class> customTypeImpl = - Kind.MAP_KEY.mappingAccess.customType( attribute, getSourceModelContext() ); + final var customTypeImpl = Kind.MAP_KEY.mappingAccess.customType( attribute, modelContext ); if ( customTypeImpl != null ) { - final Mutability customTypeMutabilityAnn = customTypeImpl.getAnnotation( Mutability.class ); + final var customTypeMutabilityAnn = customTypeImpl.getAnnotation( Mutability.class ); if ( customTypeMutabilityAnn != null ) { return resolveMutability( customTypeMutabilityAnn.value() ); } - if ( customTypeImpl.isAnnotationPresent( Immutable.class ) ) { return ImmutableMutabilityPlan.instance(); } @@ -662,20 +621,18 @@ private void prepareListIndex(MemberDetails attribute) { implicitJavaTypeAccess = typeConfiguration -> Integer.class; final boolean useDeferredBeanContainerAccess = useDeferredBeanContainerAccess(); - final ManagedBeanRegistry beanRegistry = getManagedBeanRegistry(); + final var beanRegistry = getManagedBeanRegistry(); + + final var modelContext = getSourceModelContext(); explicitJavaTypeAccess = typeConfiguration -> { - final ListIndexJavaType javaTypeAnn = - attribute.locateAnnotationUsage( ListIndexJavaType.class, getSourceModelContext() ); - if ( javaTypeAnn != null ) { - final Class> javaTypeClass = javaTypeAnn.value(); + final var javaType = attribute.locateAnnotationUsage( ListIndexJavaType.class, modelContext ); + if ( javaType != null ) { + final var javaTypeClass = javaType.value(); if ( javaTypeClass != null ) { - if ( useDeferredBeanContainerAccess ) { - return FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( javaTypeClass ); - } - else { - return beanRegistry.getBean( javaTypeClass ).getBeanInstance(); - } + return useDeferredBeanContainerAccess + ? FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( javaTypeClass ) + : beanRegistry.getBean( javaTypeClass ).getBeanInstance(); } } @@ -683,24 +640,19 @@ private void prepareListIndex(MemberDetails attribute) { }; explicitJdbcTypeAccess = typeConfiguration -> { - final ListIndexJdbcType jdbcTypeAnn = - attribute.locateAnnotationUsage( ListIndexJdbcType.class, getSourceModelContext() ); - if ( jdbcTypeAnn != null ) { - final Class jdbcTypeClass = jdbcTypeAnn.value(); + final var jdbcType = attribute.locateAnnotationUsage( ListIndexJdbcType.class, modelContext ); + if ( jdbcType != null ) { + final var jdbcTypeClass = jdbcType.value(); if ( jdbcTypeClass != null ) { - if ( useDeferredBeanContainerAccess ) { - return FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( jdbcTypeClass ); - } - else { - return beanRegistry.getBean( jdbcTypeClass ).getBeanInstance(); - } + return useDeferredBeanContainerAccess + ? FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( jdbcTypeClass ) + : beanRegistry.getBean( jdbcTypeClass ).getBeanInstance(); } } - final ListIndexJdbcTypeCode jdbcTypeCodeAnn = - attribute.locateAnnotationUsage( ListIndexJdbcTypeCode.class, getSourceModelContext() ); - if ( jdbcTypeCodeAnn != null ) { - return getDescriptor( typeConfiguration, jdbcTypeCodeAnn.value() ); + final var jdbcTypeCode = attribute.locateAnnotationUsage( ListIndexJdbcTypeCode.class, modelContext ); + if ( jdbcTypeCode != null ) { + return getDescriptor( typeConfiguration, jdbcTypeCode.value() ); } else { return null; @@ -711,22 +663,20 @@ private void prepareListIndex(MemberDetails attribute) { private void prepareCollectionElement( MemberDetails attribute, TypeDetails explicitElementTypeDetails) { - final TypeDetails elementTypeDetails = + final var elementTypeDetails = explicitElementTypeDetails == null && attribute.isArray() ? attribute.getElementType() : explicitElementTypeDetails; - final ClassDetails rawElementType = elementTypeDetails.determineRawClass(); - final java.lang.reflect.Type javaType = rawElementType.toJavaClass(); - final Class javaTypeClass = ReflectHelper.getClass( javaType ); + final var javaType = elementTypeDetails.determineRawClass().toJavaClass(); implicitJavaTypeAccess = typeConfiguration -> javaType; //noinspection deprecation - final Temporal temporalAnn = attribute.getDirectAnnotationUsage( Temporal.class ); - if ( temporalAnn != null ) { + final var temporal = attribute.getDirectAnnotationUsage( Temporal.class ); + if ( temporal != null ) { //noinspection deprecation DEPRECATION_LOGGER.deprecatedAnnotation( Temporal.class, attribute.getName() ); - temporalPrecision = temporalAnn.value(); + temporalPrecision = temporal.value(); if ( temporalPrecision == null ) { throw new IllegalStateException( "No jakarta.persistence.TemporalType defined for @jakarta.persistence.Temporal " + @@ -738,10 +688,10 @@ private void prepareCollectionElement( temporalPrecision = null; } - if ( javaTypeClass.isEnum() ) { - final Enumerated enumeratedAnn = attribute.getDirectAnnotationUsage( Enumerated.class ); - if ( enumeratedAnn != null ) { - enumType = enumeratedAnn.value(); + if ( ReflectHelper.getClass( javaType ).isEnum() ) { + final var enumerated = attribute.getDirectAnnotationUsage( Enumerated.class ); + if ( enumerated != null ) { + enumType = enumerated.value(); if ( enumType == null ) { throw new IllegalStateException( "jakarta.persistence.EnumType was null on @jakarta.persistence.Enumerated " + @@ -756,15 +706,14 @@ private void prepareCollectionElement( normalSupplementalDetails( attribute); - // layer in support for JPA's approach for specifying a specific Java type for the collection elements... - final ElementCollection elementCollectionAnn = - attribute.getDirectAnnotationUsage( ElementCollection.class ); - if ( elementCollectionAnn != null ) { - final Class targetClassDetails = elementCollectionAnn.targetClass(); + // layer in support for JPA's approach for specifying a specific Java type for the collection elements + final var elementCollection = attribute.getDirectAnnotationUsage( ElementCollection.class ); + if ( elementCollection != null ) { + final var targetClassDetails = elementCollection.targetClass(); if ( targetClassDetails != void.class) { - final Function> original = explicitJavaTypeAccess; + final var original = explicitJavaTypeAccess; explicitJavaTypeAccess = typeConfiguration -> { - final BasicJavaType originalResult = original.apply( typeConfiguration ); + final var originalResult = original.apply( typeConfiguration ); if ( originalResult != null ) { return originalResult; } @@ -782,23 +731,18 @@ private void prepareBasicAttribute( String declaringClassName, MemberDetails attribute, TypeDetails attributeType) { - final Class javaTypeClass = attributeType.determineRawClass().toJavaClass(); - implicitJavaTypeAccess = typeConfiguration -> { - if ( attributeType.getTypeKind() == TypeDetails.Kind.PARAMETERIZED_TYPE ) { - return ParameterizedTypeImpl.from( attributeType.asParameterizedType() ); - } - else { - return attributeType.determineRawClass().toJavaClass(); - } - }; + implicitJavaTypeAccess = typeConfiguration -> + attributeType.getTypeKind() == TypeDetails.Kind.PARAMETERIZED_TYPE + ? ParameterizedTypeImpl.from( attributeType.asParameterizedType() ) + : attributeType.determineRawClass().toJavaClass(); //noinspection deprecation - final Temporal temporalAnn = attribute.getDirectAnnotationUsage( Temporal.class ); - if ( temporalAnn != null ) { + final var temporal = attribute.getDirectAnnotationUsage( Temporal.class ); + if ( temporal != null ) { //noinspection deprecation DEPRECATION_LOGGER.deprecatedAnnotation( Temporal.class, declaringClassName + "." + attribute.getName() ); - temporalPrecision = temporalAnn.value(); + temporalPrecision = temporal.value(); if ( temporalPrecision == null ) { throw new IllegalStateException( "No jakarta.persistence.TemporalType defined for @jakarta.persistence.Temporal " + @@ -810,9 +754,10 @@ private void prepareBasicAttribute( temporalPrecision = null; } - final Enumerated enumeratedAnn = attribute.getDirectAnnotationUsage( Enumerated.class ); - if ( enumeratedAnn != null ) { - enumType = enumeratedAnn.value(); + final var enumerated = attribute.getDirectAnnotationUsage( Enumerated.class ); + if ( enumerated != null ) { + enumType = enumerated.value(); + final var javaTypeClass = attributeType.determineRawClass().toJavaClass(); if ( canUseEnumerated( attributeType, javaTypeClass ) ) { if ( enumType == null ) { throw new IllegalStateException( @@ -845,7 +790,7 @@ private boolean canUseEnumerated(TypeDetails javaType, Class javaTypeClass) { return true; } else if ( javaType.isImplementor( Collection.class ) ) { - final List typeArguments = javaType.asParameterizedType().getArguments(); + final var typeArguments = javaType.asParameterizedType().getArguments(); return !typeArguments.isEmpty() && typeArguments.get( 0 ).isImplementor( Enum.class ); } else { @@ -854,11 +799,11 @@ else if ( javaType.isImplementor( Collection.class ) ) { } private void prepareAnyDiscriminator(MemberDetails memberDetails) { - final AnyDiscriminator anyDiscriminatorAnn = + final var anyDiscriminator = memberDetails.locateAnnotationUsage( AnyDiscriminator.class, getSourceModelContext() ); implicitJavaTypeAccess = typeConfiguration -> { - if ( anyDiscriminatorAnn != null ) { - return switch ( anyDiscriminatorAnn.value() ) { + if ( anyDiscriminator != null ) { + return switch ( anyDiscriminator.value() ) { case CHAR -> Character.class; case INTEGER -> Integer.class; default -> String.class; @@ -873,19 +818,14 @@ private void prepareAnyDiscriminator(MemberDetails memberDetails) { normalMutabilityDetails( memberDetails ); // layer AnyDiscriminator into the JdbcType resolution - final Function originalJdbcTypeResolution = explicitJdbcTypeAccess; - this.explicitJdbcTypeAccess = typeConfiguration -> { - final JdbcType originalResolution = originalJdbcTypeResolution.apply( typeConfiguration ); - if ( originalResolution != null ) { - return originalResolution; - } - else { - final Class hintedJavaType = (Class) implicitJavaTypeAccess.apply( typeConfiguration ); - final JavaType hintedDescriptor = - typeConfiguration.getJavaTypeRegistry() - .getDescriptor( hintedJavaType ); - return hintedDescriptor.getRecommendedJdbcType( typeConfiguration.getCurrentBaseSqlTypeIndicators() ); - } + final var originalJdbcTypeResolution = explicitJdbcTypeAccess; + explicitJdbcTypeAccess = typeConfiguration -> { + final var originalResolution = originalJdbcTypeResolution.apply( typeConfiguration ); + return originalResolution != null + ? originalResolution + : typeConfiguration.getJavaTypeRegistry() + .getDescriptor( implicitJavaTypeAccess.apply( typeConfiguration ) ) + .getRecommendedJdbcType( typeConfiguration.getCurrentBaseSqlTypeIndicators() ); }; } @@ -894,36 +834,33 @@ private void prepareAnyKey(MemberDetails member) { final boolean useDeferredBeanContainerAccess = useDeferredBeanContainerAccess(); + final var context = getSourceModelContext(); + explicitJavaTypeAccess = typeConfiguration -> { - final AnyKeyJavaType javaTypeAnn = - member.locateAnnotationUsage( AnyKeyJavaType.class, getSourceModelContext() ); - if ( javaTypeAnn != null ) { - final Class> implClass = javaTypeAnn.value(); + final var anyKeyJavaType = member.locateAnnotationUsage( AnyKeyJavaType.class, context ); + if ( anyKeyJavaType != null ) { + final var implClass = anyKeyJavaType.value(); if ( implClass != null ) { - if ( useDeferredBeanContainerAccess ) { - return FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( implClass ); - } - else { - return getManagedBeanRegistry().getBean( implClass ).getBeanInstance(); - } + return useDeferredBeanContainerAccess + ? FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( implClass ) + : getManagedBeanRegistry().getBean( implClass ).getBeanInstance(); } } - final AnyKeyJavaClass javaClassAnn = - member.locateAnnotationUsage( AnyKeyJavaClass.class, getSourceModelContext() ); - if ( javaClassAnn != null ) { + final var anyKeyJavaClass = member.locateAnnotationUsage( AnyKeyJavaClass.class, context ); + if ( anyKeyJavaClass != null ) { return (BasicJavaType) typeConfiguration.getJavaTypeRegistry() - .getDescriptor( javaClassAnn.value() ); + .getDescriptor( anyKeyJavaClass.value() ); } // mainly used in XML interpretation - final AnyKeyType anyKeyTypeAnn = - member.locateAnnotationUsage( AnyKeyType.class, getSourceModelContext() ); - if ( anyKeyTypeAnn != null ) { - final String namedType = anyKeyTypeAnn.value(); - final BasicType registeredType = - typeConfiguration.getBasicTypeRegistry().getRegisteredType( namedType ); + final var anyKeyType = member.locateAnnotationUsage( AnyKeyType.class, context ); + if ( anyKeyType != null ) { + final String namedType = anyKeyType.value(); + final var registeredType = + typeConfiguration.getBasicTypeRegistry() + .getRegisteredType( namedType ); if ( registeredType == null ) { throw new MappingException( "Unrecognized @AnyKeyType value - " + namedType ); } @@ -936,24 +873,19 @@ private void prepareAnyKey(MemberDetails member) { }; explicitJdbcTypeAccess = typeConfiguration -> { - final AnyKeyJdbcType jdbcTypeAnn = - member.locateAnnotationUsage( AnyKeyJdbcType.class, getSourceModelContext() ); - if ( jdbcTypeAnn != null ) { - final Class jdbcTypeClass = jdbcTypeAnn.value(); + final var anyKeyJdbcType = member.locateAnnotationUsage( AnyKeyJdbcType.class, context ); + if ( anyKeyJdbcType != null ) { + final var jdbcTypeClass = anyKeyJdbcType.value(); if ( jdbcTypeClass != null ) { - if ( useDeferredBeanContainerAccess ) { - return FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( jdbcTypeClass ); - } - else { - return getManagedBeanRegistry().getBean( jdbcTypeClass ).getBeanInstance(); - } + return useDeferredBeanContainerAccess + ? FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( jdbcTypeClass ) + : getManagedBeanRegistry().getBean( jdbcTypeClass ).getBeanInstance(); } } - final AnyKeyJdbcTypeCode jdbcTypeCodeAnn = - member.locateAnnotationUsage( AnyKeyJdbcTypeCode.class, getSourceModelContext() ); - if ( jdbcTypeCodeAnn != null ) { - final int code = jdbcTypeCodeAnn.value(); + final var anyKeyJdbcTypeCode = member.locateAnnotationUsage( AnyKeyJdbcTypeCode.class, context ); + if ( anyKeyJdbcTypeCode != null ) { + final int code = anyKeyJdbcTypeCode.value(); if ( code != Integer.MIN_VALUE ) { return getDescriptor( typeConfiguration, code ); } @@ -965,32 +897,26 @@ private void prepareAnyKey(MemberDetails member) { private void normalJdbcTypeDetails(MemberDetails attribute) { explicitJdbcTypeAccess = typeConfiguration -> { - final org.hibernate.annotations.JdbcType jdbcTypeAnn = - attribute.locateAnnotationUsage( org.hibernate.annotations.JdbcType.class, getSourceModelContext() ); - if ( jdbcTypeAnn != null ) { - final Class jdbcTypeClass = jdbcTypeAnn.value(); + final var context = getSourceModelContext(); + + final var jdbcType = attribute.locateAnnotationUsage( org.hibernate.annotations.JdbcType.class, context ); + if ( jdbcType != null ) { + final var jdbcTypeClass = jdbcType.value(); if ( jdbcTypeClass != null ) { - if ( useDeferredBeanContainerAccess() ) { - return FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( jdbcTypeClass ); - } - else { - return getManagedBeanRegistry().getBean( jdbcTypeClass ).getBeanInstance(); - } + return useDeferredBeanContainerAccess() + ? FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( jdbcTypeClass ) + : getManagedBeanRegistry().getBean( jdbcTypeClass ).getBeanInstance(); } } - final JdbcTypeCode jdbcTypeCodeAnn = - attribute.locateAnnotationUsage( JdbcTypeCode.class, getSourceModelContext() ); - if ( jdbcTypeCodeAnn != null ) { - final int jdbcTypeCode = jdbcTypeCodeAnn.value(); - if ( jdbcTypeCode != Integer.MIN_VALUE ) { - final JdbcTypeRegistry jdbcTypeRegistry = typeConfiguration.getJdbcTypeRegistry(); - if ( jdbcTypeRegistry.getConstructor( jdbcTypeCode ) != null ) { - return null; - } - else { - return jdbcTypeRegistry.getDescriptor( jdbcTypeCode ); - } + final var jdbcTypeCode = attribute.locateAnnotationUsage( JdbcTypeCode.class, context ); + if ( jdbcTypeCode != null ) { + final int code = jdbcTypeCode.value(); + if ( code != Integer.MIN_VALUE ) { + final var jdbcTypeRegistry = typeConfiguration.getJdbcTypeRegistry(); + return jdbcTypeRegistry.getConstructor( code ) == null + ? jdbcTypeRegistry.getDescriptor( code ) + : null; } } @@ -1001,15 +927,11 @@ private void normalJdbcTypeDetails(MemberDetails attribute) { private void normalMutabilityDetails(MemberDetails attribute) { explicitMutabilityAccess = typeConfiguration -> { // Look for `@Mutability` on the attribute - final Mutability mutabilityAnn = + final var mutability = attribute.locateAnnotationUsage( Mutability.class, getSourceModelContext() ); - if ( mutabilityAnn != null ) { - final Class> mutability = mutabilityAnn.value(); - if ( mutability != null ) { - return resolveMutability( mutability ); - } + if ( mutability != null && mutability.value() != null ) { + return resolveMutability( mutability.value() ); } - // Look for `@Immutable` on the attribute if ( attribute.hasDirectAnnotationUsage( Immutable.class ) ) { return ImmutableMutabilityPlan.instance(); @@ -1017,31 +939,13 @@ private void normalMutabilityDetails(MemberDetails attribute) { // Look for `@Mutability` on the attribute's type if ( explicitJavaTypeAccess != null || implicitJavaTypeAccess != null ) { - Class attributeType = null; - if ( explicitJavaTypeAccess != null ) { - final BasicJavaType jtd = explicitJavaTypeAccess.apply( typeConfiguration ); - if ( jtd != null ) { - attributeType = jtd.getJavaTypeClass(); - } - } - if ( attributeType == null ) { - final java.lang.reflect.Type javaType = implicitJavaTypeAccess.apply( typeConfiguration ); - if ( javaType != null ) { - attributeType = ReflectHelper.getClass( javaType ); - } - } - + final var attributeType = attributeType( typeConfiguration ); if ( attributeType != null ) { - final Mutability classMutability = attributeType.getAnnotation( Mutability.class ); + final var classMutability = attributeType.getAnnotation( Mutability.class ); if ( classMutability != null ) { - final Class> mutability = classMutability.value(); - if ( mutability != null ) { - return resolveMutability( mutability ); - } + return resolveMutability( classMutability.value() ); } - - final Immutable classImmutable = attributeType.getAnnotation( Immutable.class ); - if ( classImmutable != null ) { + if ( attributeType.isAnnotationPresent( Immutable.class ) ) { return ImmutableMutabilityPlan.instance(); } } @@ -1049,30 +953,25 @@ private void normalMutabilityDetails(MemberDetails attribute) { // if the value is converted, see if the converter Class is annotated `@Mutability` if ( converterDescriptor != null ) { - final Mutability converterMutabilityAnn = - converterDescriptor.getAttributeConverterClass().getAnnotation( Mutability.class ); - if ( converterMutabilityAnn != null ) { - return resolveMutability( converterMutabilityAnn.value() ); + final var attributeConverterClass = converterDescriptor.getAttributeConverterClass(); + final var converterMutability = attributeConverterClass.getAnnotation( Mutability.class ); + if ( converterMutability != null ) { + return resolveMutability( converterMutability.value() ); } - - final Immutable converterImmutableAnn = - converterDescriptor.getAttributeConverterClass().getAnnotation( Immutable.class ); - if ( converterImmutableAnn != null ) { + if ( attributeConverterClass.isAnnotationPresent( Immutable.class ) ) { return ImmutableMutabilityPlan.instance(); } } // if a custom UserType is specified, see if the UserType Class is annotated `@Mutability` - final Class> customTypeImpl = + final var customTypeImpl = Kind.ATTRIBUTE.mappingAccess.customType( attribute, getSourceModelContext() ); if ( customTypeImpl != null ) { - final Mutability customTypeMutabilityAnn = customTypeImpl.getAnnotation( Mutability.class ); - if ( customTypeMutabilityAnn != null ) { - return resolveMutability( customTypeMutabilityAnn.value() ); + final var customTypeMutability = customTypeImpl.getAnnotation( Mutability.class ); + if ( customTypeMutability != null ) { + return resolveMutability( customTypeMutability.value() ); } - - final Immutable customTypeImmutableAnn = customTypeImpl.getAnnotation( Immutable.class ); - if ( customTypeImmutableAnn != null ) { + if ( customTypeImpl.isAnnotationPresent( Immutable.class ) ) { return ImmutableMutabilityPlan.instance(); } } @@ -1082,6 +981,23 @@ private void normalMutabilityDetails(MemberDetails attribute) { }; } + private Class attributeType(TypeConfiguration typeConfiguration) { + if ( explicitJavaTypeAccess != null ) { + final var basicJavaType = explicitJavaTypeAccess.apply( typeConfiguration ); + if ( basicJavaType != null ) { + final var attributeType = basicJavaType.getJavaTypeClass(); + if ( attributeType != null ) { + return attributeType; + } + } + } + final var javaType = implicitJavaTypeAccess.apply( typeConfiguration ); + if ( javaType != null ) { + return ReflectHelper.getClass( javaType ); + } + return null; + } + @SuppressWarnings({ "rawtypes", "unchecked" }) private MutabilityPlan resolveMutability(Class mutability) { if ( mutability.equals( Immutability.class ) ) { @@ -1099,26 +1015,24 @@ else if ( useDeferredBeanContainerAccess() ) { } private void normalSupplementalDetails(MemberDetails attribute) { + final var context = getSourceModelContext(); + explicitJavaTypeAccess = typeConfiguration -> { - final org.hibernate.annotations.JavaType javaType = - attribute.locateAnnotationUsage( org.hibernate.annotations.JavaType.class, getSourceModelContext() ); + final var javaType = + attribute.locateAnnotationUsage( org.hibernate.annotations.JavaType.class, context ); if ( javaType != null ) { - final Class> javaTypeClass = javaType.value(); - if ( javaTypeClass != null ) { - if ( useDeferredBeanContainerAccess() ) { - return FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( javaTypeClass ); - } - else { - return getManagedBeanRegistry().getBean( javaTypeClass ).getBeanInstance(); - } + final var basicJavaTypeClass = javaType.value(); + if ( basicJavaTypeClass != null ) { + return useDeferredBeanContainerAccess() + ? FallbackBeanInstanceProducer.INSTANCE.produceBeanInstance( basicJavaTypeClass ) + : getManagedBeanRegistry().getBean( basicJavaTypeClass ).getBeanInstance(); } } return null; }; - final JdbcTypeCode jdbcType = - attribute.locateAnnotationUsage( JdbcTypeCode.class, getSourceModelContext() ); + final var jdbcType = attribute.locateAnnotationUsage( JdbcTypeCode.class, context ); if ( jdbcType != null ) { jdbcTypeCode = jdbcType.value(); } @@ -1126,23 +1040,21 @@ private void normalSupplementalDetails(MemberDetails attribute) { normalJdbcTypeDetails( attribute); normalMutabilityDetails( attribute ); - final Enumerated enumerated = attribute.getDirectAnnotationUsage( Enumerated.class ); + final var enumerated = attribute.getDirectAnnotationUsage( Enumerated.class ); if ( enumerated != null ) { enumType = enumerated.value(); } //noinspection deprecation - final Temporal temporal = attribute.getDirectAnnotationUsage( Temporal.class ); + final var temporal = attribute.getDirectAnnotationUsage( Temporal.class ); if ( temporal != null ) { temporalPrecision = temporal.value(); } - final TimeZoneStorage timeZoneStorage = - attribute.getDirectAnnotationUsage( TimeZoneStorage.class ); + final var timeZoneStorage = attribute.getDirectAnnotationUsage( TimeZoneStorage.class ); if ( timeZoneStorage != null ) { timeZoneStorageType = timeZoneStorage.value(); - final TimeZoneColumn timeZoneColumnAnn = - attribute.getDirectAnnotationUsage( TimeZoneColumn.class ); + final var timeZoneColumnAnn = attribute.getDirectAnnotationUsage( TimeZoneColumn.class ); if ( timeZoneColumnAnn != null ) { if ( timeZoneStorageType != TimeZoneStorageType.AUTO && timeZoneStorageType != TimeZoneStorageType.COLUMN ) { @@ -1155,7 +1067,7 @@ private void normalSupplementalDetails(MemberDetails attribute) { } } - this.partitionKey = attribute.hasDirectAnnotationUsage( PartitionKey.class ); + partitionKey = attribute.hasDirectAnnotationUsage( PartitionKey.class ); } @Override @@ -1189,7 +1101,7 @@ private void applyJpaConverter(MemberDetails attribute, ConverterDescriptor disallowConverter( attribute, Struct.class, autoApply ); disallowConverter( attribute, Array.class, autoApply ); disallowConverter( attribute, Any.class, autoApply ); - this.converterDescriptor = attributeConverterDescriptor; + converterDescriptor = attributeConverterDescriptor; } void disallowConverter(MemberDetails attribute, Class annotationType, boolean autoApply) { @@ -1214,8 +1126,7 @@ public BasicValue make() { basicValue = new BasicValue( buildingContext, table ); if ( columns.getPropertyHolder().isComponent() ) { - final ComponentPropertyHolder propertyHolder = - (ComponentPropertyHolder) columns.getPropertyHolder(); + final var propertyHolder = (ComponentPropertyHolder) columns.getPropertyHolder(); basicValue.setAggregateColumn( propertyHolder.getAggregateColumn() ); } @@ -1260,8 +1171,8 @@ public BasicValue make() { } private void linkWithValue() { - final InFlightMetadataCollector collector = getMetadataCollector(); - final AnnotatedColumn firstColumn = columns.getColumns().get(0); + final var collector = getMetadataCollector(); + final var firstColumn = columns.getColumns().get(0); if ( !collector.isInSecondPass() && firstColumn.isNameDeferred() && referencedEntityName != null ) { collector.addSecondPass( new OverriddenFkSecondPass( basicValue, referencedEntityName, columns ) ); } @@ -1384,13 +1295,13 @@ private static class ValueMappingAccess implements BasicMappingAccess { @Override public Class> customType(MemberDetails attribute, ModelsContext context) { - final Type customType = attribute.locateAnnotationUsage( Type.class, context ); + final var customType = attribute.locateAnnotationUsage( Type.class, context ); return customType == null ? null : customType.value(); } @Override public Map customTypeParameters(MemberDetails attribute, ModelsContext context) { - final Type customType = attribute.locateAnnotationUsage( Type.class, context ); + final var customType = attribute.locateAnnotationUsage( Type.class, context ); return customType == null ? null : extractParameterMap( customType.parameters() ); } } @@ -1428,14 +1339,14 @@ private static class MapKeyMappingAccess implements BasicMappingAccess { @Override public Class> customType(MemberDetails attribute, ModelsContext context) { - final MapKeyType customType = attribute.locateAnnotationUsage( MapKeyType.class, context ); + final var customType = attribute.locateAnnotationUsage( MapKeyType.class, context ); return customType == null ? null : customType.value(); } @Override public Map customTypeParameters(MemberDetails attribute, ModelsContext context) { - final MapKeyType customType = attribute.locateAnnotationUsage( MapKeyType.class, context ); + final var customType = attribute.locateAnnotationUsage( MapKeyType.class, context ); return customType == null ? null : extractParameterMap( customType.parameters() ); } @@ -1446,14 +1357,14 @@ private static class CollectionIdMappingAccess implements BasicMappingAccess { @Override public Class> customType(MemberDetails attribute, ModelsContext context) { - final CollectionIdType customType = attribute.locateAnnotationUsage( CollectionIdType.class, context ); + final var customType = attribute.locateAnnotationUsage( CollectionIdType.class, context ); return customType == null ? null : customType.value(); } @Override public Map customTypeParameters(MemberDetails attribute, ModelsContext context) { - final CollectionIdType customType = attribute.locateAnnotationUsage( CollectionIdType.class, context ); + final var customType = attribute.locateAnnotationUsage( CollectionIdType.class, context ); return customType == null ? null : extractParameterMap( customType.parameters() ); } @@ -1474,7 +1385,7 @@ public Map customTypeParameters(MemberDetails attribute, ModelsCo } private static AnnotatedJoinColumns convertToJoinColumns(AnnotatedColumns columns, MetadataBuildingContext context) { - final AnnotatedJoinColumns joinColumns = new AnnotatedJoinColumns(); + final var joinColumns = new AnnotatedJoinColumns(); joinColumns.setBuildingContext( context ); joinColumns.setPropertyHolder( columns.getPropertyHolder() ); joinColumns.setPropertyName( columns.getPropertyName() ); @@ -1520,7 +1431,7 @@ public boolean isInPrimaryKey() { @Override public void doSecondPass(Map persistentClasses) { - final PersistentClass referencedEntity = persistentClasses.get( referencedEntityName ); + final var referencedEntity = persistentClasses.get( referencedEntityName ); if ( referencedEntity == null ) { // TODO: much better error message if this is something that can really happen! throw new AnnotationException( "Unknown entity name '" + referencedEntityName + "'" ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BinderHelper.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BinderHelper.java index d4863418986f..9b21b6c74e08 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BinderHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BinderHelper.java @@ -45,7 +45,6 @@ import org.hibernate.models.spi.MemberDetails; import org.hibernate.models.spi.ModelsContext; import org.hibernate.models.spi.TypeDetails; -import org.hibernate.type.descriptor.java.JavaType; import java.lang.annotation.Annotation; import java.util.ArrayList; @@ -372,8 +371,8 @@ else if ( persistentClassOrJoin instanceof Join join ) { */ private static Property cloneProperty(PersistentClass ownerEntity, MetadataBuildingContext context, Property property) { if ( property.isComposite() ) { - final Component component = (Component) property.getValue(); - final Component copy = new Component( context, component ); + final var component = (Component) property.getValue(); + final var copy = new Component( context, component ); copy.setComponentClassName( component.getComponentClassName() ); copy.setEmbedded( component.isEmbedded() ); for ( Property subproperty : component.getProperties() ) { @@ -727,45 +726,45 @@ public static Any buildAnyValue( EntityBinder entityBinder, boolean optional, MetadataBuildingContext context) { - final MemberDetails property = inferredData.getAttributeMember(); + final var memberDetails = inferredData.getAttributeMember(); - final Any value = new Any( context, keyColumns.getTable(), true ); - value.setLazy( lazy ); - value.setOnDeleteAction( onDeleteAction ); + final var any = new Any( context, keyColumns.getTable(), true ); + any.setLazy( lazy ); + any.setOnDeleteAction( onDeleteAction ); - final BasicValueBinder discriminatorValueBinder = + final var discriminatorValueBinder = new BasicValueBinder( BasicValueBinder.Kind.ANY_DISCRIMINATOR, context ); // TODO: if there can be only one discriminator column, // why are we making a whole array of them?? - final AnnotatedColumns discriminatorColumns = buildColumnOrFormulaFromAnnotation( - discriminatorColumn, - discriminatorFormula, - null, -// null, - nullability, - propertyHolder, - inferredData, - entityBinder.getSecondaryTables(), - context - ); + final var discriminatorColumns = + buildColumnOrFormulaFromAnnotation( + discriminatorColumn, + discriminatorFormula, + null, +// null, + nullability, + propertyHolder, + inferredData, + entityBinder.getSecondaryTables(), + context + ); assert discriminatorColumns.getColumns().size() == 1; - discriminatorColumns.setTable( value.getTable() ); + discriminatorColumns.setTable( any.getTable() ); discriminatorValueBinder.setColumns( discriminatorColumns ); discriminatorValueBinder.setReturnedClassName( inferredData.getTypeName() ); - discriminatorValueBinder.setType( property, property.getType(), null, null ); + discriminatorValueBinder.setType( memberDetails, memberDetails.getType(), null, null ); - final BasicValue discriminatorDescriptor = discriminatorValueBinder.make(); - value.setDiscriminator( discriminatorDescriptor ); + final BasicValue discriminator = discriminatorValueBinder.make(); + any.setDiscriminator( discriminator ); discriminatorValueBinder.fillSimpleValue(); // TODO: this is nasty - final AnnotatedColumn firstDiscriminatorColumn = discriminatorColumns.getColumns().get(0); - firstDiscriminatorColumn.linkWithValue( discriminatorDescriptor ); + final var firstDiscriminatorColumn = discriminatorColumns.getColumns().get(0); + firstDiscriminatorColumn.linkWithValue( discriminator ); - final JavaType discriminatorJavaType = - discriminatorDescriptor.resolve().getRelationalJavaType(); + final var discriminatorJavaType = discriminator.resolve().getRelationalJavaType(); final Map> discriminatorValueMappings = new HashMap<>(); processAnyDiscriminatorValues( @@ -776,50 +775,50 @@ public static Any buildAnyValue( ), context.getBootstrapContext().getModelsContext() ); - value.setDiscriminatorValueMappings( discriminatorValueMappings ); + any.setDiscriminatorValueMappings( discriminatorValueMappings ); - final AnyDiscriminatorImplicitValues anyDiscriminatorImplicitValues = - property.getDirectAnnotationUsage( AnyDiscriminatorImplicitValues.class ); + final var anyDiscriminatorImplicitValues = + memberDetails.getDirectAnnotationUsage( AnyDiscriminatorImplicitValues.class ); if ( anyDiscriminatorImplicitValues != null ) { - value.setImplicitDiscriminatorValueStrategy( resolveImplicitDiscriminatorStrategy( anyDiscriminatorImplicitValues, context ) ); + any.setImplicitDiscriminatorValueStrategy( + resolveImplicitDiscriminatorStrategy( anyDiscriminatorImplicitValues, context ) ); } - final BasicValueBinder keyValueBinder = new BasicValueBinder( BasicValueBinder.Kind.ANY_KEY, context ); - final List columns = keyColumns.getJoinColumns(); + final var keyValueBinder = new BasicValueBinder( BasicValueBinder.Kind.ANY_KEY, context ); + final var columns = keyColumns.getJoinColumns(); assert columns.size() == 1; - keyColumns.setTable( value.getTable() ); + keyColumns.setTable( any.getTable() ); keyValueBinder.setColumns( keyColumns ); if ( !optional ) { for ( AnnotatedJoinColumn column : columns ) { column.setNullable( false ); } } - keyValueBinder.setType( property, property.getType(), null, null ); + keyValueBinder.setType( memberDetails, memberDetails.getType(), null, null ); final BasicValue keyDescriptor = keyValueBinder.make(); - value.setKey( keyDescriptor ); + any.setKey( keyDescriptor ); keyValueBinder.fillSimpleValue(); keyColumns.checkPropertyConsistency(); columns.get(0).linkWithValue( keyDescriptor ); //TODO: nasty - return value; + return any; } private static void processAnyDiscriminatorValues( MemberDetails property, Consumer consumer, ModelsContext sourceModelContext) { - final AnyDiscriminatorValues valuesAnn = + final var anyDiscriminatorValues = property.locateAnnotationUsage( AnyDiscriminatorValues.class, sourceModelContext ); - if ( valuesAnn != null ) { - final AnyDiscriminatorValue[] nestedList = valuesAnn.value(); - ArrayHelper.forEach( nestedList, consumer ); - return; + if ( anyDiscriminatorValues != null ) { + ArrayHelper.forEach( anyDiscriminatorValues.value(), consumer ); } - - final AnyDiscriminatorValue valueAnn = - property.locateAnnotationUsage( AnyDiscriminatorValue.class, sourceModelContext ); - if ( valueAnn != null ) { - consumer.accept( valueAnn ); + else { + final var anyDiscriminatorValue = + property.locateAnnotationUsage( AnyDiscriminatorValue.class, sourceModelContext ); + if ( anyDiscriminatorValue != null ) { + consumer.accept( anyDiscriminatorValue ); + } } } @@ -828,7 +827,7 @@ public static MappedSuperclass getMappedSuperclassOrNull( Map inheritanceStatePerClass, MetadataBuildingContext context) { if ( declaringClass != null ) { - final InheritanceState inheritanceState = inheritanceStatePerClass.get( declaringClass ); + final var inheritanceState = inheritanceStatePerClass.get( declaringClass ); if ( inheritanceState == null ) { throw new AssertionFailure( "Declaring class is not found in the inheritance state hierarchy: " + declaringClass @@ -847,7 +846,7 @@ public static String getPath(PropertyHolder holder, PropertyData property) { public static Map toAliasTableMap(SqlFragmentAlias[] aliases){ final Map result = new HashMap<>(); - for ( SqlFragmentAlias aliasAnnotation : aliases ) { + for ( var aliasAnnotation : aliases ) { final String table = aliasAnnotation.table(); if ( isNotBlank( table ) ) { result.put( aliasAnnotation.alias(), table ); @@ -858,8 +857,8 @@ public static Map toAliasTableMap(SqlFragmentAlias[] aliases){ public static Map toAliasEntityMap(SqlFragmentAlias[] aliases){ final Map result = new HashMap<>(); - for ( SqlFragmentAlias aliasAnnotation : aliases ) { - final Class entityClass = aliasAnnotation.entity(); + for ( var aliasAnnotation : aliases ) { + final var entityClass = aliasAnnotation.entity(); if ( entityClass != void.class ) { result.put( aliasAnnotation.alias(), entityClass.getName() ); } @@ -886,10 +885,7 @@ public static EnumSet aggregateCascadeTypes( boolean orphanRemoval, MetadataBuildingContext context) { final var cascades = convertToHibernateCascadeType( cascadeTypes ); - final CascadeType[] hibernateCascades = - cascadeAnnotation == null - ? null - : cascadeAnnotation.value(); + final var hibernateCascades = cascadeAnnotation == null ? null : cascadeAnnotation.value(); if ( !isEmpty( hibernateCascades ) ) { addAll( cascades, hibernateCascades ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ClassLoaderAccessLazyImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ClassLoaderAccessLazyImpl.java deleted file mode 100644 index 382859f37e74..000000000000 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ClassLoaderAccessLazyImpl.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - * Copyright Red Hat Inc. and Hibernate Authors - */ -package org.hibernate.boot.model.internal; - -import java.net.URL; - -import org.hibernate.boot.spi.ClassLoaderAccess; -import org.hibernate.boot.spi.MetadataBuildingOptions; - -/** - * A ClassLoaderAccess implementation based on lazy access to {@link MetadataBuildingOptions} - * - * @author Steve Ebersole - */ -public class ClassLoaderAccessLazyImpl implements ClassLoaderAccess { - private final MetadataBuildingOptions metadataBuildingOptions; - - public ClassLoaderAccessLazyImpl(MetadataBuildingOptions metadataBuildingOptions) { - this.metadataBuildingOptions = metadataBuildingOptions; - } - - @Override - public Class classForName(String name) { - return null; - } - - @Override - public URL locateResource(String resourceName) { - return null; - } -} diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ClassPropertyHolder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ClassPropertyHolder.java index 124dc2e6a221..7cb4c6972701 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ClassPropertyHolder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ClassPropertyHolder.java @@ -5,24 +5,19 @@ package org.hibernate.boot.model.internal; import java.util.HashMap; -import java.util.Iterator; -import java.util.List; import java.util.Map; import java.util.function.Consumer; import org.checkerframework.checker.nullness.qual.Nullable; import org.hibernate.AssertionFailure; -import org.hibernate.MappingException; import org.hibernate.PropertyNotFoundException; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.SecondPass; -import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.mapping.Collection; import org.hibernate.mapping.Component; import org.hibernate.mapping.IndexedCollection; import org.hibernate.mapping.Join; import org.hibernate.mapping.KeyValue; -import org.hibernate.mapping.MappedSuperclass; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; import org.hibernate.mapping.SimpleValue; @@ -36,6 +31,7 @@ import jakarta.persistence.JoinTable; import static org.hibernate.internal.util.StringHelper.isEmpty; +import static org.hibernate.internal.util.collections.CollectionHelper.mapOfSize; /** * @author Emmanuel Bernard @@ -99,15 +95,17 @@ private void collectAttributeConversionInfo(Map // collect superclass info first collectAttributeConversionInfo( infoMap, entityClassDetails.getSuperClass() ); - final boolean canContainConvert = entityClassDetails.hasAnnotationUsage( jakarta.persistence.Entity.class, getSourceModelContext() ) - || entityClassDetails.hasAnnotationUsage( jakarta.persistence.MappedSuperclass.class, getSourceModelContext() ) - || entityClassDetails.hasAnnotationUsage( jakarta.persistence.Embeddable.class, getSourceModelContext() ); + final var sourceModelContext = getSourceModelContext(); + final boolean canContainConvert = + entityClassDetails.hasAnnotationUsage( jakarta.persistence.Entity.class, sourceModelContext ) + || entityClassDetails.hasAnnotationUsage( jakarta.persistence.MappedSuperclass.class, sourceModelContext ) + || entityClassDetails.hasAnnotationUsage( jakarta.persistence.Embeddable.class, sourceModelContext ); if ( ! canContainConvert ) { return; } - entityClassDetails.forEachAnnotationUsage( Convert.class, getSourceModelContext(), (usage) -> { - final AttributeConversionInfo info = new AttributeConversionInfo( usage, entityClassDetails ); + entityClassDetails.forEachAnnotationUsage( Convert.class, sourceModelContext, (usage) -> { + final var info = new AttributeConversionInfo( usage, entityClassDetails ); if ( isEmpty( info.getAttributeName() ) ) { throw new IllegalStateException( "@Convert placed on @Entity/@MappedSuperclass must define attributeName" ); } @@ -117,22 +115,18 @@ private void collectAttributeConversionInfo(Map @Override public void startingProperty(MemberDetails property) { - if ( property == null ) { - return; - } - - final String propertyName = property.resolveAttributeName(); - if ( attributeConversionInfoMap.containsKey( propertyName ) ) { - return; + if ( property != null ) { + final String propertyName = property.resolveAttributeName(); + if ( !attributeConversionInfoMap.containsKey( propertyName ) ) { + property.forEachAnnotationUsage( Convert.class, getSourceModelContext(), (usage) -> { + final var info = new AttributeConversionInfo( usage, property ); + final String path = isEmpty( info.getAttributeName() ) + ? propertyName + : propertyName + '.' + info.getAttributeName(); + attributeConversionInfoMap.put( path, info ); + } ); + } } - - property.forEachAnnotationUsage( Convert.class, getSourceModelContext(), (usage) -> { - final AttributeConversionInfo info = new AttributeConversionInfo( usage, property ); - final String path = isEmpty( info.getAttributeName() ) - ? propertyName - : propertyName + '.' + info.getAttributeName(); - attributeConversionInfoMap.put( path, info ); - } ); } @Override @@ -212,21 +206,21 @@ public Join addJoin(JoinTable joinTable, Table table, boolean noDelayInPkColumnC * with correctly typed sub-properties for the metamodel. */ public static void handleGenericComponentProperty(Property property, MemberDetails memberDetails, MetadataBuildingContext context) { - final Value value = property.getValue(); - if ( value instanceof final Component component ) { + if ( property.getValue() instanceof final Component component ) { + final var collector = context.getMetadataCollector(); if ( component.isGeneric() && component.getPropertySpan() > 0 - && context.getMetadataCollector().getGenericComponent( component.getComponentClass() ) == null ) { + && collector.getGenericComponent( component.getComponentClass() ) == null ) { // If we didn't already, register the generic component to use it later // as the metamodel type for generic embeddable attributes final Component copy = component.copy(); copy.setGeneric( false ); copy.getProperties().clear(); - final Map declaredMembers = getDeclaredAttributeMembers( + final var declaredMembers = getDeclaredAttributeMembers( memberDetails.getType().determineRawClass(), component.getProperty( 0 ).getPropertyAccessorName() ); - for ( Property prop : component.getProperties() ) { - final MemberDetails declaredMember = declaredMembers.get( prop.getName() ); + for ( var prop : component.getProperties() ) { + final var declaredMember = declaredMembers.get( prop.getName() ); if ( declaredMember == null ) { // This can happen for generic custom composite user types copy.addProperty( prop ); @@ -241,7 +235,7 @@ public static void handleGenericComponentProperty(Property property, MemberDetai ); } } - context.getMetadataCollector().registerGenericComponent( copy ); + collector.registerGenericComponent( copy ); } } } @@ -249,7 +243,7 @@ public static void handleGenericComponentProperty(Property property, MemberDetai private void addPropertyToPersistentClass(Property property, MemberDetails memberDetails, ClassDetails declaringClass) { handleGenericComponentProperty( property, memberDetails, getContext() ); if ( declaringClass != null ) { - final InheritanceState inheritanceState = inheritanceStatePerClass.get( declaringClass ); + final var inheritanceState = inheritanceStatePerClass.get( declaringClass ); if ( inheritanceState == null ) { throw new AssertionFailure( "Declaring class is not found in the inheritance state hierarchy: " + declaringClass @@ -273,29 +267,29 @@ public static void addPropertyToMappedSuperclass( MemberDetails memberDetails, ClassDetails declaringClass, MetadataBuildingContext context) { - final MappedSuperclass superclass = context.getMetadataCollector().getMappedSuperclass( declaringClass.toJavaClass() ); + final var superclass = context.getMetadataCollector().getMappedSuperclass( declaringClass.toJavaClass() ); prepareActualProperty( prop, memberDetails, true, context, superclass::addDeclaredProperty ); } static void prepareActualProperty( - Property prop, + Property property, MemberDetails memberDetails, boolean allowCollections, MetadataBuildingContext context, Consumer propertyConsumer) { if ( memberDetails.getDeclaringType().getGenericSuperType() == null ) { - propertyConsumer.accept( prop ); + propertyConsumer.accept( property ); return; } if ( memberDetails.getType().isResolved() ) { // Avoid copying when the property doesn't depend on a type variable - propertyConsumer.accept( prop ); + propertyConsumer.accept( property ); return; } // If the property depends on a type variable, we have to copy it and the Value - final Property actualProperty = prop.copy(); + final Property actualProperty = property.copy(); actualProperty.setGeneric( true ); actualProperty.setReturnedClassName( memberDetails.getType().getName() ); final Value value = actualProperty.getValue().copy(); @@ -305,14 +299,14 @@ static void prepareActualProperty( } // The owner is a MappedSuperclass which is not a PersistentClass, so set it to null // collection.setOwner( null ); - collection.setRole( memberDetails.getDeclaringType().getName() + "." + prop.getName() ); + collection.setRole( memberDetails.getDeclaringType().getName() + "." + property.getName() ); // To copy the element and key values, we need to defer setting the type name until the CollectionBinder ran - final Value originalValue = prop.getValue(); + final Value originalValue = property.getValue(); context.getMetadataCollector().addSecondPass( new SecondPass() { @Override - public void doSecondPass(Map persistentClasses) throws MappingException { - final Collection initializedCollection = (Collection) originalValue; + public void doSecondPass(Map persistentClasses) { + final var initializedCollection = (Collection) originalValue; final Value element = initializedCollection.getElement().copy(); setTypeName( element, memberDetails.getElementType().getName() ); if ( initializedCollection instanceof IndexedCollection indexedCollection ) { @@ -332,7 +326,7 @@ public void doSecondPass(Map persistentClasses) throws MappingException { } if ( value instanceof Component component ) { - final Class componentClass = component.getComponentClass(); + final var componentClass = component.getComponentClass(); if ( component.isGeneric() ) { actualProperty.setValue( context.getMetadataCollector().getGenericComponent( componentClass ) ); } @@ -342,7 +336,7 @@ public void doSecondPass(Map persistentClasses) throws MappingException { component.clearProperties(); } else { - final Iterator propertyIterator = component.getProperties().iterator(); + final var propertyIterator = component.getProperties().iterator(); while ( propertyIterator.hasNext() ) { try { propertyIterator.next().getGetter( componentClass ); @@ -378,15 +372,17 @@ private static void applyAttributeMembers( ClassDetails classDetails, String accessType, Map members) { - final List collectedMembers = switch ( accessType ) { + final var collectedMembers = switch ( accessType ) { case ACCESS_FIELD -> classDetails.getFields(); case ACCESS_PROPERTY -> classDetails.getMethods(); case ACCESS_RECORD -> classDetails.getRecordComponents(); default -> throw new IllegalArgumentException( "Unknown access type " + accessType ); }; - collectedMembers.stream() - .filter( MemberDetails::isPersistable ) - .forEach( member -> members.put( member.resolveAttributeName(), member ) ); + for ( var member : collectedMembers ) { + if ( member.isPersistable() ) { + members.put( member.resolveAttributeName(), member ); + } + } } private static void setTypeName(Value value, String typeName) { @@ -410,7 +406,7 @@ else if ( value instanceof SimpleValue simpleValue ) { private void addPropertyToJoin(Property property, MemberDetails memberDetails, ClassDetails declaringClass, Join join) { if ( declaringClass != null ) { - final InheritanceState inheritanceState = inheritanceStatePerClass.get( declaringClass ); + final var inheritanceState = inheritanceStatePerClass.get( declaringClass ); if ( inheritanceState == null ) { throw new AssertionFailure( "Declaring class is not found in the inheritance state hierarchy: " + declaringClass @@ -435,8 +431,8 @@ private void addPropertyToJoin(Property property, MemberDetails memberDetails, C */ private Map getJoinsPerRealTableName() { if ( joinsPerRealTableName == null ) { - joinsPerRealTableName = CollectionHelper.mapOfSize( joins.size() ); - for (Join join : joins.values()) { + joinsPerRealTableName = mapOfSize( joins.size() ); + for ( Join join : joins.values() ) { joinsPerRealTableName.put( join.getTable().getName(), join ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionBinder.java index 229646b5bf95..4d7baad63e1b 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionBinder.java @@ -21,7 +21,6 @@ import org.hibernate.annotations.*; import org.hibernate.boot.model.IdentifierGeneratorDefinition; import org.hibernate.boot.models.JpaAnnotations; -import org.hibernate.boot.models.annotations.internal.JoinColumnJpaAnnotation; import org.hibernate.boot.models.annotations.internal.MapKeyColumnJpaAnnotation; import org.hibernate.boot.spi.AccessType; import org.hibernate.boot.spi.InFlightMetadataCollector; @@ -29,20 +28,15 @@ import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.PropertyData; import org.hibernate.boot.spi.SecondPass; -import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.hibernate.engine.spi.FilterDefinition; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.PropertiesHelper; import org.hibernate.internal.util.collections.ArrayHelper; import org.hibernate.jdbc.Expectation; -import org.hibernate.mapping.Any; import org.hibernate.mapping.Backref; import org.hibernate.mapping.CheckConstraint; import org.hibernate.mapping.Collection; import org.hibernate.mapping.Column; -import org.hibernate.mapping.Component; import org.hibernate.mapping.DependantValue; -import org.hibernate.mapping.Join; import org.hibernate.mapping.KeyValue; import org.hibernate.mapping.ManyToOne; import org.hibernate.mapping.PersistentClass; @@ -80,7 +74,6 @@ import jakarta.persistence.ManyToMany; import jakarta.persistence.MapKey; import jakarta.persistence.MapKeyColumn; -import jakarta.persistence.MapKeyJoinColumn; import jakarta.persistence.OneToMany; import jakarta.persistence.OrderBy; import jakarta.persistence.OrderColumn; @@ -113,6 +106,9 @@ import static org.hibernate.boot.model.internal.EmbeddableBinder.fillEmbeddable; import static org.hibernate.boot.model.internal.GeneratorBinder.visitIdGeneratorDefinitions; import static org.hibernate.boot.model.internal.PropertyHolderBuilder.buildPropertyHolder; +import static org.hibernate.boot.model.internal.QueryBinder.bindNativeQuery; +import static org.hibernate.boot.model.internal.QueryBinder.bindQuery; +import static org.hibernate.boot.models.annotations.internal.JoinColumnJpaAnnotation.toJoinColumn; import static org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle.fromResultCheckStyle; import static org.hibernate.internal.CoreLogging.messageLogger; import static org.hibernate.internal.util.ReflectHelper.getDefaultSupplier; @@ -217,44 +213,44 @@ public static void bindCollection( MetadataBuildingContext context, Map inheritanceStatePerClass, AnnotatedJoinColumns joinColumns) { - final ModelsContext modelsContext = context.getBootstrapContext().getModelsContext(); - final MemberDetails property = inferredData.getAttributeMember(); + final var modelsContext = context.getBootstrapContext().getModelsContext(); + final var memberDetails = inferredData.getAttributeMember(); - final OneToMany oneToManyAnn = property.getAnnotationUsage( OneToMany.class, modelsContext ); - final ManyToMany manyToManyAnn = property.getAnnotationUsage( ManyToMany.class, modelsContext ); - final ElementCollection elementCollectionAnn = property.getAnnotationUsage( ElementCollection.class, modelsContext ); - checkAnnotations( propertyHolder, inferredData, property, oneToManyAnn, manyToManyAnn, elementCollectionAnn ); + final var oneToManyAnn = memberDetails.getAnnotationUsage( OneToMany.class, modelsContext ); + final var manyToManyAnn = memberDetails.getAnnotationUsage( ManyToMany.class, modelsContext ); + final var elementCollectionAnn = memberDetails.getAnnotationUsage( ElementCollection.class, modelsContext ); + checkAnnotations( propertyHolder, inferredData, memberDetails, oneToManyAnn, manyToManyAnn, elementCollectionAnn ); - final CollectionBinder collectionBinder = getCollectionBinder( property, hasMapKeyAnnotation( property ), context ); + final var collectionBinder = getCollectionBinder( memberDetails, hasMapKeyAnnotation( memberDetails ), context ); collectionBinder.setIndexColumn( getIndexColumn( propertyHolder, inferredData, entityBinder, context ) ); - collectionBinder.setMapKey( property.getAnnotationUsage( MapKey.class, modelsContext ) ); + collectionBinder.setMapKey( memberDetails.getAnnotationUsage( MapKey.class, modelsContext ) ); collectionBinder.setPropertyName( inferredData.getPropertyName() ); - collectionBinder.setJpaOrderBy( property.getAnnotationUsage( OrderBy.class, modelsContext ) ); - collectionBinder.setSqlOrder( getOverridableAnnotation( property, SQLOrder.class, context ) ); - collectionBinder.setNaturalSort( property.getAnnotationUsage( SortNatural.class, modelsContext ) ); - collectionBinder.setComparatorSort( property.getAnnotationUsage( SortComparator.class, modelsContext ) ); - collectionBinder.setCache( property.getAnnotationUsage( Cache.class, modelsContext ) ); - collectionBinder.setQueryCacheLayout( property.getAnnotationUsage( QueryCacheLayout.class, modelsContext ) ); + collectionBinder.setJpaOrderBy( memberDetails.getAnnotationUsage( OrderBy.class, modelsContext ) ); + collectionBinder.setSqlOrder( getOverridableAnnotation( memberDetails, SQLOrder.class, context ) ); + collectionBinder.setNaturalSort( memberDetails.getAnnotationUsage( SortNatural.class, modelsContext ) ); + collectionBinder.setComparatorSort( memberDetails.getAnnotationUsage( SortComparator.class, modelsContext ) ); + collectionBinder.setCache( memberDetails.getAnnotationUsage( Cache.class, modelsContext ) ); + collectionBinder.setQueryCacheLayout( memberDetails.getAnnotationUsage( QueryCacheLayout.class, modelsContext ) ); collectionBinder.setPropertyHolder(propertyHolder); - collectionBinder.setNotFoundAction( notFoundAction( propertyHolder, inferredData, property, manyToManyAnn, modelsContext ) ); + collectionBinder.setNotFoundAction( notFoundAction( propertyHolder, inferredData, memberDetails, manyToManyAnn, modelsContext ) ); collectionBinder.setElementType( inferredData.getClassOrElementType() ); collectionBinder.setAccessType( inferredData.getDefaultAccess() ); - collectionBinder.setEmbedded( property.hasAnnotationUsage( Embedded.class, modelsContext ) ); - collectionBinder.setProperty( property ); - collectionBinder.setOnDeleteActionAction( onDeleteAction( property ) ); + collectionBinder.setEmbedded( memberDetails.hasAnnotationUsage( Embedded.class, modelsContext ) ); + collectionBinder.setProperty( memberDetails ); + collectionBinder.setOnDeleteActionAction( onDeleteAction( memberDetails ) ); collectionBinder.setInheritanceStatePerClass( inheritanceStatePerClass ); collectionBinder.setDeclaringClass( inferredData.getDeclaringClass() ); - final Cascade hibernateCascade = property.getAnnotationUsage( Cascade.class, modelsContext ); + final var hibernateCascade = memberDetails.getAnnotationUsage( Cascade.class, modelsContext ); collectionBinder.setElementColumns( elementColumns( propertyHolder, nullability, entityBinder, context, - property, - virtualPropertyData( inferredData, property ) + memberDetails, + virtualPropertyData( inferredData, memberDetails ) // comment ) ); @@ -263,7 +259,7 @@ public static void bindCollection( inferredData, entityBinder, context, - property + memberDetails ) ); collectionBinder.setMapKeyManyToManyColumns( mapKeyJoinColumns( @@ -271,11 +267,11 @@ public static void bindCollection( inferredData, entityBinder, context, - property + memberDetails ) ); bindJoinedTableAssociation( - property, + memberDetails, context, entityBinder, collectionBinder, @@ -285,7 +281,7 @@ public static void bindCollection( propertyHolder, inferredData, context, - property, + memberDetails, joinColumns, oneToManyAnn, manyToManyAnn, @@ -300,11 +296,11 @@ public static void bindCollection( collectionBinder.setUpdatable( false ); } - if ( property.hasAnnotationUsage( CollectionId.class, modelsContext ) ) { + if ( memberDetails.hasAnnotationUsage( CollectionId.class, modelsContext ) ) { //do not compute the generators unless necessary final HashMap availableGenerators = new HashMap<>(); visitIdGeneratorDefinitions( - property.getDeclaringType(), + memberDetails.getDeclaringType(), definition -> { if ( !definition.getName().isEmpty() ) { availableGenerators.put( definition.getName(), definition ); @@ -313,7 +309,7 @@ public static void bindCollection( context ); visitIdGeneratorDefinitions( - property, + memberDetails, definition -> { if ( !definition.getName().isEmpty() ) { availableGenerators.put( definition.getName(), definition ); @@ -333,7 +329,7 @@ private static NotFoundAction notFoundAction( MemberDetails property, ManyToMany manyToManyAnn, ModelsContext sourceModelContext) { - final NotFound notFound = property.getAnnotationUsage( NotFound.class, sourceModelContext ); + final var notFound = property.getAnnotationUsage( NotFound.class, sourceModelContext ); if ( notFound != null ) { if ( manyToManyAnn == null ) { throw new AnnotationException( "Collection '" + getPath(propertyHolder, inferredData) @@ -364,7 +360,7 @@ private static AnnotatedJoinColumns mapKeyJoinColumns( } private static OnDeleteAction onDeleteAction(MemberDetails property) { - final OnDelete onDelete = property.getDirectAnnotationUsage( OnDelete.class ); + final var onDelete = property.getDirectAnnotationUsage( OnDelete.class ); return onDelete == null ? null : onDelete.action(); } @@ -426,10 +422,10 @@ private static IndexColumn getIndexColumn( PropertyData inferredData, EntityBinder entityBinder, MetadataBuildingContext context) { - final MemberDetails property = inferredData.getAttributeMember(); + final var memberDetails = inferredData.getAttributeMember(); return IndexColumn.fromAnnotations( - property.getDirectAnnotationUsage( OrderColumn.class ), - property.getDirectAnnotationUsage( ListIndexBase.class ), + memberDetails.getDirectAnnotationUsage( OrderColumn.class ), + memberDetails.getDirectAnnotationUsage( ListIndexBase.class ), propertyHolder, inferredData, entityBinder.getSecondaryTables(), @@ -572,9 +568,9 @@ else if ( property.hasDirectAnnotationUsage( Columns.class ) ) { private static JoinColumn[] mapKeyJoinColumnAnnotations( MemberDetails property, MetadataBuildingContext context) { - final ModelsContext modelsContext = context.getBootstrapContext().getModelsContext(); + final var modelsContext = context.getBootstrapContext().getModelsContext(); - final MapKeyJoinColumn[] mapKeyJoinColumns = property.getRepeatedAnnotationUsages( + final var mapKeyJoinColumns = property.getRepeatedAnnotationUsages( JpaAnnotations.MAP_KEY_JOIN_COLUMN, modelsContext ); @@ -582,16 +578,13 @@ private static JoinColumn[] mapKeyJoinColumnAnnotations( if ( isEmpty( mapKeyJoinColumns ) ) { return null; } - - final JoinColumn[] joinColumns = new JoinColumn[mapKeyJoinColumns.length]; - for ( int i = 0; i < mapKeyJoinColumns.length; i++ ) { - final JoinColumn joinColumn = JoinColumnJpaAnnotation.toJoinColumn( - mapKeyJoinColumns[i], - modelsContext - ); - joinColumns[i] = joinColumn; + else { + final var joinColumns = new JoinColumn[mapKeyJoinColumns.length]; + for ( int i = 0; i < mapKeyJoinColumns.length; i++ ) { + joinColumns[i] = toJoinColumn( mapKeyJoinColumns[i], modelsContext ); + } + return joinColumns; } - return joinColumns; } private static AnnotatedColumns mapKeyColumns( @@ -601,18 +594,13 @@ private static AnnotatedColumns mapKeyColumns( MetadataBuildingContext context, MemberDetails property) { // Comment comment) { - final jakarta.persistence.Column column; - if ( property.hasDirectAnnotationUsage( MapKeyColumn.class ) ) { - column = MapKeyColumnJpaAnnotation.toColumnAnnotation( - property.getDirectAnnotationUsage( MapKeyColumn.class ), - context.getBootstrapContext().getModelsContext() - ); - } - else { - column = null; - } - return buildColumnsFromAnnotations( - column == null ? null : new jakarta.persistence.Column[] { column }, + return AnnotatedColumn.buildColumnFromAnnotations( + property.hasDirectAnnotationUsage( MapKeyColumn.class ) + ? MapKeyColumnJpaAnnotation.toColumnAnnotation( + property.getDirectAnnotationUsage( MapKeyColumn.class ), + context.getBootstrapContext().getModelsContext() + ) + : null, // comment, Nullability.FORCED_NOT_NULL, propertyHolder, @@ -631,9 +619,9 @@ private static void bindJoinedTableAssociation( PropertyHolder propertyHolder, PropertyData inferredData, String mappedBy) { - final TableBinder associationTableBinder = new TableBinder(); - final JoinTable assocTable = propertyHolder.getJoinTable( property ); - final CollectionTable collectionTable = property.getDirectAnnotationUsage( CollectionTable.class ); + final var associationTableBinder = new TableBinder(); + final var assocTable = propertyHolder.getJoinTable( property ); + final var collectionTable = property.getDirectAnnotationUsage( CollectionTable.class ); final JoinColumn[] annJoins; final JoinColumn[] annInverseJoins; @@ -785,12 +773,10 @@ private static CollectionBinder getCollectionBinder( MemberDetails property, boolean isHibernateExtensionMapping, MetadataBuildingContext buildingContext) { - - final CollectionBinder binder; - final CollectionType typeAnnotation = + final var typeAnnotation = property.getAnnotationUsage( CollectionType.class, buildingContext.getBootstrapContext().getModelsContext() ); - binder = typeAnnotation != null + final var binder = typeAnnotation != null ? createBinderFromCustomTypeAnnotation( property, typeAnnotation, buildingContext ) : createBinderAutomatically( property, buildingContext ); binder.setIsHibernateExtensionMapping( isHibernateExtensionMapping ); @@ -798,8 +784,8 @@ private static CollectionBinder getCollectionBinder( } private static CollectionBinder createBinderAutomatically(MemberDetails property, MetadataBuildingContext context) { - final CollectionClassification classification = determineCollectionClassification( property, context ); - final CollectionTypeRegistrationDescriptor typeRegistration = + final var classification = determineCollectionClassification( property, context ); + final var typeRegistration = context.getMetadataCollector().findCollectionTypeRegistration( classification ); return typeRegistration != null ? createBinderFromTypeRegistration( property, classification, typeRegistration, context ) @@ -826,7 +812,7 @@ private static CollectionBinder createBinderFromTypeRegistration( } private static CollectionBinder createBinderFromProperty(MemberDetails property, MetadataBuildingContext context) { - final CollectionClassification classification = determineCollectionClassification( property, context ); + final var classification = determineCollectionClassification( property, context ); return createBinder( property, null, classification, context ); } @@ -835,8 +821,7 @@ private static CollectionBinder createBinderFromCustomTypeAnnotation( CollectionType typeAnnotation, MetadataBuildingContext buildingContext) { determineSemanticJavaType( property ); - final ManagedBean customTypeBean = - resolveCustomType( property, typeAnnotation, buildingContext ); + final var customTypeBean = resolveCustomType( property, typeAnnotation, buildingContext ); return createBinder( property, () -> customTypeBean, @@ -859,10 +844,10 @@ private static ManagedBean resolveCustomType( } private static Properties extractParameters(CollectionType typeAnnotation) { - final Parameter[] parameterAnnotations = typeAnnotation.parameters(); - final Properties configParams = new Properties( parameterAnnotations.length ); - for ( Parameter parameterAnnotation : parameterAnnotations ) { - configParams.put( parameterAnnotation.name(), parameterAnnotation.value() ); + final var parameters = typeAnnotation.parameters(); + final var configParams = new Properties( parameters.length ); + for ( var parameter : parameters ) { + configParams.put( parameter.name(), parameter.value() ); } return configParams; } @@ -872,10 +857,8 @@ private static CollectionBinder createBinder( Supplier> customTypeBeanAccess, CollectionClassification classification, MetadataBuildingContext buildingContext) { - final TypeDetails elementType = property.getElementType(); - return switch ( classification ) { - case ARRAY -> elementType.getTypeKind() == TypeDetails.Kind.PRIMITIVE + case ARRAY -> property.getElementType().getTypeKind() == TypeDetails.Kind.PRIMITIVE ? new PrimitiveArrayBinder( customTypeBeanAccess, buildingContext ) : new ArrayBinder( customTypeBeanAccess, buildingContext ); case BAG -> new BagBinder( customTypeBeanAccess, buildingContext ); @@ -895,7 +878,7 @@ private static CollectionClassification determineCollectionClassification( return CollectionClassification.ARRAY; } - final ModelsContext modelsContext = buildingContext.getBootstrapContext().getModelsContext(); + final var modelsContext = buildingContext.getBootstrapContext().getModelsContext(); if ( !property.hasAnnotationUsage( Bag.class, modelsContext ) ) { return determineCollectionClassification( determineSemanticJavaType( property ), property, buildingContext ); } @@ -912,8 +895,7 @@ private static CollectionClassification determineCollectionClassification( + "' is annotated '@Bag' and may not also be annotated '@ListIndexBase'" ); } - final ClassDetails collectionClassDetails = property.getType().determineRawClass(); - final Class collectionJavaType = collectionClassDetails.toJavaClass(); + final var collectionJavaType = property.getType().determineRawClass().toJavaClass(); if ( java.util.List.class.equals( collectionJavaType ) || java.util.Collection.class.equals( collectionJavaType ) ) { return CollectionClassification.BAG; @@ -965,15 +947,14 @@ private static CollectionClassification determineCollectionClassification( return CollectionClassification.BAG; } - final ModelsContext modelsContext = - buildingContext.getBootstrapContext().getModelsContext(); - final ManyToMany manyToMany = property.getAnnotationUsage( ManyToMany.class, modelsContext ); + final var modelsContext = buildingContext.getBootstrapContext().getModelsContext(); + final var manyToMany = property.getAnnotationUsage( ManyToMany.class, modelsContext ); if ( manyToMany != null && !manyToMany.mappedBy().isBlank() ) { // We don't support @OrderColumn on the non-owning side of a many-to-many association. return CollectionClassification.BAG; } - final OneToMany oneToMany = property.getAnnotationUsage( OneToMany.class, modelsContext ); + final var oneToMany = property.getAnnotationUsage( OneToMany.class, modelsContext ); if ( oneToMany != null && !oneToMany.mappedBy().isBlank() ) { // Unowned to-many mappings are always considered BAG by default return CollectionClassification.BAG; @@ -1000,12 +981,9 @@ private static CollectionClassification determineCollectionClassification( } if ( java.util.Collection.class.isAssignableFrom( semanticJavaType ) ) { - if ( property.hasDirectAnnotationUsage( CollectionId.class ) ) { - return CollectionClassification.ID_BAG; - } - else { - return CollectionClassification.BAG; - } + return property.hasDirectAnnotationUsage( CollectionId.class ) + ? CollectionClassification.ID_BAG + : CollectionClassification.BAG; } return null; @@ -1013,9 +991,8 @@ private static CollectionClassification determineCollectionClassification( private static Class determineSemanticJavaType(MemberDetails property) { if ( property.isPlural() ) { - final ClassDetails collectionClassDetails = property.getType().determineRawClass(); - final Class collectionClass = collectionClassDetails.toJavaClass(); - return inferCollectionClassFromSubclass( collectionClass ); + return inferCollectionClassFromSubclass( + property.getType().determineRawClass().toJavaClass() ); } else { throw new AnnotationException( @@ -1030,7 +1007,7 @@ private static Class determineSemanticJavaType(MemberDetails property) { } private static Class inferCollectionClassFromSubclass(Class clazz) { - for ( Class priorityClass : INFERRED_CLASS_PRIORITY ) { + for ( var priorityClass : INFERRED_CLASS_PRIORITY ) { if ( priorityClass.isAssignableFrom( clazz ) ) { return priorityClass; } @@ -1092,7 +1069,7 @@ private void bind() { defineFetchingStrategy(); collection.setMutable( isMutable() ); //work on association - boolean isUnowned = isUnownedCollection(); + final boolean isUnowned = isUnownedCollection(); bindOptimisticLock( isUnowned ); applySortingAndOrdering(); bindCache(); @@ -1122,7 +1099,7 @@ private void checkMapKeyColumn() { } private void scheduleSecondPass(boolean isMappedBy) { - final InFlightMetadataCollector metadataCollector = getMetadataCollector(); + final var metadataCollector = getMetadataCollector(); //many to many may need some second pass information if ( !oneToMany && isMappedBy ) { metadataCollector.addMappedBy( getElementType().getName(), mappedBy, propertyName ); @@ -1135,7 +1112,7 @@ private void scheduleSecondPass(boolean isMappedBy) { } private void bindOptimisticLock(boolean isMappedBy) { - final OptimisticLock lockAnn = property.getDirectAnnotationUsage( OptimisticLock.class ); + final var lockAnn = property.getDirectAnnotationUsage( OptimisticLock.class ); final boolean includeInOptimisticLockChecks = lockAnn != null ? !lockAnn.excluded() : !isMappedBy; collection.setOptimisticLocked( includeInOptimisticLockChecks ); } @@ -1210,7 +1187,7 @@ private boolean hasExplicitJoinColumn() { private void bindProperty() { //property building - PropertyBinder binder = new PropertyBinder(); + final var binder = new PropertyBinder(); binder.setName( propertyName ); binder.setValue( collection ); binder.setCascade( cascadeTypes ); @@ -1218,7 +1195,7 @@ private void bindProperty() { collection.setOrphanDelete( true ); } binder.setLazy( collection.isLazy() ); - final LazyGroup lazyGroupAnnotation = property.getDirectAnnotationUsage( LazyGroup.class ); + final var lazyGroupAnnotation = property.getDirectAnnotationUsage( LazyGroup.class ); if ( lazyGroupAnnotation != null ) { binder.setLazyGroup( lazyGroupAnnotation.value() ); } @@ -1237,75 +1214,74 @@ private void bindProperty() { binder.callAttributeBindersInSecondPass( prop ); } - @SuppressWarnings("deprecation") private void bindLoader() { //SQL overriding - final SQLInsert sqlInsert = property.getDirectAnnotationUsage( SQLInsert.class ); + final var sqlInsert = property.getDirectAnnotationUsage( SQLInsert.class ); if ( sqlInsert != null ) { collection.setCustomSQLInsert( sqlInsert.sql().trim(), sqlInsert.callable(), fromResultCheckStyle( sqlInsert.check() ) ); - final Class verifier = sqlInsert.verify(); - if ( !Expectation.class.equals( verifier ) ) { + final var verifier = sqlInsert.verify(); + if ( verifier != Expectation.class ) { collection.setInsertExpectation( getDefaultSupplier( verifier ) ); } } - final SQLUpdate sqlUpdate = property.getDirectAnnotationUsage( SQLUpdate.class ); + final var sqlUpdate = property.getDirectAnnotationUsage( SQLUpdate.class ); if ( sqlUpdate != null ) { collection.setCustomSQLUpdate( sqlUpdate.sql().trim(), sqlUpdate.callable(), fromResultCheckStyle( sqlUpdate.check() ) ); - final Class verifier = sqlUpdate.verify(); - if ( !Expectation.class.equals( verifier ) ) { + final var verifier = sqlUpdate.verify(); + if ( verifier != Expectation.class ) { collection.setUpdateExpectation( getDefaultSupplier( verifier ) ); } } - final SQLDelete sqlDelete = property.getDirectAnnotationUsage( SQLDelete.class ); + final var sqlDelete = property.getDirectAnnotationUsage( SQLDelete.class ); if ( sqlDelete != null ) { collection.setCustomSQLDelete( sqlDelete.sql().trim(), sqlDelete.callable(), fromResultCheckStyle( sqlDelete.check() ) ); - final Class verifier = sqlDelete.verify(); - if ( !Expectation.class.equals( verifier ) ) { + final var verifier = sqlDelete.verify(); + if ( verifier != Expectation.class ) { collection.setDeleteExpectation( getDefaultSupplier( verifier ) ); } } - final SQLDeleteAll sqlDeleteAll = property.getDirectAnnotationUsage( SQLDeleteAll.class ); + final var sqlDeleteAll = property.getDirectAnnotationUsage( SQLDeleteAll.class ); if ( sqlDeleteAll != null ) { collection.setCustomSQLDeleteAll( sqlDeleteAll.sql().trim(), sqlDeleteAll.callable(), fromResultCheckStyle( sqlDeleteAll.check() ) ); - final Class verifier = sqlDeleteAll.verify(); - if ( !Expectation.class.equals( verifier ) ) { + final var verifier = sqlDeleteAll.verify(); + if ( verifier != Expectation.class ) { collection.setDeleteAllExpectation( getDefaultSupplier( verifier ) ); } } - final SQLSelect sqlSelect = property.getDirectAnnotationUsage( SQLSelect.class ); + final var sqlSelect = property.getDirectAnnotationUsage( SQLSelect.class ); if ( sqlSelect != null ) { final String loaderName = getRole() + "$SQLSelect"; collection.setLoaderName( loaderName ); // TODO: pass in the collection element type here - QueryBinder.bindNativeQuery( loaderName, sqlSelect, null, buildingContext ); + bindNativeQuery( loaderName, sqlSelect, null, buildingContext ); } - final HQLSelect hqlSelect = property.getDirectAnnotationUsage( HQLSelect.class ); + final var hqlSelect = property.getDirectAnnotationUsage( HQLSelect.class ); if ( hqlSelect != null ) { final String loaderName = getRole() + "$HQLSelect"; collection.setLoaderName( loaderName ); - QueryBinder.bindQuery( loaderName, hqlSelect, buildingContext ); + bindQuery( loaderName, hqlSelect, buildingContext ); } } @@ -1422,7 +1398,7 @@ private void handleFetchProfileOverrides() { } private void handleFetch() { - final Fetch fetchAnnotation = property.getDirectAnnotationUsage( Fetch.class ); + final var fetchAnnotation = property.getDirectAnnotationUsage( Fetch.class ); if ( fetchAnnotation != null ) { // Hibernate @Fetch annotation takes precedence setHibernateFetchMode( fetchAnnotation.value() ); @@ -1452,16 +1428,15 @@ private void setHibernateFetchMode(org.hibernate.annotations.FetchMode fetchMode } private void handleLazy() { - final FetchType jpaFetchType = getJpaFetchType(); - collection.setLazy( jpaFetchType == LAZY ); + collection.setLazy( getJpaFetchType() == LAZY ); collection.setExtraLazy( false ); } private FetchType getJpaFetchType() { - final OneToMany oneToMany = property.getDirectAnnotationUsage( OneToMany.class ); - final ManyToMany manyToMany = property.getDirectAnnotationUsage( ManyToMany.class ); - final ElementCollection elementCollection = property.getDirectAnnotationUsage( ElementCollection.class ); - final ManyToAny manyToAny = property.getDirectAnnotationUsage( ManyToAny.class ); + final var oneToMany = property.getDirectAnnotationUsage( OneToMany.class ); + final var manyToMany = property.getDirectAnnotationUsage( ManyToMany.class ); + final var elementCollection = property.getDirectAnnotationUsage( ElementCollection.class ); + final var manyToAny = property.getDirectAnnotationUsage( ManyToAny.class ); if ( oneToMany != null ) { return oneToMany.fetch(); } @@ -1548,7 +1523,7 @@ private boolean isReversePropertyInJoin( } private boolean noAssociationTable(Map persistentClasses) { - final PersistentClass persistentClass = persistentClasses.get( getElementType().getName() ); + final var persistentClass = persistentClasses.get( getElementType().getName() ); return persistentClass != null && !isReversePropertyInJoin( getElementType(), persistentClass, persistentClasses ) && oneToMany @@ -1575,14 +1550,14 @@ protected void bindOneToManySecondPass(Map persistentCl logOneToManySecondPass(); - final org.hibernate.mapping.OneToMany oneToMany = + final var oneToMany = new org.hibernate.mapping.OneToMany( buildingContext, getCollection().getOwner() ); collection.setElement( oneToMany ); oneToMany.setReferencedEntityName( getElementType().getName() ); oneToMany.setNotFoundAction( notFoundAction ); final String referencedEntityName = oneToMany.getReferencedEntityName(); - final PersistentClass associatedClass = persistentClasses.get( referencedEntityName ); + final var associatedClass = persistentClasses.get( referencedEntityName ); handleJpaOrderBy( collection, associatedClass ); if ( associatedClass == null ) { throw new MappingException( @@ -1592,7 +1567,7 @@ protected void bindOneToManySecondPass(Map persistentCl } oneToMany.setAssociatedClass( associatedClass ); - final Map joins = getMetadataCollector().getJoins( referencedEntityName ); + final var joins = getMetadataCollector().getJoins( referencedEntityName ); foreignJoinColumns.setPropertyHolder( buildPropertyHolder( associatedClass, joins, @@ -1600,18 +1575,18 @@ protected void bindOneToManySecondPass(Map persistentCl inheritanceStatePerClass ) ); foreignJoinColumns.setJoins( joins ); - if ( foreignJoinColumns.hasMappedBy() ) { - collection.setCollectionTable( associatedClass.getRecursiveProperty( foreignJoinColumns.getMappedBy() ).getValue().getTable() ); - } - else { - collection.setCollectionTable( foreignJoinColumns.getTable() ); - } + final var collectionTable = + foreignJoinColumns.hasMappedBy() + ? associatedClass.getRecursiveProperty( foreignJoinColumns.getMappedBy() ) + .getValue().getTable() + : foreignJoinColumns.getTable(); + collection.setCollectionTable( collectionTable ); bindSynchronize(); bindFilters( false ); handleWhere( false ); - final PersistentClass targetEntity = persistentClasses.get( getElementType().getName() ); + final var targetEntity = persistentClasses.get( getElementType().getName() ); bindCollectionSecondPass( targetEntity, foreignJoinColumns ); if ( !collection.isInverse() && !collection.getKey().isNullable() ) { @@ -1620,10 +1595,10 @@ protected void bindOneToManySecondPass(Map persistentCl } private void createOneToManyBackref(org.hibernate.mapping.OneToMany oneToMany) { - final InFlightMetadataCollector collector = getMetadataCollector(); + final var collector = getMetadataCollector(); // for non-inverse one-to-many, with a not-null fk, add a backref! final String entityName = oneToMany.getReferencedEntityName(); - final PersistentClass referenced = collector.getEntityBinding( entityName ); + final var referencedEntity = collector.getEntityBinding( entityName ); final Backref backref = new Backref(); final String backrefName = '_' + foreignJoinColumns.getPropertyName() + '_' + foreignJoinColumns.getColumns().get(0).getLogicalColumnName() @@ -1635,7 +1610,7 @@ private void createOneToManyBackref(org.hibernate.mapping.OneToMany oneToMany) { backref.setCollectionRole( getRole() ); backref.setEntityName( collection.getOwner().getEntityName() ); backref.setValue( collection.getKey() ); - referenced.addProperty( backref ); + referencedEntity.addProperty( backref ); } private void handleJpaOrderBy(Collection collection, PersistentClass associatedClass) { @@ -1649,7 +1624,7 @@ private void handleJpaOrderBy(Collection collection, PersistentClass associatedC } private void bindSynchronize() { - final Synchronize synchronizeAnnotation = property.getDirectAnnotationUsage( Synchronize.class ); + final var synchronizeAnnotation = property.getDirectAnnotationUsage( Synchronize.class ); if ( synchronizeAnnotation != null ) { for ( String table : synchronizeAnnotation.value() ) { final String physicalName = @@ -1662,52 +1637,57 @@ private void bindSynchronize() { } private String toPhysicalName(String logicalName) { - final JdbcEnvironment jdbcEnvironment = getMetadataCollector().getDatabase().getJdbcEnvironment(); + final var jdbcEnvironment = getMetadataCollector().getDatabase().getJdbcEnvironment(); return buildingContext.getBuildingOptions().getPhysicalNamingStrategy() .toPhysicalTableName( jdbcEnvironment.getIdentifierHelper().toIdentifier( logicalName ), jdbcEnvironment ) .render( jdbcEnvironment.getDialect() ); } - private void bindFilters(boolean hasAssociationTable) { - property.forEachAnnotationUsage( Filter.class, modelsContext(), - usage -> addFilter( hasAssociationTable, usage ) ); - - property.forEachAnnotationUsage( FilterJoinTable.class, modelsContext(), - usage -> addFilterJoinTable( hasAssociationTable, usage ) ); - } - - private void addFilter(boolean hasAssociationTable, Filter filterAnnotation) { - final Map aliasTableMap = new HashMap<>(); - final Map aliasEntityMap = new HashMap<>(); - final SqlFragmentAlias[] aliasAnnotations = filterAnnotation.aliases(); - for ( SqlFragmentAlias aliasAnnotation : aliasAnnotations ) { + private static void fillAliasMaps( + SqlFragmentAlias[] aliases, + Map aliasTableMap, + Map aliasEntityMap) { + for ( var aliasAnnotation : aliases ) { final String alias = aliasAnnotation.alias(); - final String table = aliasAnnotation.table(); if ( isNotBlank( table ) ) { aliasTableMap.put( alias, table ); } - final Class entityClassDetails = aliasAnnotation.entity(); + final var entityClassDetails = aliasAnnotation.entity(); if ( entityClassDetails != void.class ) { aliasEntityMap.put( alias, entityClassDetails.getName() ); } } + } + + private void bindFilters(boolean hasAssociationTable) { + final var context = modelsContext(); + property.forEachAnnotationUsage( Filter.class, context, + usage -> addFilter( hasAssociationTable, usage ) ); + property.forEachAnnotationUsage( FilterJoinTable.class, context, + usage -> addFilterJoinTable( hasAssociationTable, usage ) ); + } + private void addFilter(boolean hasAssociationTable, Filter filter) { + final Map aliasTableMap = new HashMap<>(); + final Map aliasEntityMap = new HashMap<>(); + fillAliasMaps( filter.aliases(), aliasTableMap, aliasEntityMap ); + final String filterCondition = getFilterCondition( filter ); if ( hasAssociationTable ) { collection.addManyToManyFilter( - filterAnnotation.name(), - getFilterCondition( filterAnnotation ), - filterAnnotation.deduceAliasInjectionPoints(), + filter.name(), + filterCondition, + filter.deduceAliasInjectionPoints(), aliasTableMap, aliasEntityMap ); } else { collection.addFilter( - filterAnnotation.name(), - getFilterCondition( filterAnnotation ), - filterAnnotation.deduceAliasInjectionPoints(), + filter.name(), + filterCondition, + filter.deduceAliasInjectionPoints(), aliasTableMap, aliasEntityMap ); @@ -1747,8 +1727,7 @@ private void handleWhere(boolean hasAssociationTable) { } private String getWhereJoinTableClause() { - final SQLJoinTableRestriction joinTableRestriction = - property.getDirectAnnotationUsage( SQLJoinTableRestriction.class ); + final var joinTableRestriction = property.getDirectAnnotationUsage( SQLJoinTableRestriction.class ); return joinTableRestriction != null ? joinTableRestriction.value() : null; } @@ -1763,13 +1742,13 @@ private String getWhereClause() { } private String getWhereOnCollectionClause() { - final SQLRestriction restrictionOnCollection = + final var restrictionOnCollection = getOverridableAnnotation( property, SQLRestriction.class, getBuildingContext() ); return restrictionOnCollection != null ? restrictionOnCollection.value() : null; } private String getWhereOnClassClause() { - final SQLRestriction restrictionOnClass = getOverridableAnnotation( + final var restrictionOnClass = getOverridableAnnotation( property.getAssociatedType().determineRawClass(), SQLRestriction.class, buildingContext @@ -1781,21 +1760,7 @@ private void addFilterJoinTable(boolean hasAssociationTable, FilterJoinTable fil if ( hasAssociationTable ) { final Map aliasTableMap = new HashMap<>(); final Map aliasEntityMap = new HashMap<>(); - final SqlFragmentAlias[] aliasAnnotations = filter.aliases(); - for ( SqlFragmentAlias aliasAnnotation : aliasAnnotations ) { - final String alias = aliasAnnotation.alias(); - - final String table = aliasAnnotation.table(); - if ( isNotBlank( table ) ) { - aliasTableMap.put( alias, table ); - } - - final Class entityClassDetails = aliasAnnotation.entity(); - if ( entityClassDetails != void.class ) { - aliasEntityMap.put( alias, entityClassDetails.getName() ); - } - } - + fillAliasMaps( filter.aliases(), aliasTableMap, aliasEntityMap ); collection.addFilter( filter.name(), getFilterConditionForJoinTable( filter ), @@ -1825,7 +1790,7 @@ private String getFilterCondition(Filter filter) { } private String getDefaultFilterCondition(String name, Annotation annotation) { - final FilterDefinition definition = getMetadataCollector().getFilterDefinition( name ); + final var definition = getMetadataCollector().getFilterDefinition( name ); if ( definition == null ) { throw new AnnotationException( "Collection '" + qualify( propertyHolder.getPath(), propertyName ) + "' has a '@" + annotation.annotationType().getSimpleName() @@ -1888,15 +1853,15 @@ else if ( "desc".equalsIgnoreCase( orderByFragment ) ) { } } - private static String buildOrderById(PersistentClass associatedClass, String order) { - final StringBuilder sb = new StringBuilder(); - for ( Selectable selectable: associatedClass.getIdentifier().getSelectables() ) { - sb.append( selectable.getText() ); - sb.append( order ); - sb.append( ", " ); + private static String buildOrderById(PersistentClass associatedClass, String direction) { + final var order = new StringBuilder(); + for ( var selectable: associatedClass.getIdentifier().getSelectables() ) { + order.append( selectable.getText() ); + order.append( direction ); + order.append( ", " ); } - sb.setLength( sb.length() - 2 ); - return sb.toString(); + order.setLength( order.length() - 2 ); + return order.toString(); } private static String adjustUserSuppliedValueCollectionOrderingFragment(String orderByFragment) { @@ -1933,26 +1898,27 @@ private DependantValue buildCollectionKey(AnnotatedJoinColumns joinColumns, OnDe overrideReferencedPropertyName( collection, joinColumns ); final String referencedPropertyName = collection.getReferencedPropertyName(); - //binding key reference using column - final PersistentClass owner = collection.getOwner(); - final KeyValue keyValue = referencedPropertyName == null - ? owner.getIdentifier() - : (KeyValue) owner.getReferencedProperty( referencedPropertyName ).getValue(); - - final DependantValue key = new DependantValue( buildingContext, collection.getCollectionTable(), keyValue ); + // binding key reference using column + final var owner = collection.getOwner(); + final var keyValue = + referencedPropertyName == null + ? owner.getIdentifier() + : (KeyValue) owner.getReferencedProperty( referencedPropertyName ).getValue(); + + final var key = new DependantValue( buildingContext, collection.getCollectionTable(), keyValue ); key.setTypeName( null ); joinColumns.checkPropertyConsistency(); - final List columns = joinColumns.getColumns(); + final var columns = joinColumns.getColumns(); key.setNullable( columns.isEmpty() || columns.get(0).isNullable() ); key.setUpdateable( columns.isEmpty() || columns.get(0).isUpdatable() ); key.setOnDeleteAction( onDeleteAction ); collection.setKey( key ); if ( property != null ) { - final CollectionTable collectionTableAnn = property.getDirectAnnotationUsage( CollectionTable.class ); - if ( collectionTableAnn != null ) { - final ForeignKey foreignKey = collectionTableAnn.foreignKey(); - final ConstraintMode constraintMode = foreignKey.value(); + final var collectionTable = property.getDirectAnnotationUsage( CollectionTable.class ); + if ( collectionTable != null ) { + final var foreignKey = collectionTable.foreignKey(); + final var constraintMode = foreignKey.value(); if ( constraintMode == NO_CONSTRAINT || constraintMode == PROVIDER_DEFAULT && noConstraintByDefault ) { key.disableForeignKey(); @@ -1963,9 +1929,9 @@ private DependantValue buildCollectionKey(AnnotatedJoinColumns joinColumns, OnDe key.setForeignKeyOptions( foreignKey.options() ); if ( key.getForeignKeyName() == null && key.getForeignKeyDefinition() == null - && collectionTableAnn.joinColumns().length == 1 ) { - final JoinColumn joinColumn = collectionTableAnn.joinColumns()[0]; - final ForeignKey nestedForeignKey = joinColumn.foreignKey(); + && collectionTable.joinColumns().length == 1 ) { + final var joinColumn = collectionTable.joinColumns()[0]; + final var nestedForeignKey = joinColumn.foreignKey(); key.setForeignKeyName( nullIfEmpty( nestedForeignKey.name() ) ); key.setForeignKeyDefinition( nullIfEmpty( nestedForeignKey.foreignKeyDefinition() ) ); key.setForeignKeyOptions( nestedForeignKey.options() ); @@ -1973,17 +1939,17 @@ private DependantValue buildCollectionKey(AnnotatedJoinColumns joinColumns, OnDe } } else { - final JoinTable joinTableAnn = property.getDirectAnnotationUsage( JoinTable.class ); - if ( joinTableAnn != null ) { - final ForeignKey foreignKey = joinTableAnn.foreignKey(); + final var joinTable = property.getDirectAnnotationUsage( JoinTable.class ); + if ( joinTable != null ) { + final var foreignKey = joinTable.foreignKey(); String foreignKeyName = foreignKey.name(); String foreignKeyDefinition = foreignKey.foreignKeyDefinition(); String foreignKeyOptions = foreignKey.options(); ConstraintMode foreignKeyValue = foreignKey.value(); - final JoinColumn[] joinColumnAnnotations = joinTableAnn.joinColumns(); + final var joinColumnAnnotations = joinTable.joinColumns(); if ( !ArrayHelper.isEmpty( joinColumnAnnotations ) ) { - final JoinColumn joinColumnAnn = joinColumnAnnotations[0]; - final ForeignKey joinColumnForeignKey = joinColumnAnn.foreignKey(); + final var joinColumnAnn = joinColumnAnnotations[0]; + final var joinColumnForeignKey = joinColumnAnn.foreignKey(); if ( foreignKeyName.isBlank() ) { foreignKeyName = joinColumnForeignKey.name(); foreignKeyDefinition = joinColumnForeignKey.foreignKeyDefinition(); @@ -2005,24 +1971,24 @@ private DependantValue buildCollectionKey(AnnotatedJoinColumns joinColumns, OnDe } else { final String propertyPath = qualify( propertyHolder.getPath(), property.getName() ); - final ForeignKey foreignKey = propertyHolder.getOverriddenForeignKey( propertyPath ); + final var foreignKey = propertyHolder.getOverriddenForeignKey( propertyPath ); if ( foreignKey != null ) { handleForeignKeyConstraint( noConstraintByDefault, key, foreignKey ); } else { - final OneToMany oneToManyAnn = property.getDirectAnnotationUsage( OneToMany.class ); - final OnDelete onDeleteAnn = property.getDirectAnnotationUsage( OnDelete.class ); - if ( oneToManyAnn != null - && !oneToManyAnn.mappedBy().isBlank() - && ( onDeleteAnn == null || onDeleteAnn.action() != OnDeleteAction.CASCADE ) ) { + final var oneToMany = property.getDirectAnnotationUsage( OneToMany.class ); + final var onDelete = property.getDirectAnnotationUsage( OnDelete.class ); + if ( oneToMany != null + && !oneToMany.mappedBy().isBlank() + && ( onDelete == null || onDelete.action() != OnDeleteAction.CASCADE ) ) { // foreign key should be up to @ManyToOne side // @OnDelete generate "on delete cascade" foreign key key.disableForeignKey(); } else { - final JoinColumn joinColumnAnn = property.getDirectAnnotationUsage( JoinColumn.class ); - if ( joinColumnAnn != null ) { - handleForeignKeyConstraint( noConstraintByDefault, key, joinColumnAnn.foreignKey() ); + final var joinColumn = property.getDirectAnnotationUsage( JoinColumn.class ); + if ( joinColumn != null ) { + handleForeignKeyConstraint( noConstraintByDefault, key, joinColumn.foreignKey() ); } } } @@ -2037,7 +2003,7 @@ private static void handleForeignKeyConstraint( boolean noConstraintByDefault, DependantValue key, ForeignKey foreignKey) { - final ConstraintMode constraintMode = foreignKey.value(); + final var constraintMode = foreignKey.value(); if ( constraintMode == NO_CONSTRAINT || constraintMode == PROVIDER_DEFAULT && noConstraintByDefault) { key.disableForeignKey(); @@ -2051,10 +2017,11 @@ private static void handleForeignKeyConstraint( private void overrideReferencedPropertyName(Collection collection, AnnotatedJoinColumns joinColumns) { if ( isUnownedCollection() && !joinColumns.getColumns().isEmpty() ) { - final String entityName = joinColumns.getManyToManyOwnerSideEntityName() != null - ? "inverse__" + joinColumns.getManyToManyOwnerSideEntityName() - : joinColumns.getPropertyHolder().getEntityName(); - final InFlightMetadataCollector collector = getMetadataCollector(); + final String entityName = + joinColumns.getManyToManyOwnerSideEntityName() != null + ? "inverse__" + joinColumns.getManyToManyOwnerSideEntityName() + : joinColumns.getPropertyHolder().getEntityName(); + final var collector = getMetadataCollector(); final String referencedProperty = collector.getPropertyReferencedAssociation( entityName, mappedBy ); if ( referencedProperty != null ) { collection.setReferencedPropertyName( referencedProperty ); @@ -2071,8 +2038,8 @@ private void bindManyToManySecondPass(Map persistentCla throw new AssertionFailure( "Null property" ); } - final TypeDetails elementType = getElementType(); - final PersistentClass targetEntity = persistentClasses.get( elementType.getName() ); //null if this is an @ElementCollection + final var elementTypeDetails = getElementType(); + final var targetEntity = persistentClasses.get( elementTypeDetails.getName() ); //null if this is an @ElementCollection final String hqlOrderBy = extractHqlOrderBy( jpaOrderBy ); final boolean isCollectionOfEntities = targetEntity != null; @@ -2081,10 +2048,10 @@ private void bindManyToManySecondPass(Map persistentCla logManyToManySecondPass( oneToMany, isCollectionOfEntities, isManyToAny ); //check for user error - detectManyToManyProblems( elementType, isCollectionOfEntities, isManyToAny ); + detectManyToManyProblems( elementTypeDetails, isCollectionOfEntities, isManyToAny ); if ( isUnownedCollection() ) { - handleUnownedManyToMany( elementType, targetEntity, isCollectionOfEntities ); + handleUnownedManyToMany( elementTypeDetails, targetEntity, isCollectionOfEntities ); } else { handleOwnedManyToMany( targetEntity, isCollectionOfEntities ); @@ -2097,14 +2064,14 @@ private void bindManyToManySecondPass(Map persistentCla bindCollectionSecondPass( targetEntity, joinColumns ); if ( isCollectionOfEntities ) { - final ManyToOne element = handleCollectionOfEntities( elementType, targetEntity, hqlOrderBy ); + final ManyToOne element = handleCollectionOfEntities( elementTypeDetails, targetEntity, hqlOrderBy ); bindManyToManyInverseForeignKey( targetEntity, inverseJoinColumns, element, oneToMany ); } else if ( isManyToAny ) { handleManyToAny(); } else { - handleElementCollection( elementType, hqlOrderBy ); + handleElementCollection( elementTypeDetails, hqlOrderBy ); } checkFilterConditions( collection ); @@ -2117,13 +2084,13 @@ private void handleElementCollection(TypeDetails elementType, String hqlOrderBy) // 'property' is the collection XProperty final boolean isPrimitive = isPrimitive( elementType.getName() ); - final ClassDetails elementClass = isPrimitive ? null : elementType.determineRawClass(); - final AnnotatedClassType classType = annotatedElementType( isEmbedded, isPrimitive, property, elementClass ); + final var elementClass = isPrimitive ? null : elementType.determineRawClass(); + final var classType = annotatedElementType( isEmbedded, isPrimitive, property, elementClass ); if ( !isPrimitive ) { propertyHolder.startingProperty( property ); } - final CollectionPropertyHolder holder = + final var holder = buildPropertyHolder( collection, getRole(), elementClass, property, propertyHolder, buildingContext ); final var compositeUserType = resolveCompositeUserType( property, elementClass, buildingContext ); @@ -2145,7 +2112,7 @@ private void handleCollectionElement( CollectionPropertyHolder holder) { final var elementBinder = new BasicValueBinder( COLLECTION_ELEMENT, buildingContext ); elementBinder.setReturnedClassName( elementType.getName() ); - final AnnotatedColumns actualColumns = createElementColumnsIfNecessary( + final var actualColumns = createElementColumnsIfNecessary( collection, elementColumns, Collection.DEFAULT_ELEMENT_COLUMN_NAME, @@ -2174,7 +2141,7 @@ private void handleCompositeCollectionElement( CollectionPropertyHolder holder, Class> compositeUserType) { //TODO be smart with isNullable - final AccessType accessType = accessType( property, collection.getOwner() ); + final var accessType = accessType( property, collection.getOwner() ); // We create a new entity binder here because it's needed for processing the embeddable // Since this is an element collection, there is no real entity binder though, // so we just create an "empty shell" for the purpose of avoiding null checks in the fillEmbeddable() method etc. @@ -2182,7 +2149,7 @@ private void handleCompositeCollectionElement( // Copy over the access type that we resolve for the element collection, // so that nested components use the same access type. This fixes HHH-15966 entityBinder.setPropertyAccessType( accessType ); - final Component component = fillEmbeddable( + final var embeddable = fillEmbeddable( holder, getSpecialMembers( elementType ), accessType, @@ -2197,7 +2164,7 @@ private void handleCompositeCollectionElement( buildingContext, inheritanceStatePerClass ); - collection.setElement( component ); + collection.setElement( embeddable ); if ( isNotBlank( hqlOrderBy ) ) { final String orderBy = adjustUserSuppliedValueCollectionOrderingFragment( hqlOrderBy ); if ( orderBy != null ) { @@ -2207,15 +2174,15 @@ private void handleCompositeCollectionElement( } static AccessType accessType(MemberDetails property, PersistentClass owner) { - final Access accessAnn = property.getDirectAnnotationUsage( Access.class ); - if ( accessAnn != null ) { + final var access = property.getDirectAnnotationUsage( Access.class ); + if ( access != null ) { // the attribute is locally annotated with `@Access`, use that - return accessAnn.value() == PROPERTY + return access.value() == PROPERTY ? AccessType.PROPERTY : AccessType.FIELD; } else { - final Property identifierProperty = owner.getIdentifierProperty(); + final var identifierProperty = owner.getIdentifierProperty(); if ( identifierProperty != null ) { // use the access for the owning entity's id attribute, if one return identifierProperty.getPropertyAccessorName().equals( BASIC.getExternalName() ) @@ -2223,7 +2190,7 @@ static AccessType accessType(MemberDetails property, PersistentClass owner) { : AccessType.FIELD; } else { - final Component identifierMapper = owner.getIdentifierMapper(); + final var identifierMapper = owner.getIdentifierMapper(); if ( identifierMapper != null && identifierMapper.getPropertySpan() > 0 ) { // use the access for the owning entity's "id mapper" final Property first = identifierMapper.getProperties().get( 0 ); @@ -2268,9 +2235,9 @@ static AnnotatedColumns createElementColumnsIfNecessary( Long defaultLength, MetadataBuildingContext context) { if ( elementColumns == null || elementColumns.getColumns().isEmpty() ) { - final AnnotatedColumns columns = new AnnotatedColumns(); + final var columns = new AnnotatedColumns(); columns.setBuildingContext( context ); - final AnnotatedColumn column = new AnnotatedColumn(); + final var column = new AnnotatedColumn(); column.setLogicalColumnName( defaultName ); if ( defaultLength != null ) { column.setLength( defaultLength ); @@ -2292,7 +2259,7 @@ private ManyToOne handleCollectionOfEntities( TypeDetails elementType, PersistentClass collectionEntity, String hqlOrderBy) { - final ManyToOne element = new ManyToOne( buildingContext, collection.getCollectionTable() ); + final var element = new ManyToOne( buildingContext, collection.getCollectionTable() ); collection.setElement( element ); element.setReferencedEntityName( elementType.getName() ); //element.setFetchMode( fetchMode ); @@ -2306,25 +2273,25 @@ private ManyToOne handleCollectionOfEntities( collection.setManyToManyOrdering( buildOrderByClauseFromHql( hqlOrderBy, collectionEntity ) ); } - final JoinTable joinTableAnn = property.getDirectAnnotationUsage( JoinTable.class ); + final var joinTableAnn = property.getDirectAnnotationUsage( JoinTable.class ); if ( joinTableAnn != null ) { - final ForeignKey inverseForeignKey = joinTableAnn.inverseForeignKey(); + final var inverseForeignKey = joinTableAnn.inverseForeignKey(); String foreignKeyName = inverseForeignKey.name(); String foreignKeyDefinition = inverseForeignKey.foreignKeyDefinition(); String foreignKeyOptions = inverseForeignKey.options(); - final JoinColumn[] inverseJoinColumns = joinTableAnn.inverseJoinColumns(); + final var inverseJoinColumns = joinTableAnn.inverseJoinColumns(); if ( !ArrayHelper.isEmpty( inverseJoinColumns ) ) { - final JoinColumn joinColumnAnn = inverseJoinColumns[0]; + final var joinColumnAnn = inverseJoinColumns[0]; if ( foreignKeyName.isBlank() ) { - final ForeignKey inverseJoinColumnForeignKey = joinColumnAnn.foreignKey(); + final var inverseJoinColumnForeignKey = joinColumnAnn.foreignKey(); foreignKeyName = inverseJoinColumnForeignKey.name(); foreignKeyDefinition = inverseJoinColumnForeignKey.foreignKeyDefinition(); foreignKeyOptions = inverseJoinColumnForeignKey.options(); } } - final ConstraintMode constraintMode = inverseForeignKey.value(); + final var constraintMode = inverseForeignKey.value(); if ( constraintMode == NO_CONSTRAINT || constraintMode == PROVIDER_DEFAULT && buildingContext.getBuildingOptions().isNoConstraintByDefault() ) { @@ -2342,7 +2309,7 @@ private ManyToOne handleCollectionOfEntities( private void handleManyToAny() { //@ManyToAny //Make sure that collTyp is never used during the @ManyToAny branch: it will be set to void.class - final PropertyData inferredData = new PropertyInferredData( + final var inferredData = new PropertyInferredData( null, declaringClass, property, @@ -2350,21 +2317,20 @@ private void handleManyToAny() { buildingContext ); - final MemberDetails prop = inferredData.getAttributeMember(); - final jakarta.persistence.Column discriminatorColumnAnn = prop.getDirectAnnotationUsage( jakarta.persistence.Column.class ); - final Formula discriminatorFormulaAnn = getOverridableAnnotation( prop, Formula.class, buildingContext ); + final var memberDetails = inferredData.getAttributeMember(); + final var discriminatorColumnAnn = memberDetails.getDirectAnnotationUsage( jakarta.persistence.Column.class ); + final var discriminatorFormulaAnn = getOverridableAnnotation( memberDetails, Formula.class, buildingContext ); //override the table inverseJoinColumns.setTable( collection.getCollectionTable() ); - final ManyToAny anyAnn = property.getDirectAnnotationUsage( ManyToAny.class ); - final Any any = buildAnyValue( + final var any = buildAnyValue( discriminatorColumnAnn, discriminatorFormulaAnn, inverseJoinColumns, inferredData, onDeleteAction, - anyAnn.fetch() == LAZY, + property.getDirectAnnotationUsage( ManyToAny.class ).fetch() == LAZY, Nullability.NO_CONSTRAINT, propertyHolder, new EntityBinder( buildingContext ), @@ -2396,10 +2362,10 @@ private PropertyData getSpecialMembers(TypeDetails elementClass) { } private void handleOwnedManyToMany(PersistentClass collectionEntity, boolean isCollectionOfEntities) { + final var collector = getMetadataCollector(); //TODO: only for implicit columns? //FIXME NamingStrategy - final InFlightMetadataCollector collector = getMetadataCollector(); - final PersistentClass owner = collection.getOwner(); + final var owner = collection.getOwner(); joinColumns.setMappedBy( owner.getEntityName(), collector.getLogicalTableName( owner.getTable() ), @@ -2422,7 +2388,7 @@ private void handleOwnedManyToMany(PersistentClass collectionEntity, boolean isC tableBinder.setJPA2ElementCollection( !isCollectionOfEntities && property.hasDirectAnnotationUsage( ElementCollection.class ) ); - final Table collectionTable = tableBinder.bind(); + final var collectionTable = tableBinder.bind(); collection.setCollectionTable( collectionTable ); handleCheckConstraints( collectionTable ); processSoftDeletes(); @@ -2431,7 +2397,7 @@ private void handleOwnedManyToMany(PersistentClass collectionEntity, boolean isC private void handleCheckConstraints(Table collectionTable) { property.forEachAnnotationUsage( Check.class, modelsContext(), usage -> addCheckToCollection( collectionTable, usage ) ); - property.forEachAnnotationUsage( jakarta.persistence.JoinTable.class, modelsContext(), (usage) -> { + property.forEachAnnotationUsage( jakarta.persistence.JoinTable.class, modelsContext(), usage -> { TableBinder.addTableCheck( collectionTable, usage.check() ); TableBinder.addTableComment( collectionTable, usage.comment() ); TableBinder.addTableOptions( collectionTable, usage.options() ); @@ -2448,32 +2414,22 @@ private static void addCheckToCollection(Table collectionTable, Check check) { private void processSoftDeletes() { assert collection.getCollectionTable() != null; - - final SoftDelete softDelete = extractSoftDelete( property, buildingContext ); - if ( softDelete == null ) { - return; + final var softDelete = extractSoftDelete( property, buildingContext ); + if ( softDelete != null ) { + SoftDeleteHelper.bindSoftDeleteIndicator( + softDelete, + collection, + collection.getCollectionTable(), + buildingContext + ); } - - SoftDeleteHelper.bindSoftDeleteIndicator( - softDelete, - collection, - collection.getCollectionTable(), - buildingContext - ); } private static SoftDelete extractSoftDelete(MemberDetails property, MetadataBuildingContext context) { - final SoftDelete fromProperty = property.getDirectAnnotationUsage( SoftDelete.class ); - if ( fromProperty != null ) { - return fromProperty; - } - else { - return extractFromPackage( - SoftDelete.class, - property.getDeclaringType(), - context - ); - } + final var fromProperty = property.getDirectAnnotationUsage( SoftDelete.class ); + return fromProperty == null + ? extractFromPackage( SoftDelete.class, property.getDeclaringType(), context ) + : fromProperty; } private void handleUnownedManyToMany( @@ -2496,8 +2452,8 @@ private void handleUnownedManyToMany( + "is 'mappedBy' a property named '" + mappedBy + "' which does not exist in the target entity '" + elementType.getName() + "'" ); } - final Value otherSidePropertyValue = otherSideProperty.getValue(); - final Table table = + final var otherSidePropertyValue = otherSideProperty.getValue(); + final var table = otherSidePropertyValue instanceof Collection collectionProperty // this is a collection on the other side ? collectionProperty.getCollectionTable() @@ -2531,7 +2487,7 @@ else if (isManyToAny) { } } else { - final JoinTable joinTableAnn = propertyHolder.getJoinTable( property ); + final var joinTableAnn = propertyHolder.getJoinTable( property ); if ( joinTableAnn != null && !ArrayHelper.isEmpty( joinTableAnn.inverseJoinColumns() ) ) { throw new AnnotationException( "Association '" + safeCollectionRole() + " has a '@JoinTable' with 'inverseJoinColumns' and" @@ -2552,20 +2508,20 @@ private static Class resolveCustomInstantiator MemberDetails property, TypeDetails propertyClass, MetadataBuildingContext context) { - final org.hibernate.annotations.EmbeddableInstantiator propertyAnnotation + final var propertyAnnotation = property.getDirectAnnotationUsage( org.hibernate.annotations.EmbeddableInstantiator.class ); if ( propertyAnnotation != null ) { return propertyAnnotation.value(); } - final ClassDetails rawPropertyClassDetails = propertyClass.determineRawClass(); - final org.hibernate.annotations.EmbeddableInstantiator classAnnotation + final var rawPropertyClassDetails = propertyClass.determineRawClass(); + final var classAnnotation = rawPropertyClassDetails.getDirectAnnotationUsage( org.hibernate.annotations.EmbeddableInstantiator.class ); if ( classAnnotation != null ) { return classAnnotation.value(); } - final Class embeddableClass = rawPropertyClassDetails.toJavaClass(); + final var embeddableClass = rawPropertyClassDetails.toJavaClass(); if ( embeddableClass != null ) { return context.getMetadataCollector().findRegisteredEmbeddableInstantiator( embeddableClass ); } @@ -2577,19 +2533,19 @@ private static Class> resolveCompositeUserType( MemberDetails property, ClassDetails returnedClass, MetadataBuildingContext context) { - final CompositeType compositeType = property.getDirectAnnotationUsage( CompositeType.class ); + final var compositeType = property.getDirectAnnotationUsage( CompositeType.class ); if ( compositeType != null ) { return compositeType.value(); } - - if ( returnedClass != null ) { - final Class embeddableClass = returnedClass.toJavaClass(); + else if ( returnedClass != null ) { + final var embeddableClass = returnedClass.toJavaClass(); return embeddableClass == null ? null : context.getMetadataCollector().findRegisteredCompositeUserType( embeddableClass ); } - - return null; + else { + return null; + } } private static String extractHqlOrderBy(OrderBy jpaOrderBy) { @@ -2659,7 +2615,7 @@ private void bindCollectionSecondPass(PersistentClass targetEntity, AnnotatedJoi joinColumns.setElementCollection( true ); } - final DependantValue key = buildCollectionKey( joinColumns, onDeleteAction ); + final var key = buildCollectionKey( joinColumns, onDeleteAction ); TableBinder.bindForeignKey( collection.getOwner(), targetEntity, @@ -2733,15 +2689,14 @@ private void bindUnownedManyToManyInverseForeignKey( AnnotatedJoinColumns joinColumns, SimpleValue value) { final Property property = targetEntity.getRecursiveProperty( mappedBy ); - final List mappedByColumns = mappedByColumns( targetEntity, property ); - final AnnotatedJoinColumn firstColumn = joinColumns.getJoinColumns().get(0); - for ( Selectable selectable: mappedByColumns ) { + final var firstColumn = joinColumns.getJoinColumns().get(0); + for ( var selectable: mappedByColumns( targetEntity, property ) ) { firstColumn.linkValueUsingAColumnCopy( (Column) selectable, value); } - final InFlightMetadataCollector metadataCollector = getMetadataCollector(); + final var metadataCollector = getMetadataCollector(); final String referencedPropertyName = metadataCollector.getPropertyReferencedAssociation( targetEntity.getEntityName(), mappedBy ); - final ManyToOne manyToOne = (ManyToOne) value; + final var manyToOne = (ManyToOne) value; if ( referencedPropertyName != null ) { //TODO always a many to one? manyToOne.setReferencedPropertyName( referencedPropertyName ); @@ -2758,7 +2713,7 @@ private static List mappedByColumns(PersistentClass referencedEntity else { //find the appropriate reference key, can be in a join KeyValue key = null; - for ( Join join : referencedEntity.getJoins() ) { + for ( var join : referencedEntity.getJoins() ) { if ( join.containsProperty(property) ) { key = join.getKey(); break; diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionPropertyHolder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionPropertyHolder.java index e61906f2373c..b117e37d53ce 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionPropertyHolder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionPropertyHolder.java @@ -104,7 +104,7 @@ private void applyLocalConvert( // of either is disabled for whatever reason. For example, if the Map is annotated with @Enumerated the // elements cannot be converted so any @Convert likely meant the key, so we apply it to the key - final AttributeConversionInfo info = new AttributeConversionInfo( convertAnnotation, collectionProperty ); + final var info = new AttributeConversionInfo( convertAnnotation, collectionProperty ); final String attributeName = info.getAttributeName(); if ( collection.isMap() ) { logSpecNoncompliance( attributeName, collection.getRole() ); @@ -409,7 +409,7 @@ public ConverterDescriptor resolveElementAttributeConverterDescriptor( public ConverterDescriptor mapKeyAttributeConverterDescriptor( MemberDetails memberDetails, TypeDetails keyTypeDetails) { - final AttributeConversionInfo info = locateAttributeConversionInfo( "key" ); + final var info = locateAttributeConversionInfo( "key" ); if ( info != null ) { if ( info.isConversionDisabled() ) { return null; diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionSecondPass.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionSecondPass.java index 9e4362928dd7..cfd64f88bbe4 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/CollectionSecondPass.java @@ -13,7 +13,6 @@ import org.hibernate.mapping.IndexedCollection; import org.hibernate.mapping.OneToMany; import org.hibernate.mapping.PersistentClass; -import org.hibernate.mapping.Selectable; import org.hibernate.mapping.Value; import static org.hibernate.internal.CoreLogging.messageLogger; @@ -62,8 +61,8 @@ public void doSecondPass(Map persistentClasses) abstract public void secondPass(Map persistentClasses) throws MappingException; private static String columns(Value val) { - final StringBuilder columns = new StringBuilder(); - for ( Selectable selectable : val.getSelectables() ) { + final var columns = new StringBuilder(); + for ( var selectable : val.getSelectables() ) { if ( !columns.isEmpty() ) { columns.append( ", " ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ColumnsBuilder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ColumnsBuilder.java index dca6d21e6ac6..9a41d20566fd 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ColumnsBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ColumnsBuilder.java @@ -5,6 +5,7 @@ package org.hibernate.boot.model.internal; import org.hibernate.AnnotationException; +import org.hibernate.annotations.Any; import org.hibernate.annotations.Columns; import org.hibernate.annotations.Formula; import org.hibernate.annotations.FractionalSeconds; @@ -16,18 +17,15 @@ import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.PropertyData; import org.hibernate.models.spi.MemberDetails; -import org.hibernate.models.spi.ModelsContext; import jakarta.persistence.Column; import jakarta.persistence.ElementCollection; import jakarta.persistence.JoinColumn; -import jakarta.persistence.JoinTable; import jakarta.persistence.ManyToMany; import jakarta.persistence.ManyToOne; import jakarta.persistence.MapsId; import jakarta.persistence.OneToMany; import jakarta.persistence.OneToOne; -import jakarta.persistence.PrimaryKeyJoinColumn; import static org.hibernate.boot.model.internal.AnnotatedColumn.buildColumnFromAnnotation; import static org.hibernate.boot.model.internal.AnnotatedColumn.buildColumnFromNoAnnotation; @@ -83,13 +81,9 @@ public ColumnsBuilder extractMetadata() { columns = null; joinColumns = buildExplicitJoinColumns( property, inferredData ); - final Column columnAnn = property.getDirectAnnotationUsage( Column.class ); - final Columns columnsAnn = property.getDirectAnnotationUsage( Columns.class ); - final Formula formulaAnn = property.getDirectAnnotationUsage( Formula.class ); - - if ( columnAnn != null ) { + if ( property.hasDirectAnnotationUsage( Column.class ) ) { columns = buildColumnFromAnnotation( - columnAnn, + property.getDirectAnnotationUsage( Column.class ), property.getDirectAnnotationUsage( FractionalSeconds.class ), nullability, propertyHolder, @@ -98,7 +92,7 @@ public ColumnsBuilder extractMetadata() { buildingContext ); } - else if ( formulaAnn != null ) { + else if ( property.hasDirectAnnotationUsage( Formula.class) ) { columns = buildFormulaFromAnnotation( getOverridableAnnotation( property, Formula.class, buildingContext ), nullability, @@ -108,9 +102,9 @@ else if ( formulaAnn != null ) { buildingContext ); } - else if ( columnsAnn != null ) { + else if ( property.hasDirectAnnotationUsage( Columns.class ) ) { columns = buildColumnsFromAnnotations( - columnsAnn.columns(), + property.getDirectAnnotationUsage( Columns.class ).columns(), null, nullability, propertyHolder, @@ -129,7 +123,7 @@ else if ( columnsAnn != null ) { else if ( joinColumns == null && ( property.hasDirectAnnotationUsage( OneToMany.class ) || property.hasDirectAnnotationUsage( ElementCollection.class ) ) ) { - final OneToMany oneToMany = property.getDirectAnnotationUsage( OneToMany.class ); + final var oneToMany = property.getDirectAnnotationUsage( OneToMany.class ); joinColumns = AnnotatedJoinColumns.buildJoinColumns( null, oneToMany == null ? null : nullIfEmpty( oneToMany.mappedBy() ), @@ -140,7 +134,7 @@ else if ( joinColumns == null ); } else if ( joinColumns == null - && property.hasDirectAnnotationUsage( org.hibernate.annotations.Any.class ) ) { + && property.hasDirectAnnotationUsage( Any.class ) ) { throw new AnnotationException( "Property '" + getPath( propertyHolder, inferredData ) + "' is annotated '@Any' and must declare at least one '@JoinColumn'" ); } @@ -168,10 +162,10 @@ else if ( joinColumns == null private AnnotatedJoinColumns buildDefaultJoinColumnsForToOne( MemberDetails property, PropertyData inferredData) { - final JoinTable joinTableAnn = propertyHolder.getJoinTable( property ); - if ( joinTableAnn != null ) { + final var joinTable = propertyHolder.getJoinTable( property ); + if ( joinTable != null ) { return AnnotatedJoinColumns.buildJoinColumns( - joinTableAnn.inverseJoinColumns(), + joinTable.inverseJoinColumns(), null, entityBinder.getSecondaryTables(), propertyHolder, @@ -180,10 +174,10 @@ private AnnotatedJoinColumns buildDefaultJoinColumnsForToOne( ); } else { - final OneToOne oneToOneAnn = property.getDirectAnnotationUsage( OneToOne.class ); + final var oneToOne = property.getDirectAnnotationUsage( OneToOne.class ); return AnnotatedJoinColumns.buildJoinColumns( null, - oneToOneAnn == null ? null : nullIfEmpty( oneToOneAnn.mappedBy() ), + oneToOne == null ? null : nullIfEmpty( oneToOne.mappedBy() ), entityBinder.getSecondaryTables(), propertyHolder, inferredData, @@ -194,10 +188,10 @@ private AnnotatedJoinColumns buildDefaultJoinColumnsForToOne( private AnnotatedJoinColumns buildExplicitJoinColumns(MemberDetails property, PropertyData inferredData) { // process @JoinColumns before @Columns to handle collection of entities properly - final JoinColumn[] joinColumnAnnotations = getJoinColumnAnnotations( property ); - if ( joinColumnAnnotations != null ) { + final var joinColumns = getJoinColumnAnnotations( property ); + if ( joinColumns != null ) { return AnnotatedJoinColumns.buildJoinColumns( - joinColumnAnnotations, + joinColumns, null, entityBinder.getSecondaryTables(), propertyHolder, @@ -206,10 +200,10 @@ private AnnotatedJoinColumns buildExplicitJoinColumns(MemberDetails property, Pr ); } - final JoinColumnOrFormula[] joinColumnOrFormulaAnnotations = joinColumnOrFormulaAnnotations( property ); - if ( joinColumnOrFormulaAnnotations != null ) { + final var joinColumnOrFormulas = joinColumnOrFormulaAnnotations( property ); + if ( joinColumnOrFormulas != null ) { return AnnotatedJoinColumns.buildJoinColumnsOrFormulas( - joinColumnOrFormulaAnnotations, + joinColumnOrFormulas, null, entityBinder.getSecondaryTables(), propertyHolder, @@ -218,10 +212,9 @@ private AnnotatedJoinColumns buildExplicitJoinColumns(MemberDetails property, Pr ); } - if ( property.hasDirectAnnotationUsage( JoinFormula.class) ) { - final JoinFormula joinFormula = getOverridableAnnotation( property, JoinFormula.class, buildingContext ); + if ( property.hasDirectAnnotationUsage( JoinFormula.class ) ) { return AnnotatedJoinColumns.buildJoinColumnsWithFormula( - joinFormula, + getOverridableAnnotation( property, JoinFormula.class, buildingContext ), entityBinder.getSecondaryTables(), propertyHolder, inferredData, @@ -233,21 +226,16 @@ private AnnotatedJoinColumns buildExplicitJoinColumns(MemberDetails property, Pr } private JoinColumnOrFormula[] joinColumnOrFormulaAnnotations(MemberDetails property) { - final ModelsContext modelsContext = buildingContext.getBootstrapContext().getModelsContext(); - final JoinColumnOrFormula[] annotations = property.getRepeatedAnnotationUsages( + final var annotations = property.getRepeatedAnnotationUsages( HibernateAnnotations.JOIN_COLUMN_OR_FORMULA, - modelsContext + buildingContext.getBootstrapContext().getModelsContext() ); return isNotEmpty( annotations ) ? annotations : null; } private JoinColumn[] getJoinColumnAnnotations(MemberDetails property) { - final ModelsContext modelsContext = buildingContext.getBootstrapContext().getModelsContext(); - - final JoinColumn[] joinColumns = property.getRepeatedAnnotationUsages( - JpaAnnotations.JOIN_COLUMN, - modelsContext - ); + final var modelsContext = buildingContext.getBootstrapContext().getModelsContext(); + final var joinColumns = property.getRepeatedAnnotationUsages( JpaAnnotations.JOIN_COLUMN, modelsContext ); if ( isNotEmpty( joinColumns ) ) { return joinColumns; } @@ -256,15 +244,12 @@ else if ( property.hasDirectAnnotationUsage( MapsId.class ) ) { // masquerade as a regular JoinColumn (when a @OneToOne maps to // the primary key of the child table, it's more elegant and more // spec-compliant to map the association with @PrimaryKeyJoinColumn) - final PrimaryKeyJoinColumn[] primaryKeyJoinColumns = property.getRepeatedAnnotationUsages( - JpaAnnotations.PRIMARY_KEY_JOIN_COLUMN, - modelsContext - ); + final var primaryKeyJoinColumns = + property.getRepeatedAnnotationUsages( JpaAnnotations.PRIMARY_KEY_JOIN_COLUMN, modelsContext ); if ( isNotEmpty( primaryKeyJoinColumns ) ) { - final JoinColumn[] adapters = new JoinColumn[primaryKeyJoinColumns.length]; + final var adapters = new JoinColumn[primaryKeyJoinColumns.length]; for ( int i = 0; i < primaryKeyJoinColumns.length; i++ ) { - final PrimaryKeyJoinColumn primaryKeyJoinColumn = primaryKeyJoinColumns[i]; - adapters[i] = JoinColumnJpaAnnotation.toJoinColumn( primaryKeyJoinColumn, modelsContext ); + adapters[i] = JoinColumnJpaAnnotation.toJoinColumn( primaryKeyJoinColumns[i], modelsContext ); } return adapters; } @@ -282,10 +267,10 @@ else if ( property.hasDirectAnnotationUsage( MapsId.class ) ) { */ AnnotatedColumns overrideColumnFromMapperOrMapsIdProperty(PropertyData override) { if ( override != null ) { - final MemberDetails attributeMember = override.getAttributeMember(); - final AnnotatedJoinColumns joinColumns = buildExplicitJoinColumns( attributeMember, override ); + final var memberDetails = override.getAttributeMember(); + final var joinColumns = buildExplicitJoinColumns( memberDetails, override ); return joinColumns == null - ? buildDefaultJoinColumnsForToOne( attributeMember, override ) + ? buildDefaultJoinColumnsForToOne( memberDetails, override ) : joinColumns; } else { diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ComponentPropertyHolder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ComponentPropertyHolder.java index 762a8f9a69d3..a9f7a33168e7 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ComponentPropertyHolder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ComponentPropertyHolder.java @@ -78,22 +78,23 @@ public ComponentPropertyHolder( MetadataBuildingContext context, Map inheritanceStatePerClass) { super( path, parent, inferredData.getPropertyType().determineRawClass(), context ); - final MemberDetails embeddedMemberDetails = inferredData.getAttributeMember(); + final var embeddedMemberDetails = inferredData.getAttributeMember(); setCurrentProperty( embeddedMemberDetails ); this.component = component; - this.isOrWithinEmbeddedId = parent.isOrWithinEmbeddedId() + this.inheritanceStatePerClass = inheritanceStatePerClass; + + isOrWithinEmbeddedId = parent.isOrWithinEmbeddedId() || embeddedMemberDetails != null && hasIdAnnotation( embeddedMemberDetails ); - this.isWithinElementCollection = parent.isWithinElementCollection() + isWithinElementCollection = parent.isWithinElementCollection() || parent instanceof CollectionPropertyHolder; - this.inheritanceStatePerClass = inheritanceStatePerClass; if ( embeddedMemberDetails != null ) { - this.embeddedAttributeName = embeddedMemberDetails.getName(); - this.attributeConversionInfoMap = processAttributeConversions( embeddedMemberDetails ); + embeddedAttributeName = embeddedMemberDetails.getName(); + attributeConversionInfoMap = processAttributeConversions( embeddedMemberDetails ); } else { - this.embeddedAttributeName = ""; - this.attributeConversionInfoMap = processAttributeConversions( inferredData.getClassOrElementType() ); + embeddedAttributeName = ""; + attributeConversionInfoMap = processAttributeConversions( inferredData.getClassOrElementType() ); } } @@ -122,7 +123,7 @@ public Component getComponent() { private Map processAttributeConversions(MemberDetails embeddedMemberDetails) { final Map infoMap = new HashMap<>(); - final TypeDetails embeddableTypeDetails = embeddedMemberDetails.getType(); + final var embeddableTypeDetails = embeddedMemberDetails.getType(); // as a baseline, we want to apply conversions from the Embeddable and then overlay conversions // from the Embedded @@ -132,7 +133,7 @@ private Map processAttributeConversions(MemberDe // then we can overlay any conversions from the Embedded attribute embeddedMemberDetails.forEachAnnotationUsage( Convert.class, getSourceModelContext(), (usage) -> { - final AttributeConversionInfo info = new AttributeConversionInfo( usage, embeddedMemberDetails ); + final var info = new AttributeConversionInfo( usage, embeddedMemberDetails ); if ( isEmpty( info.getAttributeName() ) ) { throw new IllegalStateException( "Convert placed on Embedded attribute must define (sub)attributeName" ); } @@ -143,9 +144,9 @@ private Map processAttributeConversions(MemberDe } private void processAttributeConversions(TypeDetails embeddableTypeDetails, Map infoMap) { - final ClassDetails embeddableClassDetails = embeddableTypeDetails.determineRawClass(); + final var embeddableClassDetails = embeddableTypeDetails.determineRawClass(); embeddableClassDetails.forEachAnnotationUsage( Convert.class, getSourceModelContext(), (usage) -> { - final AttributeConversionInfo info = new AttributeConversionInfo( usage, embeddableClassDetails ); + final var info = new AttributeConversionInfo( usage, embeddableClassDetails ); if ( isEmpty( info.getAttributeName() ) ) { throw new IllegalStateException( "@Convert placed on @Embeddable must define attributeName" ); } @@ -171,26 +172,24 @@ protected String normalizeCompositePathForLogging(String attributeName) { @Override public void startingProperty(MemberDetails propertyMemberDetails) { - if ( propertyMemberDetails == null ) { - return; - } + if ( propertyMemberDetails != null ) { + // again: the property coming in here *should* be the property on the embeddable (Address#city in the example), + // so we just ignore it if there is already an existing conversion info for that path since they would have + // precedence - // again : the property coming in here *should* be the property on the embeddable (Address#city in the example), - // so we just ignore it if there is already an existing conversion info for that path since they would have - // precedence + // technically we should only do this for properties of "basic type" - // technically we should only do this for properties of "basic type" + final String attributeName = propertyMemberDetails.resolveAttributeName(); + final String path = embeddedAttributeName + '.' + attributeName; + if ( attributeConversionInfoMap.containsKey( path ) ) { + return; + } - final String attributeName = propertyMemberDetails.resolveAttributeName(); - final String path = embeddedAttributeName + '.' + attributeName; - if ( attributeConversionInfoMap.containsKey( path ) ) { - return; + propertyMemberDetails.forEachAnnotationUsage( Convert.class, getSourceModelContext(), (usage) -> { + final AttributeConversionInfo info = new AttributeConversionInfo( usage, propertyMemberDetails ); + attributeConversionInfoMap.put( attributeName, info ); + } ); } - - propertyMemberDetails.forEachAnnotationUsage( Convert.class, getSourceModelContext(), (usage) -> { - final AttributeConversionInfo info = new AttributeConversionInfo( usage, propertyMemberDetails ); - attributeConversionInfoMap.put( attributeName, info ); - } ); } @Override @@ -202,12 +201,12 @@ protected AttributeConversionInfo locateAttributeConversionInfo(MemberDetails at @Override protected AttributeConversionInfo locateAttributeConversionInfo(String path) { final String embeddedPath = qualifyConditionally( embeddedAttributeName, path ); - final AttributeConversionInfo fromParent = parent.locateAttributeConversionInfo( embeddedPath ); + final var fromParent = parent.locateAttributeConversionInfo( embeddedPath ); if ( fromParent != null ) { return fromParent; } - final AttributeConversionInfo fromEmbedded = attributeConversionInfoMap.get( embeddedPath ); + final var fromEmbedded = attributeConversionInfoMap.get( embeddedPath ); if ( fromEmbedded != null ) { return fromEmbedded; } @@ -221,7 +220,11 @@ public String getEntityName() { } @Override - public void addProperty(Property property, MemberDetails attributeMemberDetails, @Nullable AnnotatedColumns columns, ClassDetails declaringClass) { + public void addProperty( + Property property, + MemberDetails attributeMemberDetails, + @Nullable AnnotatedColumns columns, + ClassDetails declaringClass) { //AnnotatedColumns.checkPropertyConsistency( ); //already called earlier // Check table matches between the component and the columns // if not, change the component table if no properties are set @@ -270,7 +273,7 @@ public String getEntityOwnerClassName() { } public AggregateColumn getAggregateColumn() { - final AggregateColumn aggregateColumn = component.getAggregateColumn(); + final var aggregateColumn = component.getAggregateColumn(); return aggregateColumn != null ? aggregateColumn : component.getParentAggregateColumn(); } @@ -283,7 +286,7 @@ public Table getTable() { public void addProperty(Property prop, MemberDetails attributeMemberDetails, ClassDetails declaringClass) { handleGenericComponentProperty( prop, attributeMemberDetails, getContext() ); if ( declaringClass != null ) { - final InheritanceState inheritanceState = inheritanceStatePerClass.get( declaringClass ); + final var inheritanceState = inheritanceStatePerClass.get( declaringClass ); if ( inheritanceState != null && inheritanceState.isEmbeddableSuperclass() ) { addPropertyToMappedSuperclass( prop, attributeMemberDetails, declaringClass, getContext() ); } @@ -346,9 +349,9 @@ public Column[] getOverriddenColumn(String propertyName) { } private String extractUserPropertyName(String redundantString, String propertyName) { - String className = component.getOwner().getClassName(); + final String className = component.getOwner().getClassName(); if ( className != null && propertyName.startsWith( className ) ) { - boolean specialCase = propertyName.length() > className.length() + 2 + redundantString.length() + final boolean specialCase = propertyName.length() > className.length() + 2 + redundantString.length() && propertyName.substring( className.length() + 1, className.length() + 1 + redundantString.length() ).equals( redundantString ); if ( specialCase ) { //remove id we might be in a @IdClass case diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/DialectOverridesAnnotationHelper.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/DialectOverridesAnnotationHelper.java index 94efcdae259e..7bd3f615fc15 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/DialectOverridesAnnotationHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/DialectOverridesAnnotationHelper.java @@ -15,7 +15,6 @@ import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.dialect.Dialect; import org.hibernate.models.spi.AnnotationTarget; -import org.hibernate.models.spi.ModelsContext; import static org.hibernate.internal.util.collections.CollectionHelper.isNotEmpty; @@ -29,43 +28,37 @@ public class DialectOverridesAnnotationHelper { private static Map, Class> buildOverrideMap() { // not accessed concurrently final Map, Class> results = new HashMap<>(); - - final Class[] dialectOverrideMembers = DialectOverride.class.getNestMembers(); - for ( Class dialectOverrideMember : dialectOverrideMembers ) { - if ( !dialectOverrideMember.isAnnotation() ) { - continue; - } - - final DialectOverride.OverridesAnnotation overrideAnnotation = dialectOverrideMember.getAnnotation( DialectOverride.OverridesAnnotation.class ); - if ( overrideAnnotation == null ) { - continue; + for ( Class dialectOverrideMember : DialectOverride.class.getNestMembers() ) { + if ( dialectOverrideMember.isAnnotation() ) { + final var overrideAnnotation = + dialectOverrideMember.getAnnotation( DialectOverride.OverridesAnnotation.class ); + if ( overrideAnnotation != null ) { + // The "real" annotation. e.g. `org.hibernate.annotations.Formula` + final var baseAnnotation = overrideAnnotation.value(); + // the "override" annotation. e.g. `org.hibernate.annotations.DialectOverride.Formula` + //noinspection unchecked + final var dialectOverrideAnnotation = (Class) dialectOverrideMember; + results.put( baseAnnotation, dialectOverrideAnnotation ); + } } - - // The "real" annotation. e.g. `org.hibernate.annotations.Formula` - final Class baseAnnotation = overrideAnnotation.value(); - - // the "override" annotation. e.g. `org.hibernate.annotations.DialectOverride.Formula` - //noinspection unchecked - final Class dialectOverrideAnnotation = (Class) dialectOverrideMember; - - results.put( baseAnnotation, dialectOverrideAnnotation ); } - return results; } public static Class getOverrideAnnotation(Class annotationType) { final Class overrideAnnotation = findOverrideAnnotation( annotationType ); - if ( overrideAnnotation != null ) { + if ( overrideAnnotation == null ) { + throw new HibernateException( + String.format( + Locale.ROOT, + "Specified Annotation type (%s) does not have an override form", + annotationType.getName() + ) + ); + } + else { return overrideAnnotation; } - throw new HibernateException( - String.format( - Locale.ROOT, - "Specified Annotation type (%s) does not have an override form", - annotationType.getName() - ) - ); } public static Class findOverrideAnnotation(Class annotationType) { @@ -77,18 +70,16 @@ public static T getOverridableAnnotation( AnnotationTarget element, Class annotationType, MetadataBuildingContext context) { - final ModelsContext modelsContext = context.getBootstrapContext().getModelsContext(); - final Class overrideAnnotation = OVERRIDE_MAP.get( annotationType ); - + final var modelsContext = context.getBootstrapContext().getModelsContext(); + final var overrideAnnotation = OVERRIDE_MAP.get( annotationType ); if ( overrideAnnotation != null ) { // the requested annotation does have a DialectOverride variant - look for matching one of those... final Dialect dialect = context.getMetadataCollector().getDatabase().getDialect(); - final Annotation[] overrides = element.getRepeatedAnnotationUsages( overrideAnnotation, modelsContext ); if ( isNotEmpty( overrides ) ) { - for ( int i = 0; i < overrides.length; i++ ) { + for ( Annotation annotation : overrides ) { //noinspection unchecked - final DialectOverrider override = (DialectOverrider) overrides[i]; + final var override = (DialectOverrider) annotation; if ( override.matches( dialect ) ) { return override.override(); } @@ -96,11 +87,7 @@ public static T getOverridableAnnotation( } } - // no override was found. return the base annotation (if one) + // No override was found. Return the base annotation (if one) return element.getAnnotationUsage( annotationType, modelsContext ); } - - public static boolean overrideMatchesDialect(DialectOverrider override, Dialect dialect) { - return override.matches( dialect ); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/DiscriminatorColumnSecondPass.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/DiscriminatorColumnSecondPass.java index ee1042161ee2..bddd01e70768 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/DiscriminatorColumnSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/DiscriminatorColumnSecondPass.java @@ -14,9 +14,9 @@ import org.hibernate.mapping.CheckConstraint; import org.hibernate.mapping.Column; import org.hibernate.mapping.PersistentClass; -import org.hibernate.mapping.Selectable; import org.hibernate.mapping.Subclass; -import org.hibernate.persister.entity.DiscriminatorHelper; + +import static org.hibernate.persister.entity.DiscriminatorHelper.getDiscriminatorValue; public class DiscriminatorColumnSecondPass implements SecondPass { @@ -30,9 +30,9 @@ public DiscriminatorColumnSecondPass(String rootEntityName, Dialect dialect) { @Override public void doSecondPass(Map persistentClasses) throws MappingException { - final PersistentClass rootClass = persistentClasses.get( rootEntityName ); + final var rootClass = persistentClasses.get( rootEntityName ); if ( hasNullDiscriminatorValue( rootClass ) ) { - for ( Selectable selectable: rootClass.getDiscriminator().getSelectables() ) { + for ( var selectable: rootClass.getDiscriminator().getSelectables() ) { if ( selectable instanceof Column column ) { column.setNullable( true ); } @@ -41,7 +41,7 @@ public void doSecondPass(Map persistentClasses) throws if ( !hasNotNullDiscriminatorValue( rootClass ) // a "not null" discriminator is a catch-all && !rootClass.getDiscriminator().hasFormula() // can't add check constraints to formulas && !rootClass.isForceDiscriminator() ) { // the usecase for "forced" discriminators is that there are some rogue values - final Column column = rootClass.getDiscriminator().getColumns().get( 0 ); + final var column = rootClass.getDiscriminator().getColumns().get( 0 ); column.addCheckConstraint( new CheckConstraint( checkConstraint( rootClass, column ) ) ); } } @@ -50,7 +50,7 @@ private boolean hasNullDiscriminatorValue(PersistentClass rootClass) { if ( rootClass.isDiscriminatorValueNull() ) { return true; } - for ( Subclass subclass : rootClass.getSubclasses() ) { + for ( var subclass : rootClass.getSubclasses() ) { if ( subclass.isDiscriminatorValueNull() ) { return true; } @@ -62,7 +62,7 @@ private boolean hasNotNullDiscriminatorValue(PersistentClass rootClass) { if ( rootClass.isDiscriminatorValueNotNull() ) { return true; } - for ( Subclass subclass : rootClass.getSubclasses() ) { + for ( var subclass : rootClass.getSubclasses() ) { if ( subclass.isDiscriminatorValueNotNull() ) { return true; } @@ -83,13 +83,13 @@ private static List discriminatorValues(PersistentClass rootClass) { if ( !rootClass.isAbstract() && !rootClass.isDiscriminatorValueNull() && !rootClass.isDiscriminatorValueNotNull() ) { - values.add( DiscriminatorHelper.getDiscriminatorValue( rootClass ).toString() ); + values.add( getDiscriminatorValue( rootClass ).toString() ); } for ( Subclass subclass : rootClass.getSubclasses() ) { if ( !subclass.isAbstract() && !subclass.isDiscriminatorValueNull() && !subclass.isDiscriminatorValueNotNull() ) { - values.add( DiscriminatorHelper.getDiscriminatorValue( subclass ).toString() ); + values.add( getDiscriminatorValue( subclass ).toString() ); } } return values; diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EmbeddableBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EmbeddableBinder.java index d0b195452b2a..ed990864526f 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EmbeddableBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EmbeddableBinder.java @@ -26,7 +26,6 @@ import org.hibernate.annotations.Instantiator; import org.hibernate.annotations.TypeBinderType; import org.hibernate.binder.TypeBinder; -import org.hibernate.boot.model.relational.Database; import org.hibernate.boot.spi.AccessType; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.PropertyData; @@ -38,26 +37,20 @@ import org.hibernate.mapping.Component; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; -import org.hibernate.mapping.Selectable; import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.SingleTableSubclass; import org.hibernate.mapping.Value; import org.hibernate.metamodel.mapping.EntityDiscriminatorMapping; import org.hibernate.metamodel.spi.EmbeddableInstantiator; import org.hibernate.models.spi.ClassDetails; -import org.hibernate.models.spi.FieldDetails; import org.hibernate.models.spi.MemberDetails; -import org.hibernate.models.spi.MethodDetails; -import org.hibernate.models.spi.ModelsContext; import org.hibernate.models.spi.TypeDetails; import org.hibernate.property.access.internal.PropertyAccessStrategyCompositeUserTypeImpl; import org.hibernate.property.access.internal.PropertyAccessStrategyGetterImpl; -import org.hibernate.property.access.spi.PropertyAccessStrategy; import org.hibernate.resource.beans.internal.FallbackBeanInstanceProducer; import org.hibernate.type.BasicType; import org.hibernate.usertype.CompositeUserType; -import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Type; import java.util.ArrayList; @@ -81,7 +74,6 @@ import static org.hibernate.internal.util.StringHelper.isBlank; import static org.hibernate.internal.util.StringHelper.qualify; import static org.hibernate.internal.util.StringHelper.unqualify; -import static org.hibernate.internal.util.collections.CollectionHelper.isEmpty; import static org.hibernate.internal.util.collections.CollectionHelper.mapOfSize; /** @@ -200,7 +192,7 @@ private static Component bindOverriddenEmbeddable( PropertyData mapsIdProperty) { // careful: not always a @MapsId property, sometimes it's from an @IdClass final String propertyName = mapsIdProperty.getPropertyName(); - final AnnotatedJoinColumns actualColumns = new AnnotatedJoinColumns(); + final var actualColumns = new AnnotatedJoinColumns(); actualColumns.setBuildingContext( context ); actualColumns.setPropertyHolder( propertyHolder ); actualColumns.setPropertyName( getRelativePath( propertyHolder, propertyName ) ); @@ -237,7 +229,7 @@ static boolean isEmbedded(MemberDetails property, TypeDetails returnedClass) { return true; } else { - final ClassDetails returnClassDetails = returnedClass.determineRawClass(); + final var returnClassDetails = returnedClass.determineRawClass(); return returnClassDetails.hasDirectAnnotationUsage( Embeddable.class ) && !property.hasDirectAnnotationUsage( Convert.class ); } @@ -317,25 +309,21 @@ static Component bindEmbeddable( } private static void callTypeBinders(Component component, MetadataBuildingContext context, TypeDetails annotatedClass ) { - final ModelsContext modelsContext = context.getBootstrapContext().getModelsContext(); - - final List metaAnnotatedAnnotations = annotatedClass.determineRawClass().getMetaAnnotated( TypeBinderType.class, modelsContext ); - if ( isEmpty( metaAnnotatedAnnotations ) ) { - return; - } - - for ( Annotation metaAnnotated : metaAnnotatedAnnotations ) { - final TypeBinderType binderType = metaAnnotated.annotationType().getAnnotation( TypeBinderType.class ); + final var metaAnnotatedAnnotations = + annotatedClass.determineRawClass() + .getMetaAnnotated( TypeBinderType.class, + context.getBootstrapContext().getModelsContext() ); + for ( var metaAnnotated : metaAnnotatedAnnotations ) { + final var binderType = metaAnnotated.annotationType().getAnnotation( TypeBinderType.class ); try { //noinspection rawtypes - final Class binderImpl = binderType.binder(); - //noinspection rawtypes - final TypeBinder binder = binderImpl.getDeclaredConstructor().newInstance(); + final TypeBinder binder = binderType.binder().getDeclaredConstructor().newInstance(); //noinspection unchecked binder.bind( metaAnnotated, context, component ); } - catch ( Exception e ) { - throw new AnnotationException( "error processing @TypeBinderType annotation '" + metaAnnotated + "'", e ); + catch (Exception e) { + throw new AnnotationException( + "error processing @TypeBinderType annotation '" + metaAnnotated + "'", e ); } } } @@ -349,7 +337,7 @@ private static PropertyBinder createEmbeddedProperty( boolean isId, Map inheritanceStatePerClass, Component component) { - final PropertyBinder binder = new PropertyBinder(); + final var binder = new PropertyBinder(); binder.setDeclaringClass( inferredData.getDeclaringClass() ); binder.setName( inferredData.getPropertyName() ); binder.setValue( component ); @@ -503,20 +491,21 @@ static Component fillEmbeddable( ); } + final var annotatedTypeDetails = inferredData.getPropertyType(); + final Map subclassToSuperclass = component.isPolymorphic() ? new HashMap<>() : null; - final TypeDetails annotatedType = inferredData.getPropertyType(); final List classElements = collectClassElements( propertyAccessor, context, returnedClassOrElement, - annotatedType, + annotatedTypeDetails, isIdClass, subclassToSuperclass ); if ( component.isPolymorphic() ) { validateInheritanceIsSupported( subholder, compositeUserType ); - final BasicType discriminatorType = (BasicType) component.getDiscriminator().getType(); + final var discriminatorType = (BasicType) component.getDiscriminator().getType(); // Discriminator values are used to construct the embeddable domain // type hierarchy so order of processing is important final Map discriminatorValues = new LinkedHashMap<>(); @@ -538,7 +527,7 @@ static Component fillEmbeddable( collectBaseClassElements( baseInferredData, propertyAccessor, context, entityAtStake ); if ( baseClassElements != null //useful to avoid breaking pre JPA 2 mappings - && !hasAnnotationsOnIdClass( annotatedType ) ) { + && !hasAnnotationsOnIdClass( annotatedTypeDetails ) ) { processIdClassElements( propertyHolder, baseInferredData, classElements, baseClassElements ); } for ( PropertyData propertyAnnotatedElement : classElements ) { @@ -557,12 +546,12 @@ static Component fillEmbeddable( inheritanceStatePerClass ); - final MemberDetails member = propertyAnnotatedElement.getAttributeMember(); + final var memberDetails = propertyAnnotatedElement.getAttributeMember(); if ( isIdClass || subholder.isOrWithinEmbeddedId() ) { - final Property property = findProperty( component, member.getName() ); + final var property = findProperty( component, memberDetails.getName() ); if ( property != null ) { // Identifier properties are always simple values - final SimpleValue value = (SimpleValue) property.getValue(); + final var value = (SimpleValue) property.getValue(); createIdGeneratorsFromGeneratorAnnotations( subholder, propertyAnnotatedElement, @@ -571,9 +560,9 @@ static Component fillEmbeddable( ); } } - else if ( member.hasDirectAnnotationUsage( GeneratedValue.class ) ) { + else if ( memberDetails.hasDirectAnnotationUsage( GeneratedValue.class ) ) { throw new AnnotationException( - "Property '" + member.getName() + "' of '" + "Property '" + memberDetails.getName() + "' of '" + getPath( propertyHolder, inferredData ) + "' is annotated '@GeneratedValue' but is not part of an identifier" ); } @@ -587,7 +576,7 @@ else if ( member.hasDirectAnnotationUsage( GeneratedValue.class ) ) { } private static Property findProperty(Component component, String name) { - for ( Property property : component.getProperties() ) { + for ( var property : component.getProperties() ) { if ( property.getName().equals( name ) ) { return property; } @@ -618,7 +607,7 @@ private static void bindDiscriminator( if ( inheritanceState == null ) { return; } - final AnnotatedDiscriminatorColumn discriminatorColumn = processEmbeddableDiscriminatorProperties( + final var discriminatorColumn = processEmbeddableDiscriminatorProperties( componentClass, propertyData, parentHolder, @@ -638,12 +627,9 @@ private static AnnotatedDiscriminatorColumn processEmbeddableDiscriminatorProper PropertyHolder holder, InheritanceState inheritanceState, MetadataBuildingContext context) { - final DiscriminatorColumn discriminatorColumn = annotatedClass.getDirectAnnotationUsage( DiscriminatorColumn.class ); - final DiscriminatorFormula discriminatorFormula = getOverridableAnnotation( - annotatedClass, - DiscriminatorFormula.class, - context - ); + final var discriminatorColumn = annotatedClass.getDirectAnnotationUsage( DiscriminatorColumn.class ); + final var discriminatorFormula = + getOverridableAnnotation( annotatedClass, DiscriminatorFormula.class, context ); if ( !inheritanceState.hasParents() ) { if ( inheritanceState.hasSiblings() ) { final String path = qualify( holder.getPath(), EntityDiscriminatorMapping.DISCRIMINATOR_ROLE_NAME ); @@ -690,7 +676,7 @@ private static void bindDiscriminatorColumnToComponent( PropertyHolder holder, MetadataBuildingContext context) { assert component.getDiscriminator() == null; - final AnnotatedColumns columns = new AnnotatedColumns(); + final var columns = new AnnotatedColumns(); columns.setPropertyHolder( holder ); columns.setBuildingContext( context ); discriminatorColumn.setParent( columns ); @@ -733,8 +719,7 @@ private static List collectClassElements( Map subclassToSuperclass) { final List classElements = new ArrayList<>(); //embeddable elements can have type defs - final PropertyContainer container = - new PropertyContainer( returnedClassOrElement, annotatedClass, propertyAccessor ); + final var container = new PropertyContainer( returnedClassOrElement, annotatedClass, propertyAccessor ); addElementsOfClass( classElements, container, context, 0 ); //add elements of the embeddable's mapped superclasses ClassDetails subclass = returnedClassOrElement; @@ -763,7 +748,7 @@ private static void collectSubclassElements( BasicType discriminatorType, Map discriminatorValues, Map subclassToSuperclass) { - for ( final ClassDetails subclass : context.getMetadataCollector().getEmbeddableSubclasses( superclass ) ) { + for ( var subclass : context.getMetadataCollector().getEmbeddableSubclasses( superclass ) ) { // collect the discriminator value details final String old = collectDiscriminatorValue( subclass, discriminatorType, discriminatorValues ); if ( old != null ) { @@ -776,7 +761,7 @@ private static void collectSubclassElements( final String put = subclassToSuperclass.put( subclass.getName().intern(), superclass.getName().intern() ); assert put == null; // collect property of subclass - final PropertyContainer superContainer = new PropertyContainer( subclass, superclass, propertyAccessor ); + final var superContainer = new PropertyContainer( subclass, superclass, propertyAccessor ); addElementsOfClass( classElements, superContainer, context, 0 ); // recursively do that same for all subclasses collectSubclassElements( @@ -795,9 +780,10 @@ private static String collectDiscriminatorValue( ClassDetails annotatedClass, BasicType discriminatorType, Map discriminatorValues) { - final String explicitValue = annotatedClass.hasDirectAnnotationUsage( DiscriminatorValue.class ) - ? annotatedClass.getDirectAnnotationUsage( DiscriminatorValue.class ).value() - : null; + final String explicitValue = + annotatedClass.hasDirectAnnotationUsage( DiscriminatorValue.class ) + ? annotatedClass.getDirectAnnotationUsage( DiscriminatorValue.class ).value() + : null; final String discriminatorValue; if ( isBlank( explicitValue ) ) { final String name = unqualify( annotatedClass.getName() ); @@ -830,9 +816,9 @@ private static boolean isValidSuperclass(ClassDetails superClass, boolean isIdCl } return superClass.hasDirectAnnotationUsage( MappedSuperclass.class ) - || ( isIdClass + || isIdClass && !superClass.getName().equals( Object.class.getName() ) - && !superClass.getName().equals( "java.lang.Record" ) ); + && !superClass.getName().equals( "java.lang.Record" ); } private static List collectBaseClassElements( @@ -846,11 +832,9 @@ private static List collectBaseClassElements( // might be spread across the subclasses and super classes. TypeDetails baseReturnedClassOrElement = baseInferredData.getClassOrElementType(); while ( !Object.class.getName().equals( baseReturnedClassOrElement.getName() ) ) { - final PropertyContainer container = new PropertyContainer( - baseReturnedClassOrElement.determineRawClass(), - entityAtStake, - propertyAccessor - ); + final var container = + new PropertyContainer( baseReturnedClassOrElement.determineRawClass(), + entityAtStake, propertyAccessor ); addElementsOfClass( baseClassElements, container, context, 0 ); baseReturnedClassOrElement = baseReturnedClassOrElement.determineRawClass().getGenericSuperType(); } @@ -865,12 +849,12 @@ private static void processCompositeUserType(Component component, CompositeUserT component.sortProperties(); final List sortedPropertyNames = new ArrayList<>( component.getPropertySpan() ); final List sortedPropertyTypes = new ArrayList<>( component.getPropertySpan() ); - final PropertyAccessStrategy strategy = new PropertyAccessStrategyCompositeUserTypeImpl( + final var strategy = new PropertyAccessStrategyCompositeUserTypeImpl( compositeUserType, sortedPropertyNames, sortedPropertyTypes ); - for ( Property property : component.getProperties() ) { + for ( var property : component.getProperties() ) { sortedPropertyNames.add( property.getName() ); sortedPropertyTypes.add( PropertyAccessStrategyGetterImpl.INSTANCE.buildPropertyAccess( @@ -887,12 +871,12 @@ private static boolean hasAnnotationsOnIdClass(TypeDetails idClassType) { return hasAnnotationsOnIdClass( idClassType.determineRawClass() ); } private static boolean hasAnnotationsOnIdClass(ClassDetails idClass) { - for ( FieldDetails field : idClass.getFields() ) { + for ( var field : idClass.getFields() ) { if ( hasTriggeringAnnotation( field ) ) { return true; } } - for ( MethodDetails method : idClass.getMethods() ) { + for ( var method : idClass.getMethods() ) { if ( hasTriggeringAnnotation( method ) ) { return true; } @@ -923,8 +907,7 @@ private static void processIdClassElements( for ( int i = 0; i < classElements.size(); i++ ) { final PropertyData idClassPropertyData = classElements.get( i ); final String propertyName = idClassPropertyData.getPropertyName(); - final PropertyData entityPropertyData = - baseClassElementsByName.get( propertyName ); + final PropertyData entityPropertyData = baseClassElementsByName.get( propertyName ); if ( propertyHolder.isInIdClass() ) { if ( entityPropertyData == null ) { throw new AnnotationException( @@ -954,8 +937,8 @@ private static void processIdClassElements( private static boolean hasCompatibleType(String typeNameInIdClass, String typeNameInEntityClass) { return typeNameInIdClass.equals( typeNameInEntityClass ) - || canonicalize( typeNameInIdClass ).equals( typeNameInEntityClass ) - || typeNameInIdClass.equals( canonicalize( typeNameInEntityClass ) ); + || canonicalize( typeNameInIdClass ).equals( typeNameInEntityClass ) + || typeNameInIdClass.equals( canonicalize( typeNameInEntityClass ) ); } private static String canonicalize(String typeName) { @@ -979,7 +962,7 @@ static Component createEmbeddable( boolean isIdentifierMapper, Class customInstantiatorImpl, MetadataBuildingContext context) { - final Component component = new Component( context, propertyHolder.getPersistentClass() ); + final var component = new Component( context, propertyHolder.getPersistentClass() ); component.setEmbedded( isComponentEmbedded ); //yuk component.setTable( propertyHolder.getTable() ); @@ -991,12 +974,12 @@ static Component createEmbeddable( component.setComponentClassName( inferredData.getClassOrElementType().getName() ); } component.setCustomInstantiator( customInstantiatorImpl ); - final Constructor constructor = resolveInstantiator( inferredData.getClassOrElementType() ); + final var constructor = resolveInstantiator( inferredData.getClassOrElementType() ); if ( constructor != null ) { component.setInstantiator( constructor, constructor.getAnnotation( Instantiator.class ).value() ); } if ( propertyHolder.isComponent() ) { - final ComponentPropertyHolder componentPropertyHolder = (ComponentPropertyHolder) propertyHolder; + final var componentPropertyHolder = (ComponentPropertyHolder) propertyHolder; component.setParentAggregateColumn( componentPropertyHolder.getAggregateColumn() ); } applyColumnNamingPattern( component, inferredData ); @@ -1015,7 +998,8 @@ private static void applyColumnNamingPattern(Component component, PropertyData i return; } - final EmbeddedColumnNaming columnNaming = inferredData.getAttributeMember().getDirectAnnotationUsage( EmbeddedColumnNaming.class ); + final var columnNaming = + inferredData.getAttributeMember().getDirectAnnotationUsage( EmbeddedColumnNaming.class ); if ( columnNaming == null ) { return; } @@ -1046,9 +1030,9 @@ private static Constructor resolveInstantiator(TypeDetails embeddableClass) { private static Constructor resolveInstantiator(ClassDetails embeddableClass) { if ( embeddableClass != null ) { - final Constructor[] declaredConstructors = embeddableClass.toJavaClass().getDeclaredConstructors(); + final var declaredConstructors = embeddableClass.toJavaClass().getDeclaredConstructors(); Constructor constructor = null; - for ( Constructor declaredConstructor : declaredConstructors ) { + for ( var declaredConstructor : declaredConstructors ) { if ( declaredConstructor.isAnnotationPresent( Instantiator.class ) ) { if ( constructor != null ) { throw new AnnotationException( "Multiple constructors of '" + embeddableClass.getName() @@ -1071,13 +1055,13 @@ public static Class determineCustomInstantiato return null; } - final org.hibernate.annotations.EmbeddableInstantiator propertyAnnotation = + final var propertyAnnotation = property.getDirectAnnotationUsage( org.hibernate.annotations.EmbeddableInstantiator.class ); if ( propertyAnnotation != null ) { return propertyAnnotation.value(); } - final org.hibernate.annotations.EmbeddableInstantiator classAnnotation = + final var classAnnotation = returnedClass.getDirectAnnotationUsage( org.hibernate.annotations.EmbeddableInstantiator.class ); if ( classAnnotation != null ) { return classAnnotation.value(); @@ -1127,8 +1111,8 @@ public boolean isInPrimaryKey() { @Override public void doSecondPass(Map persistentClasses) throws MappingException { - final PersistentClass referencedPersistentClass = persistentClasses.get( referencedEntityName ); - final Component referencedComponent = getReferencedComponent( referencedPersistentClass ); + final var referencedPersistentClass = persistentClasses.get( referencedEntityName ); + final var referencedComponent = getReferencedComponent( referencedPersistentClass ); //prepare column name structure boolean isExplicitReference = true; @@ -1200,22 +1184,22 @@ private Property createComponentProperty( Map columnByReferencedName, MutableInteger index, Property referencedProperty ) { - final Property property = new Property(); + final var property = new Property(); property.setName( referencedProperty.getName() ); //FIXME set optional? //property.setOptional( property.isOptional() ); property.setPersistentClass( component.getOwner() ); property.setPropertyAccessorName( referencedProperty.getPropertyAccessorName() ); - Component value = new Component( buildingContext, component.getOwner() ); + var value = new Component( buildingContext, component.getOwner() ); property.setValue( value ); - final Component referencedValue = (Component) referencedProperty.getValue(); + final var referencedValue = (Component) referencedProperty.getValue(); value.setTypeName( referencedValue.getTypeName() ); value.setTypeParameters( referencedValue.getTypeParameters() ); value.setComponentClassName( referencedValue.getComponentClassName() ); - for ( Property referencedComponentProperty : referencedValue.getProperties() ) { + for ( var referencedComponentProperty : referencedValue.getProperties() ) { if ( referencedComponentProperty.isComposite() ) { value.addProperty( createComponentProperty( isExplicitReference, @@ -1245,15 +1229,15 @@ private Property createSimpleProperty( Map columnByReferencedName, MutableInteger index, Property referencedProperty ) { - final Property property = new Property(); + final var property = new Property(); property.setName( referencedProperty.getName() ); //FIXME set optional? //property.setOptional( property.isOptional() ); property.setPersistentClass( component.getOwner() ); property.setPropertyAccessorName( referencedProperty.getPropertyAccessorName() ); - final SimpleValue value = new BasicValue( buildingContext, component.getTable() ); + final var value = new BasicValue( buildingContext, component.getTable() ); property.setValue( value ); - final SimpleValue referencedValue = (SimpleValue) referencedProperty.getValue(); + final var referencedValue = (SimpleValue) referencedProperty.getValue(); value.copyTypeFrom( referencedValue ); //TODO: this bit is nasty, move up to AnnotatedJoinColumns @@ -1266,7 +1250,7 @@ private Property createSimpleProperty( ); } else { - for ( Selectable selectable : referencedValue.getSelectables() ) { + for ( var selectable : referencedValue.getSelectables() ) { if ( selectable instanceof org.hibernate.mapping.Column column ) { final AnnotatedJoinColumn joinColumn; final String logicalColumnName; @@ -1293,7 +1277,7 @@ private Property createSimpleProperty( ? "tata_" + column.getName() : joinColumn.getName(); - final Database database = buildingContext.getMetadataCollector().getDatabase(); + final var database = buildingContext.getMetadataCollector().getDatabase(); final String physicalName = buildingContext.getBuildingOptions().getPhysicalNamingStrategy() .toPhysicalColumnName( database.toIdentifier( columnName ), @@ -1314,8 +1298,9 @@ private Property createSimpleProperty( return property; } - private void applyComponentColumnSizeValueToJoinColumn(org.hibernate.mapping.Column column, AnnotatedJoinColumn joinColumn) { - final org.hibernate.mapping.Column mappingColumn = joinColumn.getMappingColumn(); + private void applyComponentColumnSizeValueToJoinColumn( + org.hibernate.mapping.Column column, AnnotatedJoinColumn joinColumn) { + final var mappingColumn = joinColumn.getMappingColumn(); mappingColumn.setLength( column.getLength() ); mappingColumn.setPrecision( column.getPrecision() ); mappingColumn.setScale( column.getScale() ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java index 66833859f886..fcb37e258222 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java @@ -18,6 +18,7 @@ import jakarta.persistence.Inheritance; import jakarta.persistence.JoinColumn; import jakarta.persistence.JoinTable; +import jakarta.persistence.MappedSuperclass; import jakarta.persistence.NamedEntityGraph; import jakarta.persistence.PrimaryKeyJoinColumn; import jakarta.persistence.PrimaryKeyJoinColumns; @@ -35,6 +36,8 @@ import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.naming.ImplicitEntityNameSource; import org.hibernate.boot.model.naming.NamingStrategyHelper; +import org.hibernate.boot.model.naming.PhysicalNamingStrategy; +import org.hibernate.boot.model.relational.Database; import org.hibernate.boot.model.relational.QualifiedTableName; import org.hibernate.boot.models.HibernateAnnotations; import org.hibernate.boot.models.JpaAnnotations; @@ -45,9 +48,7 @@ import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.PropertyData; import org.hibernate.cfg.AvailableSettings; -import org.hibernate.dialect.Dialect; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.hibernate.engine.spi.FilterDefinition; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.collections.ArrayHelper; @@ -59,7 +60,6 @@ import org.hibernate.mapping.Join; import org.hibernate.mapping.JoinedSubclass; import org.hibernate.mapping.PersistentClass; -import org.hibernate.mapping.Property; import org.hibernate.mapping.RootClass; import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.SingleTableSubclass; @@ -72,7 +72,6 @@ import org.hibernate.models.internal.ClassTypeDetailsImpl; import org.hibernate.models.spi.AnnotationTarget; import org.hibernate.models.spi.ClassDetails; -import org.hibernate.models.spi.MemberDetails; import org.hibernate.models.spi.ModelsContext; import org.hibernate.models.spi.TypeDetails; import org.hibernate.spi.NavigablePath; @@ -169,6 +168,14 @@ private InFlightMetadataCollector getMetadataCollector() { return context.getMetadataCollector(); } + private PhysicalNamingStrategy getPhysicalNamingStrategy() { + return context.getBuildingOptions().getPhysicalNamingStrategy(); + } + + private Database getDatabase() { + return context.getMetadataCollector().getDatabase(); + } + /** * Bind an entity class. This can be done in a single pass. */ @@ -275,7 +282,7 @@ private static void bindSoftDelete( // todo (soft-delete) : do we assume all package-level registrations are already available? // or should this be a "second pass"? - final SoftDelete softDelete = extractSoftDelete( classDetails, context ); + final var softDelete = extractSoftDelete( classDetails, context ); if ( softDelete != null ) { SoftDeleteHelper.bindSoftDeleteIndicator( softDelete, @@ -288,16 +295,16 @@ private static void bindSoftDelete( private static SoftDelete extractSoftDelete(ClassDetails classDetails, MetadataBuildingContext context) { final var modelsContext = context.getBootstrapContext().getModelsContext(); - final SoftDelete fromClass = classDetails.getAnnotationUsage( SoftDelete.class, modelsContext ); + final var fromClass = classDetails.getAnnotationUsage( SoftDelete.class, modelsContext ); if ( fromClass != null ) { return fromClass; } ClassDetails classToCheck = classDetails.getSuperClass(); while ( classToCheck != null ) { - final SoftDelete fromSuper = classToCheck.getAnnotationUsage( SoftDelete.class, modelsContext ); + final var fromSuper = classToCheck.getAnnotationUsage( SoftDelete.class, modelsContext ); if ( fromSuper != null - && classToCheck.hasAnnotationUsage( jakarta.persistence.MappedSuperclass.class, modelsContext ) ) { + && classToCheck.hasAnnotationUsage( MappedSuperclass.class, modelsContext ) ) { return fromSuper; } classToCheck = classToCheck.getSuperClass(); @@ -309,13 +316,13 @@ private static SoftDelete extractSoftDelete(ClassDetails classDetails, MetadataB private void handleCheckConstraints() { if ( annotatedClass.hasAnnotationUsage( Checks.class, modelsContext() ) ) { // if we have more than one of them they are not overrideable - final Checks explicitUsage = annotatedClass.getAnnotationUsage( Checks.class, modelsContext() ); - for ( Check check : explicitUsage.value() ) { + final var explicitUsage = annotatedClass.getAnnotationUsage( Checks.class, modelsContext() ); + for ( var check : explicitUsage.value() ) { addCheckToEntity( check ); } } else { - final Check check = getOverridableAnnotation( annotatedClass, Check.class, context ); + final var check = getOverridableAnnotation( annotatedClass, Check.class, context ); if ( check != null ) { addCheckToEntity( check ); } @@ -336,7 +343,7 @@ private void addCheckToEntity(Check check) { private void callTypeBinders(PersistentClass persistentClass) { final var metaAnnotatedList = annotatedClass.getMetaAnnotated( TypeBinderType.class, modelsContext() ); - for ( Annotation metaAnnotated : metaAnnotatedList ) { + for ( var metaAnnotated : metaAnnotatedList ) { applyTypeBinder( metaAnnotated, persistentClass ); } } @@ -346,7 +353,6 @@ private void applyTypeBinder(Annotation containingAnnotation, PersistentClass pe containingAnnotation.annotationType() .getAnnotation( TypeBinderType.class ) .binder(); - try { //noinspection rawtypes final TypeBinder binder = binderClass.getConstructor().newInstance(); @@ -386,7 +392,7 @@ private void processComplementaryTableDefinitions() { final var models = modelsContext(); final var jpaTableUsage = annotatedClass.getAnnotationUsage( jakarta.persistence.Table.class, models ); if ( jpaTableUsage != null ) { - final Table table = persistentClass.getTable(); + final var table = persistentClass.getTable(); TableBinder.addJpaIndexes( table, jpaTableUsage.indexes(), context ); TableBinder.addTableCheck( table, jpaTableUsage.check() ); TableBinder.addTableComment( table, jpaTableUsage.comment() ); @@ -396,7 +402,7 @@ private void processComplementaryTableDefinitions() { final var entityTableXref = getMetadataCollector().getEntityTableXref( persistentClass.getEntityName() ); annotatedClass.forEachAnnotationUsage( jakarta.persistence.SecondaryTable.class, models, (usage) -> { final Identifier secondaryTableLogicalName = toIdentifier( usage.name() ); - final Table table = entityTableXref.resolveTable( secondaryTableLogicalName ); + final var table = entityTableXref.resolveTable( secondaryTableLogicalName ); assert table != null; TableBinder.addJpaIndexes( table, usage.indexes(), context ); } ); @@ -483,7 +489,7 @@ private boolean mapAsIdClass( else { final boolean ignoreIdAnnotations = isIgnoreIdAnnotations(); this.ignoreIdAnnotations = true; - final Component idClassComponent = bindIdClass( + final var idClassComponent = bindIdClass( inferredData, baseInferredData, propertyHolder, @@ -491,7 +497,7 @@ private boolean mapAsIdClass( context, inheritanceStates ); - final Component mapper = createMapperProperty( + final var mapper = createMapperProperty( inheritanceStates, persistentClass, propertyHolder, @@ -506,7 +512,7 @@ private boolean mapAsIdClass( mapper.setSimpleRecord( true ); } this.ignoreIdAnnotations = ignoreIdAnnotations; - for ( Property property : mapper.getProperties() ) { + for ( var property : mapper.getProperties() ) { idPropertiesIfIdClass.add( property.getName() ); } return true; @@ -514,12 +520,12 @@ private boolean mapAsIdClass( } private ClassDetails idClassDetails(InheritanceState inheritanceState, ClassDetails classWithIdClass) { - final IdClass idClassAnn = classWithIdClass.getDirectAnnotationUsage( IdClass.class ); + final var idClassAnn = classWithIdClass.getDirectAnnotationUsage( IdClass.class ); final var classDetailsRegistry = modelsContext().getClassDetailsRegistry(); if ( idClassAnn == null ) { try { // look for an Id class generated by Hibernate Processor as an inner class of static metamodel - final Class javaClass = inheritanceState.getClassDetails().toJavaClass(); + final var javaClass = inheritanceState.getClassDetails().toJavaClass(); final String generatedIdClassName = getGeneratedClassName( javaClass ) + "$Id"; return classDetailsRegistry.resolveClassDetails( generatedIdClassName ); } @@ -548,7 +554,7 @@ private Component createMapperProperty( PropertyData baseInferredData, AccessType propertyAccessor, boolean isIdClass) { - final Component mapper = createMapper( + final var mapper = createMapper( inheritanceStates, persistentClass, propertyHolder, @@ -559,7 +565,7 @@ private Component createMapperProperty( propertyAccessor, isIdClass ); - final Property mapperProperty = new SyntheticProperty(); + final var mapperProperty = new SyntheticProperty(); mapperProperty.setName( NavigablePath.IDENTIFIER_MAPPER_PROPERTY ); mapperProperty.setUpdatable( false ); mapperProperty.setInsertable( false ); @@ -579,7 +585,7 @@ private Component createMapper( PropertyData baseInferredData, AccessType propertyAccessor, boolean isIdClass) { - final Component mapper = fillEmbeddable( + final var mapper = fillEmbeddable( propertyHolder, new PropertyPreloadedData( propertyAccessor, @@ -621,10 +627,11 @@ private static PropertyData getUniqueIdPropertyFromBaseClass( AccessType propertyAccessor, MetadataBuildingContext context) { final List baseClassElements = new ArrayList<>(); - final var propContainer = + final var propertyContainer = new PropertyContainer( baseInferredData.getClassOrElementType().determineRawClass(), inferredData.getPropertyType(), propertyAccessor ); - final int idPropertyCount = addElementsOfClass( baseClassElements, propContainer, context, 0 ); + final int idPropertyCount = + addElementsOfClass( baseClassElements, propertyContainer, context, 0 ); assert idPropertyCount == 1; //Id properties are on top and there is only one return baseClassElements.get( 0 ); @@ -648,24 +655,23 @@ private boolean isIdClassPrimaryKeyOfAssociatedEntity( // entity referenced via a @ManyToOne or @OneToOne association final PropertyData idPropertyOnBaseClass = getUniqueIdPropertyFromBaseClass( inferredData, baseInferredData, propertyAccessor, context ); - final TypeDetails idPropertyType = idPropertyOnBaseClass.getClassOrElementType(); - final InheritanceState state = inheritanceStates.get( idPropertyType.determineRawClass() ); + final var idTypeDetails = idPropertyOnBaseClass.getClassOrElementType(); + final var state = inheritanceStates.get( idTypeDetails.determineRawClass() ); if ( state == null ) { // Likely a user error, but treat it as something that might happen return false; } else { - final ClassDetails associatedClassWithIdClass = state.getClassWithIdClass( true ); + final var associatedClassWithIdClass = state.getClassWithIdClass( true ); if ( associatedClassWithIdClass == null ) { // If annotated @OneToOne or @ManyToOne, it's an association to another entity return hasToOneAnnotation( idPropertyOnBaseClass.getAttributeMember() ) // determine if the @Id or @EmbeddedId tpe is the same - && isIdClassOfAssociatedEntity( compositeClass, propertyAccessor, context, idPropertyType ); + && isIdClassOfAssociatedEntity( compositeClass, propertyAccessor, context, idTypeDetails ); } else { // The associated entity has an @IdClass, so check if it's the same - final IdClass idClass = - associatedClassWithIdClass.getAnnotationUsage( IdClass.class, modelsContext() ); + final var idClass = associatedClassWithIdClass.getAnnotationUsage( IdClass.class, modelsContext() ); return compositeClass.getName().equals( idClass.value().getName() ); } } @@ -715,7 +721,7 @@ private Component bindIdClass( throw new AnnotationException( "Entity '" + persistentClass.getEntityName() + "' is a subclass in an entity inheritance hierarchy and may not redefine the identifier of the root entity" ); } - final Component id = fillEmbeddable( + final var id = fillEmbeddable( propertyHolder, inferredData, baseInferredData, @@ -799,8 +805,8 @@ private void createTable( String catalog, UniqueConstraint[] uniqueConstraints) { final var models = modelsContext(); - final RowId rowId = annotatedClass.getAnnotationUsage( RowId.class, models ); - final View view = annotatedClass.getAnnotationUsage( View.class, models ); + final var rowId = annotatedClass.getAnnotationUsage( RowId.class, models ); + final var view = annotatedClass.getAnnotationUsage( View.class, models ); bindTable( schema, catalog, @@ -844,8 +850,7 @@ private void handleInheritance( } private void singleTableInheritance(InheritanceState inheritanceState, PropertyHolder holder) { - final AnnotatedDiscriminatorColumn discriminatorColumn = - processSingleTableDiscriminatorProperties( inheritanceState ); + final var discriminatorColumn = processSingleTableDiscriminatorProperties( inheritanceState ); // todo : sucks that this is separate from RootClass distinction if ( !inheritanceState.hasParents() ) { final var rootClass = (RootClass) persistentClass; @@ -866,10 +871,10 @@ private void joinedInheritance(InheritanceState state, PersistentClass superEnti final var key = new DependantValue( context, joinedSubclass.getTable(), joinedSubclass.getIdentifier() ); joinedSubclass.setKey( key ); handleForeignKeys( annotatedClass, context, key ); - final OnDelete onDelete = annotatedClass.getAnnotationUsage( OnDelete.class, modelsContext() ); + final var onDelete = annotatedClass.getAnnotationUsage( OnDelete.class, modelsContext() ); key.setOnDeleteAction( onDelete == null ? null : onDelete.action() ); //we are never in a second pass at that stage, so queue it - final InFlightMetadataCollector metadataCollector = getMetadataCollector(); + final var metadataCollector = getMetadataCollector(); metadataCollector.addSecondPass( new JoinedSubclassFkSecondPass( joinedSubclass, joinColumns, key, context) ); metadataCollector.addSecondPass( new CreateKeySecondPass( joinedSubclass ) ); } @@ -908,15 +913,15 @@ private void checkNoOnDelete(ClassDetails annotatedClass) { } private void handleForeignKeys(ClassDetails clazzToProcess, MetadataBuildingContext context, DependantValue key) { - final PrimaryKeyJoinColumn pkJoinColumn = clazzToProcess.getDirectAnnotationUsage( PrimaryKeyJoinColumn.class ); - final PrimaryKeyJoinColumns pkJoinColumns = clazzToProcess.getDirectAnnotationUsage( PrimaryKeyJoinColumns.class ); + final var pkJoinColumn = clazzToProcess.getDirectAnnotationUsage( PrimaryKeyJoinColumn.class ); + final var pkJoinColumns = clazzToProcess.getDirectAnnotationUsage( PrimaryKeyJoinColumns.class ); final boolean noConstraintByDefault = context.getBuildingOptions().isNoConstraintByDefault(); if ( pkJoinColumn != null && noConstraint( pkJoinColumn.foreignKey(), noConstraintByDefault ) || pkJoinColumns != null && noConstraint( pkJoinColumns.foreignKey(), noConstraintByDefault ) ) { key.disableForeignKey(); } else { - final ForeignKey foreignKey = clazzToProcess.getDirectAnnotationUsage( ForeignKey.class ); + final var foreignKey = clazzToProcess.getDirectAnnotationUsage( ForeignKey.class ); if ( noConstraint( foreignKey, noConstraintByDefault ) ) { key.disableForeignKey(); } @@ -929,13 +934,13 @@ else if ( noConstraintByDefault ) { key.disableForeignKey(); } else if ( pkJoinColumns != null ) { - final ForeignKey nestedFk = pkJoinColumns.foreignKey(); + final var nestedFk = pkJoinColumns.foreignKey(); key.setForeignKeyName( nullIfEmpty( nestedFk.name() ) ); key.setForeignKeyDefinition( nullIfEmpty( nestedFk.foreignKeyDefinition() ) ); key.setForeignKeyOptions( nestedFk.options() ); } else if ( pkJoinColumn != null ) { - final ForeignKey nestedFk = pkJoinColumn.foreignKey(); + final var nestedFk = pkJoinColumn.foreignKey(); key.setForeignKeyName( nullIfEmpty( nestedFk.name() ) ); key.setForeignKeyDefinition( nullIfEmpty( nestedFk.foreignKeyDefinition() ) ); key.setForeignKeyOptions( nestedFk.options() ); @@ -966,7 +971,7 @@ private void bindDiscriminatorColumnToRootPersistentClass( rootClass.setPolymorphic( true ); getMetadataCollector() .addSecondPass( new DiscriminatorColumnSecondPass( rootClass.getEntityName(), - context.getMetadataCollector().getDatabase().getDialect() ) ); + getDatabase().getDialect() ) ); } } @@ -974,10 +979,8 @@ private void bindDiscriminatorColumnToRootPersistentClass( * Process all discriminator-related metadata per rules for "single table" inheritance */ private AnnotatedDiscriminatorColumn processSingleTableDiscriminatorProperties(InheritanceState inheritanceState) { - final DiscriminatorColumn discriminatorColumn = - annotatedClass.getAnnotationUsage( DiscriminatorColumn.class, modelsContext() ); - final DiscriminatorFormula discriminatorFormula = - getOverridableAnnotation( annotatedClass, DiscriminatorFormula.class, context ); + final var discriminatorColumn = annotatedClass.getAnnotationUsage( DiscriminatorColumn.class, modelsContext() ); + final var discriminatorFormula = getOverridableAnnotation( annotatedClass, DiscriminatorFormula.class, context ); if ( !inheritanceState.hasParents() || annotatedClass.hasAnnotationUsage( Inheritance.class, modelsContext() ) ) { @@ -1004,15 +1007,16 @@ private AnnotatedDiscriminatorColumn processSingleTableDiscriminatorProperties(I * and {@value AvailableSettings#IGNORE_EXPLICIT_DISCRIMINATOR_COLUMNS_FOR_JOINED_SUBCLASS}. */ private AnnotatedDiscriminatorColumn processJoinedDiscriminatorProperties(InheritanceState inheritanceState) { - if ( annotatedClass.hasAnnotationUsage( DiscriminatorFormula.class, modelsContext() ) ) { + final var modelContext = modelsContext(); + + if ( annotatedClass.hasAnnotationUsage( DiscriminatorFormula.class, modelContext ) ) { throw new AnnotationException( "Entity class '" + annotatedClass.getName() + "' has 'JOINED' inheritance and is annotated '@DiscriminatorFormula'" ); } - final DiscriminatorColumn discriminatorColumn = - annotatedClass.getAnnotationUsage( DiscriminatorColumn.class, modelsContext() ); + final var discriminatorColumn = annotatedClass.getAnnotationUsage( DiscriminatorColumn.class, modelContext ); if ( !inheritanceState.hasParents() - || annotatedClass.hasAnnotationUsage( Inheritance.class, modelsContext() ) ) { + || annotatedClass.hasAnnotationUsage( Inheritance.class, modelContext ) ) { return useDiscriminatorColumnForJoined( discriminatorColumn ) ? buildDiscriminatorColumn( discriminatorColumn, null, null, DEFAULT_DISCRIMINATOR_COLUMN_NAME, context ) : null; @@ -1073,8 +1077,8 @@ private void processIdPropertiesIfNotAlready( for ( PropertyData propertyAnnotatedElement : elementsToProcess.getElements() ) { final String propertyName = propertyAnnotatedElement.getPropertyName(); if ( !idPropertiesIfIdClass.contains( propertyName ) ) { - final MemberDetails property = propertyAnnotatedElement.getAttributeMember(); - final boolean hasIdAnnotation = hasIdAnnotation( property ); + final var memberDetails = propertyAnnotatedElement.getAttributeMember(); + final boolean hasIdAnnotation = hasIdAnnotation( memberDetails ); if ( !idPropertiesIfIdClass.isEmpty() && !isIgnoreIdAnnotations() && hasIdAnnotation ) { missingEntityProperties.add( propertyName ); } @@ -1082,7 +1086,7 @@ private void processIdPropertiesIfNotAlready( final boolean subclassAndSingleTableStrategy = inheritanceState.getType() == SINGLE_TABLE && inheritanceState.hasParents(); - if ( !hasIdAnnotation && property.hasAnnotationUsage( GeneratedValue.class, modelsContext() ) ) { + if ( !hasIdAnnotation && memberDetails.hasAnnotationUsage( GeneratedValue.class, modelsContext() ) ) { throw new AnnotationException( "Property '" + getPath( propertyHolder, propertyAnnotatedElement ) + "' is annotated '@GeneratedValue' but is not part of an identifier" ); } @@ -1154,27 +1158,14 @@ private static AnnotatedJoinColumns subclassJoinColumns( final var joinColumns = new AnnotatedJoinColumns(); joinColumns.setBuildingContext( context ); - final ModelsContext modelsContext = context.getBootstrapContext().getModelsContext(); - final PrimaryKeyJoinColumns primaryKeyJoinColumns = + final var modelsContext = context.getBootstrapContext().getModelsContext(); + final var primaryKeyJoinColumns = clazzToProcess.getAnnotationUsage( PrimaryKeyJoinColumns.class, modelsContext ); - if ( primaryKeyJoinColumns != null ) { - final PrimaryKeyJoinColumn[] columns = primaryKeyJoinColumns.value(); - if ( !ArrayHelper.isEmpty( columns ) ) { - for ( PrimaryKeyJoinColumn column : columns ) { - buildInheritanceJoinColumn( - column, - null, - superEntity.getIdentifier(), - joinColumns, - context - ); - } - } - else { - final PrimaryKeyJoinColumn columnAnnotation = - clazzToProcess.getAnnotationUsage( PrimaryKeyJoinColumn.class, modelsContext ); + if ( primaryKeyJoinColumns != null + && !ArrayHelper.isEmpty( primaryKeyJoinColumns.value() ) ) { + for ( var column : primaryKeyJoinColumns.value() ) { buildInheritanceJoinColumn( - columnAnnotation, + column, null, superEntity.getIdentifier(), joinColumns, @@ -1199,12 +1190,12 @@ private static PersistentClass getSuperEntity( Map inheritanceStates, MetadataBuildingContext context, InheritanceState inheritanceState) { - final InheritanceState superState = getInheritanceStateOfSuperEntity( clazzToProcess, inheritanceStates ); + final var superState = getInheritanceStateOfSuperEntity( clazzToProcess, inheritanceStates ); if ( superState == null ) { return null; } else { - final PersistentClass superEntity = + final var superEntity = context.getMetadataCollector() .getEntityBinding( superState.getClassDetails().getName() ); //check if superclass is not a potential persistent class @@ -1249,34 +1240,32 @@ public boolean isPropertyDefinedInSuperHierarchy(String name) { } private void bindRowManagement() { - final DynamicInsert dynamicInsertAnn = - annotatedClass.getAnnotationUsage( DynamicInsert.class, modelsContext() ); + final var ontext = modelsContext(); + final var dynamicInsertAnn = annotatedClass.getAnnotationUsage( DynamicInsert.class, ontext ); persistentClass.setDynamicInsert( dynamicInsertAnn != null ); - final DynamicUpdate dynamicUpdateAnn = - annotatedClass.getAnnotationUsage( DynamicUpdate.class, modelsContext() ); + final var dynamicUpdateAnn = annotatedClass.getAnnotationUsage( DynamicUpdate.class, ontext ); persistentClass.setDynamicUpdate( dynamicUpdateAnn != null ); if ( persistentClass.useDynamicInsert() - && annotatedClass.hasAnnotationUsage( SQLInsert.class, modelsContext() ) ) { + && annotatedClass.hasAnnotationUsage( SQLInsert.class, ontext ) ) { throw new AnnotationException( "Entity '" + name + "' is annotated both '@DynamicInsert' and '@SQLInsert'" ); } if ( persistentClass.useDynamicUpdate() - && annotatedClass.hasAnnotationUsage( SQLUpdate.class, modelsContext() ) ) { + && annotatedClass.hasAnnotationUsage( SQLUpdate.class, ontext ) ) { throw new AnnotationException( "Entity '" + name + "' is annotated both '@DynamicUpdate' and '@SQLUpdate'" ); } } private void bindOptimisticLocking() { - final OptimisticLocking optimisticLockingAnn = - annotatedClass.getAnnotationUsage( OptimisticLocking.class, modelsContext() ); + final var optimisticLockingAnn = annotatedClass.getAnnotationUsage( OptimisticLocking.class, modelsContext() ); persistentClass.setOptimisticLockStyle( fromLockType( optimisticLockingAnn == null ? OptimisticLockType.VERSION : optimisticLockingAnn.type() ) ); } private void bindEntityAnnotation() { - final Entity entity = annotatedClass.getAnnotationUsage( Entity.class, modelsContext() ); + final var entity = annotatedClass.getAnnotationUsage( Entity.class, modelsContext() ); if ( entity == null ) { throw new AssertionFailure( "@Entity should never be missing" ); } @@ -1377,7 +1366,7 @@ private void bindRootEntity() { private void bindCustomSql() { final String primaryTableName = persistentClass.getTable().getName(); - SQLInsert sqlInsert = resolveCustomSqlAnnotation( annotatedClass, SQLInsert.class, primaryTableName ); + var sqlInsert = resolveCustomSqlAnnotation( annotatedClass, SQLInsert.class, primaryTableName ); if ( sqlInsert == null ) { sqlInsert = resolveCustomSqlAnnotation( annotatedClass, SQLInsert.class, "" ); } @@ -1387,13 +1376,13 @@ private void bindCustomSql() { sqlInsert.callable(), fromResultCheckStyle( sqlInsert.check() ) ); - final Class expectationClass = sqlInsert.verify(); + final var expectationClass = sqlInsert.verify(); if ( expectationClass != Expectation.class ) { - persistentClass.setInsertExpectation( getDefaultSupplier( expectationClass ) ); + persistentClass.setInsertExpectation( getDefaultSupplier( expectationClass ) ); } } - SQLUpdate sqlUpdate = resolveCustomSqlAnnotation( annotatedClass, SQLUpdate.class, primaryTableName ); + var sqlUpdate = resolveCustomSqlAnnotation( annotatedClass, SQLUpdate.class, primaryTableName ); if ( sqlUpdate == null ) { sqlUpdate = resolveCustomSqlAnnotation( annotatedClass, SQLUpdate.class, "" ); } @@ -1403,13 +1392,13 @@ private void bindCustomSql() { sqlUpdate.callable(), fromResultCheckStyle( sqlUpdate.check() ) ); - final Class expectationClass = sqlUpdate.verify(); + final var expectationClass = sqlUpdate.verify(); if ( expectationClass != Expectation.class ) { persistentClass.setUpdateExpectation( getDefaultSupplier( expectationClass ) ); } } - SQLDelete sqlDelete = resolveCustomSqlAnnotation( annotatedClass, SQLDelete.class, primaryTableName ); + var sqlDelete = resolveCustomSqlAnnotation( annotatedClass, SQLDelete.class, primaryTableName ); if ( sqlDelete == null ) { sqlDelete = resolveCustomSqlAnnotation( annotatedClass, SQLDelete.class, "" ); } @@ -1419,26 +1408,26 @@ private void bindCustomSql() { sqlDelete.callable(), fromResultCheckStyle( sqlDelete.check() ) ); - final Class expectationClass = sqlDelete.verify(); + final var expectationClass = sqlDelete.verify(); if ( expectationClass != Expectation.class ) { persistentClass.setDeleteExpectation( getDefaultSupplier( expectationClass ) ); } } - final SQLDeleteAll sqlDeleteAll = resolveCustomSqlAnnotation( annotatedClass, SQLDeleteAll.class, "" ); + final var sqlDeleteAll = resolveCustomSqlAnnotation( annotatedClass, SQLDeleteAll.class, "" ); if ( sqlDeleteAll != null ) { throw new AnnotationException("@SQLDeleteAll does not apply to entities: " + persistentClass.getEntityName()); } - final SQLSelect sqlSelect = getOverridableAnnotation( annotatedClass, SQLSelect.class, context ); + final var sqlSelect = getOverridableAnnotation( annotatedClass, SQLSelect.class, context ); if ( sqlSelect != null ) { final String loaderName = persistentClass.getEntityName() + "$SQLSelect"; persistentClass.setLoaderName( loaderName ); QueryBinder.bindNativeQuery( loaderName, sqlSelect, annotatedClass, context ); } - final HQLSelect hqlSelect = annotatedClass.getAnnotationUsage( HQLSelect.class, modelsContext() ); + final var hqlSelect = annotatedClass.getAnnotationUsage( HQLSelect.class, modelsContext() ); if ( hqlSelect != null ) { final String loaderName = persistentClass.getEntityName() + "$HQLSelect"; persistentClass.setLoaderName( loaderName ); @@ -1447,7 +1436,7 @@ private void bindCustomSql() { } private void bindSubselect() { - final Subselect subselect = annotatedClass.getAnnotationUsage( Subselect.class, modelsContext() ); + final var subselect = annotatedClass.getAnnotationUsage( Subselect.class, modelsContext() ); if ( subselect != null ) { this.subselect = subselect.value(); } @@ -1466,10 +1455,10 @@ private A resolveCustomSqlAnnotation( final Annotation[] dialectOverrides = annotatedClass.getRepeatedAnnotationUsages( overrideAnnotation, modelsContext() ); if ( isNotEmpty( dialectOverrides ) ) { - final Dialect dialect = getMetadataCollector().getDatabase().getDialect(); - for ( Annotation annotation : dialectOverrides ) { + final var dialect = getDatabase().getDialect(); + for ( var annotation : dialectOverrides ) { //noinspection unchecked - final DialectOverrider dialectOverride = (DialectOverrider) annotation; + final var dialectOverride = (DialectOverrider) annotation; if ( dialectOverride.matches( dialect ) ) { final A override = dialectOverride.override(); final String table = ((CustomSqlDetails) override).table(); @@ -1485,7 +1474,7 @@ private A resolveCustomSqlAnnotation( } private void bindFilters() { - for ( Filter filter : filters ) { + for ( var filter : filters ) { final String filterName = filter.name(); String condition = filter.condition(); if ( condition.isBlank() ) { @@ -1502,7 +1491,7 @@ private void bindFilters() { } private String getDefaultFilterCondition(String filterName) { - final FilterDefinition definition = getMetadataCollector().getFilterDefinition( filterName ); + final var definition = getMetadataCollector().getFilterDefinition( filterName ); if ( definition == null ) { throw new AnnotationException( "Entity '" + name + "' has a '@Filter' for an undefined filter named '" + filterName + "'" ); @@ -1517,9 +1506,9 @@ private String getDefaultFilterCondition(String filterName) { } private void bindSynchronize() { - final Synchronize synchronize = annotatedClass.getAnnotationUsage( Synchronize.class, modelsContext() ); + final var synchronize = annotatedClass.getAnnotationUsage( Synchronize.class, modelsContext() ); if ( synchronize != null ) { - final var jdbcEnvironment = getMetadataCollector().getDatabase().getJdbcEnvironment(); + final var jdbcEnvironment = getDatabase().getJdbcEnvironment(); final boolean logical = synchronize.logical(); for ( String tableName : synchronize.value() ) { final String physicalName = logical ? toPhysicalName( jdbcEnvironment, tableName ) : tableName; @@ -1530,7 +1519,7 @@ private void bindSynchronize() { private String toPhysicalName(JdbcEnvironment jdbcEnvironment, String logicalName) { final var identifier = jdbcEnvironment.getIdentifierHelper().toIdentifier( logicalName ); - return context.getBuildingOptions().getPhysicalNamingStrategy() + return getPhysicalNamingStrategy() .toPhysicalTableName( identifier, jdbcEnvironment ) .render( jdbcEnvironment.getDialect() ); } @@ -1541,7 +1530,6 @@ public PersistentClass getPersistentClass() { private void processNamedEntityGraphs() { annotatedClass.forEachAnnotationUsage( NamedEntityGraph.class, modelsContext(), this::processNamedEntityGraph ); - processParsedNamedGraphs(); } @@ -1587,9 +1575,8 @@ private NamedEntityGraphDefinition namedEntityGraphDefinition(org.hibernate.anno } private void bindDiscriminatorValue() { - final DiscriminatorValue discriminatorValueAnn = - annotatedClass.getAnnotationUsage( DiscriminatorValue.class, modelsContext() ); - if ( discriminatorValueAnn == null ) { + final var discriminatorValue = annotatedClass.getAnnotationUsage( DiscriminatorValue.class, modelsContext() ); + if ( discriminatorValue == null ) { final Value discriminator = persistentClass.getDiscriminator(); if ( discriminator == null ) { persistentClass.setDiscriminatorValue( name ); @@ -1609,14 +1596,13 @@ private void bindDiscriminatorValue() { } } else { - persistentClass.setDiscriminatorValue( discriminatorValueAnn.value() ); + persistentClass.setDiscriminatorValue( discriminatorValue.value() ); } } private void bindConcreteProxy() { - final ConcreteProxy annotationUsage = - annotatedClass.getAnnotationUsage( ConcreteProxy.class, modelsContext() ); - if ( annotationUsage != null ) { + final var concreteProxy = annotatedClass.getAnnotationUsage( ConcreteProxy.class, modelsContext() ); + if ( concreteProxy != null ) { if ( persistentClass.getSuperclass() != null ) { throw new AnnotationException( "Entity class '" + persistentClass.getClassName() + "' is annotated '@ConcreteProxy' but it is not the root of the entity inheritance hierarchy" ); @@ -1626,7 +1612,7 @@ private void bindConcreteProxy() { } private void bindSqlRestriction() { - final SQLRestriction restriction = extractSQLRestriction( annotatedClass ); + final var restriction = extractSQLRestriction( annotatedClass ); if ( restriction != null ) { where = restriction.value(); } @@ -1634,15 +1620,15 @@ private void bindSqlRestriction() { private SQLRestriction extractSQLRestriction(ClassDetails classDetails) { final var modelsContext = modelsContext(); - final SQLRestriction fromClass = getOverridableAnnotation( classDetails, SQLRestriction.class, context ); + final var fromClass = getOverridableAnnotation( classDetails, SQLRestriction.class, context ); if ( fromClass != null ) { return fromClass; } // as a special favor to users, we allow @SQLRestriction to be declared on a @MappedSuperclass ClassDetails classToCheck = classDetails.getSuperClass(); while ( classToCheck != null - && classToCheck.hasAnnotationUsage( jakarta.persistence.MappedSuperclass.class, modelsContext ) ) { - final SQLRestriction fromSuper = getOverridableAnnotation( classToCheck, SQLRestriction.class, context ); + && classToCheck.hasAnnotationUsage( MappedSuperclass.class, modelsContext ) ) { + final var fromSuper = getOverridableAnnotation( classToCheck, SQLRestriction.class, context ); if ( fromSuper != null ) { return fromSuper; } @@ -1652,20 +1638,18 @@ private SQLRestriction extractSQLRestriction(ClassDetails classDetails) { } private void bindNaturalIdCache() { - final NaturalIdCache naturalIdCacheAnn = - annotatedClass.getAnnotationUsage( NaturalIdCache.class, modelsContext() ); - if ( naturalIdCacheAnn != null ) { - final String region = naturalIdCacheAnn.region(); + final var naturalIdCache = annotatedClass.getAnnotationUsage( NaturalIdCache.class, modelsContext() ); + if ( naturalIdCache != null ) { + final String region = naturalIdCache.region(); if ( region.isBlank() ) { - final Cache explicitCacheAnn = - annotatedClass.getAnnotationUsage( Cache.class, modelsContext() ); + final var explicitCache = annotatedClass.getAnnotationUsage( Cache.class, modelsContext() ); naturalIdCacheRegion = - explicitCacheAnn != null && isNotBlank( explicitCacheAnn.region() ) - ? explicitCacheAnn.region() + NATURAL_ID_CACHE_SUFFIX + explicitCache != null && isNotBlank( explicitCache.region() ) + ? explicitCache.region() + NATURAL_ID_CACHE_SUFFIX : annotatedClass.getName() + NATURAL_ID_CACHE_SUFFIX; } else { - naturalIdCacheRegion = naturalIdCacheAnn.region(); + naturalIdCacheRegion = naturalIdCache.region(); } } else { @@ -1709,19 +1693,18 @@ private void bindSubclassCache() { private void bindRootClassCache() { final var sourceModelContext = modelsContext(); - final Cache cache = annotatedClass.getAnnotationUsage( Cache.class, sourceModelContext ); - final Cacheable cacheable = annotatedClass.getAnnotationUsage( Cacheable.class, sourceModelContext ); + final var cache = annotatedClass.getAnnotationUsage( Cache.class, sourceModelContext ); + final var cacheable = annotatedClass.getAnnotationUsage( Cacheable.class, sourceModelContext ); // preserve legacy behavior of circumventing SharedCacheMode when Hibernate @Cache is used - final Cache effectiveCache = cache != null ? cache : buildCacheMock( annotatedClass ); + final var effectiveCache = cache != null ? cache : buildCacheMock( annotatedClass ); isCached = cache != null || isCacheable( cacheable ); cacheConcurrentStrategy = getCacheConcurrencyStrategy( effectiveCache.usage() ); cacheRegion = effectiveCache.region(); cacheLazyProperty = effectiveCache.includeLazy(); - final QueryCacheLayout queryCache = - annotatedClass.getAnnotationUsage( QueryCacheLayout.class, sourceModelContext ); + final var queryCache = annotatedClass.getAnnotationUsage( QueryCacheLayout.class, sourceModelContext ); queryCacheLayout = queryCache == null ? null : queryCache.layout(); } @@ -1909,9 +1892,8 @@ private void createPrimaryColumnsToSecondaryTable( PropertyHolder propertyHolder, Join join) { // `incoming` will be an array of some sort of annotation - final Annotation[] joinColumnSource = (Annotation[]) incoming; + final var joinColumnSource = (Annotation[]) incoming; final AnnotatedJoinColumns annotatedJoinColumns; - if ( isEmpty( joinColumnSource ) ) { annotatedJoinColumns = createDefaultJoinColumn( propertyHolder ); } @@ -1940,7 +1922,7 @@ else if ( first instanceof JoinColumn ) { annotatedJoinColumns = createJoinColumns( propertyHolder, pkJoinColumns, joinColumns ); } - for ( AnnotatedJoinColumn joinColumn : annotatedJoinColumns.getJoinColumns() ) { + for ( var joinColumn : annotatedJoinColumns.getJoinColumns() ) { joinColumn.forceNotNull(); } bindJoinToPersistentClass( join, annotatedJoinColumns, context ); @@ -1965,7 +1947,10 @@ private AnnotatedJoinColumns createJoinColumns( PropertyHolder propertyHolder, PrimaryKeyJoinColumn[] primaryKeyJoinColumns, JoinColumn[] joinColumns) { - final int joinColumnCount = primaryKeyJoinColumns != null ? primaryKeyJoinColumns.length : joinColumns.length; + final int joinColumnCount = + primaryKeyJoinColumns != null + ? primaryKeyJoinColumns.length + : joinColumns.length; if ( joinColumnCount == 0 ) { return createDefaultJoinColumn( propertyHolder ); } @@ -1975,15 +1960,13 @@ private AnnotatedJoinColumns createJoinColumns( columns.setJoins( secondaryTables ); columns.setPropertyHolder( propertyHolder ); for ( int colIndex = 0; colIndex < joinColumnCount; colIndex++ ) { - final PrimaryKeyJoinColumn primaryKeyJoinColumn = primaryKeyJoinColumns != null - ? primaryKeyJoinColumns[colIndex] - : null; - final JoinColumn joinColumn = joinColumns != null - ? joinColumns[colIndex] - : null; buildInheritanceJoinColumn( - primaryKeyJoinColumn, - joinColumn, + primaryKeyJoinColumns != null + ? primaryKeyJoinColumns[colIndex] + : null, + joinColumns != null + ? joinColumns[colIndex] + : null, persistentClass.getIdentifier(), columns, context @@ -1993,7 +1976,10 @@ private AnnotatedJoinColumns createJoinColumns( } } - private void bindJoinToPersistentClass(Join join, AnnotatedJoinColumns joinColumns, MetadataBuildingContext context) { + private void bindJoinToPersistentClass( + Join join, + AnnotatedJoinColumns joinColumns, + MetadataBuildingContext context) { final var key = new DependantValue( context, join.getTable(), persistentClass.getIdentifier() ); join.setKey( key ); setForeignKeyNameIfDefined( join ); @@ -2007,7 +1993,7 @@ private void bindJoinToPersistentClass(Join join, AnnotatedJoinColumns joinColum private void setForeignKeyNameIfDefined(Join join) { final var key = (SimpleValue) join.getKey(); - final SecondaryTable jpaSecondaryTable = findMatchingSecondaryTable( join ); + final var jpaSecondaryTable = findMatchingSecondaryTable( join ); if ( jpaSecondaryTable != null ) { final boolean noConstraintByDefault = context.getBuildingOptions().isNoConstraintByDefault(); if ( jpaSecondaryTable.foreignKey().value() == ConstraintMode.NO_CONSTRAINT @@ -2024,14 +2010,13 @@ private void setForeignKeyNameIfDefined(Join join) { private SecondaryTable findMatchingSecondaryTable(Join join) { final String nameToMatch = join.getTable().getQuotedName(); - final SecondaryTable secondaryTable = annotatedClass.getDirectAnnotationUsage( SecondaryTable.class ); + final var secondaryTable = annotatedClass.getDirectAnnotationUsage( SecondaryTable.class ); if ( secondaryTable != null && nameToMatch.equals( secondaryTable.name() ) ) { return secondaryTable; } - final SecondaryTables secondaryTables = annotatedClass.getDirectAnnotationUsage( SecondaryTables.class ); + final var secondaryTables = annotatedClass.getDirectAnnotationUsage( SecondaryTables.class ); if ( secondaryTables != null ) { - final SecondaryTable[] nestedSecondaryTableList = secondaryTables.value(); - for ( SecondaryTable nestedSecondaryTable : nestedSecondaryTableList ) { + for ( var nestedSecondaryTable : secondaryTables.value() ) { if ( nestedSecondaryTable != null && nameToMatch.equals( nestedSecondaryTable.name() ) ) { return nestedSecondaryTable; } @@ -2041,15 +2026,14 @@ private SecondaryTable findMatchingSecondaryTable(Join join) { } private SecondaryRow findMatchingSecondaryRowAnnotation(String tableName) { - final SecondaryRow row = annotatedClass.getDirectAnnotationUsage( SecondaryRow.class ); + final var row = annotatedClass.getDirectAnnotationUsage( SecondaryRow.class ); if ( row != null && ( row.table().isBlank() || equalsTableName( tableName, row ) ) ) { return row; } else { - final SecondaryRows tables = annotatedClass.getDirectAnnotationUsage( SecondaryRows.class ); + final var tables = annotatedClass.getDirectAnnotationUsage( SecondaryRows.class ); if ( tables != null ) { - final SecondaryRow[] rowList = tables.value(); - for ( SecondaryRow current : rowList ) { + for ( var current : tables.value() ) { if ( equalsTableName( tableName, current ) ) { return current; } @@ -2060,16 +2044,17 @@ private SecondaryRow findMatchingSecondaryRowAnnotation(String tableName) { } private boolean equalsTableName(String physicalTableName, SecondaryRow secondaryRow) { - final Identifier logicalName = context.getMetadataCollector().getDatabase().toIdentifier( secondaryRow.table() ); + final var database = getDatabase(); + final Identifier logicalName = database.toIdentifier( secondaryRow.table() ); final Identifier secondaryRowPhysicalTableName = - context.getBuildingOptions().getPhysicalNamingStrategy() - .toPhysicalTableName( logicalName, EntityTableNamingStrategyHelper.jdbcEnvironment( context ) ); + getPhysicalNamingStrategy() + .toPhysicalTableName( logicalName, database.getJdbcEnvironment() ); return physicalTableName.equals( secondaryRowPhysicalTableName.render() ); } //Used for @*ToMany @JoinTable public Join addJoinTable(JoinTable joinTable, PropertyHolder holder, boolean noDelayInPkColumnCreation) { - final Join join = addJoin( + final var join = addJoin( holder, noDelayInPkColumnCreation, false, @@ -2079,7 +2064,7 @@ public Join addJoinTable(JoinTable joinTable, PropertyHolder holder, boolean noD joinTable.joinColumns(), joinTable.uniqueConstraints() ); - final Table table = join.getTable(); + final var table = join.getTable(); TableBinder.addTableCheck( table, joinTable.check() ); TableBinder.addTableComment( table, joinTable.comment() ); TableBinder.addTableOptions( table, joinTable.options() ); @@ -2087,7 +2072,7 @@ public Join addJoinTable(JoinTable joinTable, PropertyHolder holder, boolean noD } public Join addSecondaryTable(SecondaryTable secondaryTable, PropertyHolder holder, boolean noDelayInPkColumnCreation) { - final Join join = addJoin( + final var join = addJoin( holder, noDelayInPkColumnCreation, true, @@ -2097,7 +2082,7 @@ public Join addSecondaryTable(SecondaryTable secondaryTable, PropertyHolder hold secondaryTable.pkJoinColumns(), secondaryTable.uniqueConstraints() ); - final Table table = join.getTable(); + final var table = join.getTable(); new IndexBinder( context ).bindIndexes( table, secondaryTable.indexes() ); TableBinder.addTableCheck( table, secondaryTable.check() ); TableBinder.addTableComment( table, secondaryTable.comment() ); @@ -2114,7 +2099,7 @@ private Join addJoin( String catalog, Object joinColumns, UniqueConstraint[] uniqueConstraints) { - final QualifiedTableName logicalName = logicalTableName( name, schema, catalog ); + final var logicalName = logicalTableName( name, schema, catalog ); return createJoin( propertyHolder, noDelayInPkColumnCreation, @@ -2136,8 +2121,7 @@ private QualifiedTableName logicalTableName(String name, String schema, String c return new QualifiedTableName( toIdentifier( catalog ), toIdentifier( schema ), - getMetadataCollector().getDatabase().getJdbcEnvironment() - .getIdentifierHelper().toIdentifier( name ) + getDatabase().getJdbcEnvironment().getIdentifierHelper().toIdentifier( name ) ); } @@ -2186,7 +2170,7 @@ Join createJoin( private void handleSecondaryRowManagement(Join join) { final String tableName = join.getTable().getQuotedName(); - final SecondaryRow matchingRow = findMatchingSecondaryRowAnnotation( tableName ); + final var matchingRow = findMatchingSecondaryRowAnnotation( tableName ); if ( matchingRow != null ) { join.setInverse( !matchingRow.owned() ); join.setOptional( matchingRow.optional() ); @@ -2200,7 +2184,8 @@ private void handleSecondaryRowManagement(Join join) { private void processSecondaryTableCustomSql(Join join) { final String tableName = join.getTable().getQuotedName(); - final SQLInsert sqlInsert = resolveCustomSqlAnnotation( annotatedClass, SQLInsert.class, tableName ); + + final var sqlInsert = resolveCustomSqlAnnotation( annotatedClass, SQLInsert.class, tableName ); if ( sqlInsert != null ) { join.setCustomSQLInsert( sqlInsert.sql().trim(), @@ -2213,7 +2198,7 @@ private void processSecondaryTableCustomSql(Join join) { } } - final SQLUpdate sqlUpdate = resolveCustomSqlAnnotation( annotatedClass, SQLUpdate.class, tableName ); + final var sqlUpdate = resolveCustomSqlAnnotation( annotatedClass, SQLUpdate.class, tableName ); if ( sqlUpdate != null ) { join.setCustomSQLUpdate( sqlUpdate.sql().trim(), @@ -2226,7 +2211,7 @@ private void processSecondaryTableCustomSql(Join join) { } } - final SQLDelete sqlDelete = resolveCustomSqlAnnotation( annotatedClass, SQLDelete.class, tableName ); + final var sqlDelete = resolveCustomSqlAnnotation( annotatedClass, SQLDelete.class, tableName ); if ( sqlDelete != null ) { join.setCustomSQLDelete( sqlDelete.sql().trim(), @@ -2266,13 +2251,13 @@ public void setPropertyAccessType(AccessType propertyAccessType) { } public AccessType getPropertyAccessor(AnnotationTarget element) { - final AccessType accessType = getExplicitAccessType( element ); + final var accessType = getExplicitAccessType( element ); return accessType == null ? propertyAccessType : accessType; } private AccessType getExplicitAccessType(AnnotationTarget element) { if ( element != null ) { - final Access access = element.getAnnotationUsage( Access.class, modelsContext() ); + final var access = element.getAnnotationUsage( Access.class, modelsContext() ); if ( access != null ) { return AccessType.getAccessStrategy( access.value() ); } @@ -2302,11 +2287,11 @@ private void bindFiltersInHierarchy() { } private void bindFilters(AnnotationTarget element) { - final Filters filters = getOverridableAnnotation( element, Filters.class, context ); + final var filters = getOverridableAnnotation( element, Filters.class, context ); if ( filters != null ) { addAll( this.filters, filters.value() ); } - final Filter filter = element.getDirectAnnotationUsage( Filter.class ); + final var filter = element.getDirectAnnotationUsage( Filter.class ); if ( filter != null ) { this.filters.add( filter ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FetchOverrideSecondPass.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FetchOverrideSecondPass.java index b7a9814e833e..8bec283f6aeb 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FetchOverrideSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FetchOverrideSecondPass.java @@ -32,18 +32,16 @@ public FetchOverrideSecondPass( @Override public void doSecondPass(Map persistentClasses) throws MappingException { - final Class entityClassDetails = fetch.entity(); + final var collector = buildingContext.getMetadataCollector(); + final Class entityClass = fetch.entity(); final String attributeName = fetch.association(); - // throws MappingException in case the property does not exist - buildingContext.getMetadataCollector() - .getEntityBinding( entityClassDetails.getName() ) + collector.getEntityBinding( entityClass.getName() ) .getProperty( attributeName ); - - final FetchProfile profile = buildingContext.getMetadataCollector().getFetchProfile( fetchProfileName ); + final var profile = collector.getFetchProfile( fetchProfileName ); // we already know that the FetchProfile exists and is good to use profile.addFetch( new FetchProfile.Fetch( - entityClassDetails.getName(), + entityClass.getName(), attributeName, fetch.mode(), fetch.fetch() diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FetchSecondPass.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FetchSecondPass.java index ed02f4e0dcbb..f0bc57485d73 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FetchSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FetchSecondPass.java @@ -40,7 +40,7 @@ public FetchSecondPass( @Override public void doSecondPass(Map persistentClasses) throws MappingException { final String profileName = fetch.profile(); - final FetchProfile profile = buildingContext.getMetadataCollector().getFetchProfile( profileName ); + final var profile = buildingContext.getMetadataCollector().getFetchProfile( profileName ); if ( profile == null ) { throw new AnnotationException( "Property '" + qualify( propertyHolder.getPath(), propertyName ) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FilterDefBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FilterDefBinder.java index 728162b18fea..5700563a8364 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FilterDefBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/FilterDefBinder.java @@ -12,14 +12,11 @@ import org.hibernate.AnnotationException; import org.hibernate.MappingException; import org.hibernate.annotations.FilterDef; -import org.hibernate.annotations.ParamDef; -import org.hibernate.boot.spi.BootstrapContext; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.engine.spi.FilterDefinition; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.metamodel.mapping.JdbcMapping; import org.hibernate.models.spi.AnnotationTarget; -import org.hibernate.models.spi.ModelsContext; import org.hibernate.resource.beans.spi.ManagedBean; import org.hibernate.type.descriptor.java.JavaType; import org.hibernate.usertype.UserType; @@ -41,7 +38,7 @@ public class FilterDefBinder { private static final CoreMessageLogger LOG = messageLogger( FilterDefBinder.class ); public static void bindFilterDefs(AnnotationTarget annotatedElement, MetadataBuildingContext context) { - final ModelsContext modelsContext = context.getBootstrapContext().getModelsContext(); + final var modelsContext = context.getBootstrapContext().getModelsContext(); annotatedElement.forEachAnnotationUsage( FilterDef.class, modelsContext, (usage) -> { bindFilterDef( usage, context ); } ); @@ -55,7 +52,7 @@ public static void bindFilterDef(FilterDef filterDef, MetadataBuildingContext co final Map paramJdbcMappings; final Map>> parameterResolvers; - final ParamDef[] explicitParameters = filterDef.parameters(); + final var explicitParameters = filterDef.parameters(); if ( isEmpty( explicitParameters ) ) { paramJdbcMappings = emptyMap(); parameterResolvers = emptyMap(); @@ -63,7 +60,7 @@ public static void bindFilterDef(FilterDef filterDef, MetadataBuildingContext co else { paramJdbcMappings = new HashMap<>(); parameterResolvers = new HashMap<>(); - for ( ParamDef explicitParameter : explicitParameters ) { + for ( var explicitParameter : explicitParameters ) { final String parameterName = explicitParameter.name(); final Class typeClassDetails = explicitParameter.type(); final JdbcMapping jdbcMapping = resolveFilterParamType( typeClassDetails, context ); @@ -79,14 +76,15 @@ public static void bindFilterDef(FilterDef filterDef, MetadataBuildingContext co } paramJdbcMappings.put( parameterName, jdbcMapping ); - final Class resolverClass = explicitParameter.resolver(); + final var resolverClass = explicitParameter.resolver(); if ( !Supplier.class.equals( resolverClass ) ) { - parameterResolvers.put( explicitParameter.name(), resolveParamResolver( resolverClass, context ) ); + parameterResolvers.put( explicitParameter.name(), + resolveParamResolver( resolverClass, context ) ); } } } - final FilterDefinition filterDefinition = new FilterDefinition( + final var filterDefinition = new FilterDefinition( name, filterDef.defaultCondition(), filterDef.autoEnabled(), @@ -104,8 +102,9 @@ public static void bindFilterDef(FilterDef filterDef, MetadataBuildingContext co @SuppressWarnings({"rawtypes", "unchecked"}) private static ManagedBean> resolveParamResolver(Class resolverClass, MetadataBuildingContext context) { assert resolverClass != Supplier.class; - final BootstrapContext bootstrapContext = context.getBootstrapContext(); - return (ManagedBean>) bootstrapContext.getManagedBeanRegistry() + final var bootstrapContext = context.getBootstrapContext(); + return (ManagedBean>) + bootstrapContext.getManagedBeanRegistry() .getBean( resolverClass, bootstrapContext.getCustomTypeProducer() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/GeneratorAnnotationHelper.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/GeneratorAnnotationHelper.java index a373156c51ea..6f135e9d9f57 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/GeneratorAnnotationHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/GeneratorAnnotationHelper.java @@ -9,7 +9,6 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.IdGeneratorType; -import org.hibernate.annotations.Parameter; import org.hibernate.boot.model.IdentifierGeneratorDefinition; import org.hibernate.boot.model.relational.ExportableProducer; import org.hibernate.boot.models.HibernateAnnotations; @@ -36,7 +35,6 @@ import java.lang.annotation.Annotation; import java.util.HashMap; import java.util.Map; -import java.util.Objects; import java.util.Properties; import java.util.function.BiConsumer; import java.util.function.Consumer; @@ -64,7 +62,7 @@ public static A findLocalizedMatch( @Nullable Function nameExtractor, @Nullable String matchName, MetadataBuildingContext context) { - final ModelsContext modelsContext = context.getBootstrapContext().getModelsContext(); + final var modelsContext = context.getBootstrapContext().getModelsContext(); A possibleMatch = null; @@ -126,7 +124,7 @@ else if ( registrationName.equals( matchName ) ) { } // lastly, on the package - final ClassDetails packageInfo = locatePackageInfoDetails( idMember.getDeclaringType(), context ); + final var packageInfo = locatePackageInfoDetails( idMember.getDeclaringType(), context ); if ( packageInfo != null ) { for ( A generatorAnnotation: packageInfo.getRepeatedAnnotationUsages( generatorAnnotationType, modelsContext ) ) { @@ -151,8 +149,7 @@ else if ( registrationName.equals( matchName ) ) { } public static ClassDetails locatePackageInfoDetails(ClassDetails classDetails, MetadataBuildingContext buildingContext) { - final ModelsContext modelsContext = buildingContext.getBootstrapContext().getModelsContext(); - return locatePackageInfoDetails( classDetails, modelsContext ); + return locatePackageInfoDetails( classDetails, buildingContext.getBootstrapContext().getModelsContext() ); } public static ClassDetails locatePackageInfoDetails(ClassDetails classDetails, ModelsContext modelContext) { @@ -177,10 +174,10 @@ public static void handleSequenceGenerator( MemberDetails idMember, MetadataBuildingContext buildingContext) { idValue.setCustomIdGeneratorCreator( creationContext -> { - final SequenceStyleGenerator identifierGenerator = + final var sequenceStyleGenerator = instantiateGenerator( beanContainer( buildingContext ), SequenceStyleGenerator.class ); prepareForUse( - identifierGenerator, + sequenceStyleGenerator, generatorAnnotation, idMember, properties -> { @@ -195,10 +192,11 @@ else if ( nameFromGeneratedValue != null ) { }, generatorAnnotation == null ? null - : (a, properties) -> SequenceStyleGenerator.applyConfiguration( generatorAnnotation, properties::put ), + : (a, properties) -> + SequenceStyleGenerator.applyConfiguration( generatorAnnotation, properties::put ), creationContext ); - return identifierGenerator; + return sequenceStyleGenerator; } ); } @@ -209,11 +207,11 @@ public static void handleTableGenerator( MemberDetails idMember, MetadataBuildingContext buildingContext) { idValue.setCustomIdGeneratorCreator( creationContext -> { - final org.hibernate.id.enhanced.TableGenerator identifierGenerator = + final var tableGenerator = instantiateGenerator( beanContainer( buildingContext ), org.hibernate.id.enhanced.TableGenerator.class ); prepareForUse( - identifierGenerator, + tableGenerator, generatorAnnotation, idMember, properties -> { @@ -237,7 +235,7 @@ else if ( nameFromGeneratedValue != null ) { ), creationContext ); - return identifierGenerator; + return tableGenerator; } ); } @@ -246,7 +244,7 @@ public static void handleIdGeneratorType( SimpleValue idValue, MemberDetails idMember, MetadataBuildingContext buildingContext) { - final IdGeneratorType markerAnnotation = + final var markerAnnotation = generatorAnnotation.annotationType().getAnnotation( IdGeneratorType.class ); idValue.setCustomIdGeneratorCreator( creationContext -> { final Generator identifierGenerator = @@ -282,11 +280,11 @@ public static void prepareForUse( GeneratorCreationContext creationContext) { if ( generator instanceof AnnotationBasedGenerator ) { @SuppressWarnings("unchecked") - final AnnotationBasedGenerator generation = (AnnotationBasedGenerator) generator; + final var generation = (AnnotationBasedGenerator) generator; generation.initialize( annotation, idMember.toJavaMember(), creationContext ); } if ( generator instanceof Configurable configurable ) { - final Properties properties = new Properties(); + final var properties = new Properties(); if ( configBaseline != null ) { configBaseline.accept( properties ); } @@ -317,7 +315,7 @@ public static void handleUuidStrategy( MemberDetails idMember, ClassDetails entityClass, MetadataBuildingContext context) { - final org.hibernate.annotations.UuidGenerator generatorConfig = findLocalizedMatch( + final var generatorConfig = findLocalizedMatch( HibernateAnnotations.UUID_GENERATOR, idMember, entityClass, @@ -361,12 +359,14 @@ public static void handleGenericGenerator( } private static String determineStrategyName(GenericGenerator generatorConfig) { - final Class type = generatorConfig.type(); - return !Objects.equals( type, Generator.class ) ? type.getName() : generatorConfig.strategy(); + final var generatorClass = generatorConfig.type(); + return Generator.class.equals( generatorClass ) + ? generatorConfig.strategy() + : generatorClass.getName(); } private static void applyAnnotationParameters(GenericGenerator generatorConfig, Map configuration) { - for ( Parameter parameter : generatorConfig.parameters() ) { + for ( var parameter : generatorConfig.parameters() ) { configuration.put( parameter.name(), parameter.value() ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/GeneratorBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/GeneratorBinder.java index d191ec59b15e..7819dfc17884 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/GeneratorBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/GeneratorBinder.java @@ -19,7 +19,6 @@ import org.hibernate.boot.model.relational.ExportableProducer; import org.hibernate.boot.model.source.internal.hbm.MappingDocument; import org.hibernate.boot.models.spi.GlobalRegistrar; -import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.PropertyData; import org.hibernate.engine.config.spi.ConfigurationService; @@ -43,7 +42,6 @@ import org.hibernate.mapping.Value; import org.hibernate.models.spi.AnnotationTarget; import org.hibernate.models.spi.MemberDetails; -import org.hibernate.models.spi.ModelsContext; import org.hibernate.resource.beans.container.spi.BeanContainer; import org.hibernate.resource.beans.internal.Helper; @@ -51,7 +49,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.util.HashMap; -import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; @@ -116,13 +113,13 @@ public static void makeIdGenerator( } if ( generatorName.isEmpty() ) { - final GeneratedValue generatedValue = idAttributeMember.getDirectAnnotationUsage( GeneratedValue.class ); + final var generatedValue = idAttributeMember.getDirectAnnotationUsage( GeneratedValue.class ); if ( generatedValue != null ) { // The mapping used @GeneratedValue but specified no name. This is a special case added in JPA 3.2. // Look for a matching "implied generator" based on the GenerationType - final GenerationType strategy = generatedValue.strategy(); + final var strategy = generatedValue.strategy(); final String strategyGeneratorClassName = correspondingGeneratorName( strategy ); - final IdentifierGeneratorDefinition impliedGenerator = + final var impliedGenerator = determineImpliedGenerator( strategy, strategyGeneratorClassName, localGenerators ); if ( impliedGenerator != null ) { configuration.putAll( impliedGenerator.getParameters() ); @@ -152,10 +149,9 @@ private static IdentifierGeneratorDefinition determineImpliedGenerator( } if ( localGenerators.size() == 1 ) { - final IdentifierGeneratorDefinition generatorDefinition = - localGenerators.values().iterator().next(); - // NOTE : a little bit of a special rule here for the case of just one - - // we consider it a match, based on strategy, if the strategy is AUTO or matches... + final var generatorDefinition = localGenerators.values().iterator().next(); + // NOTE: a little bit of a special rule here for the case of just one - + // we consider it a match, based on strategy, if the strategy is AUTO or matches if ( strategy == AUTO || isImpliedGenerator( strategy, strategyGeneratorClassName, generatorDefinition ) ) { return generatorDefinition; @@ -163,7 +159,7 @@ private static IdentifierGeneratorDefinition determineImpliedGenerator( } IdentifierGeneratorDefinition matching = null; - for ( IdentifierGeneratorDefinition localGenerator : localGenerators.values() ) { + for ( var localGenerator : localGenerators.values() ) { if ( isImpliedGenerator( strategy, strategyGeneratorClassName, localGenerator ) ) { if ( matching != null ) { // we found multiple matching generators @@ -201,7 +197,7 @@ private static String determineStrategy( Map configuration) { if ( !generatorName.isEmpty() ) { //we have a named generator - final IdentifierGeneratorDefinition definition = + final var definition = makeIdentifierGeneratorDefinition( generatorName, idAttributeMember, localGenerators, context ); if ( definition == null ) { throw new AnnotationException( "No id generator was declared with the name '" + generatorName @@ -230,19 +226,20 @@ private static IdentifierGeneratorDefinition makeIdentifierGeneratorDefinition( Map localGenerators, MetadataBuildingContext buildingContext) { if ( localGenerators != null ) { - final IdentifierGeneratorDefinition result = localGenerators.get( name ); + final var result = localGenerators.get( name ); if ( result != null ) { return result; } } - final IdentifierGeneratorDefinition globalDefinition = - buildingContext.getMetadataCollector().getIdentifierGenerator( name ); + final var globalDefinition = + buildingContext.getMetadataCollector() + .getIdentifierGenerator( name ); if ( globalDefinition != null ) { return globalDefinition; } else { - final GeneratedValue generatedValue = idAttributeMember.getDirectAnnotationUsage( GeneratedValue.class ); + final var generatedValue = idAttributeMember.getDirectAnnotationUsage( GeneratedValue.class ); if ( generatedValue == null ) { throw new AssertionFailure( "No @GeneratedValue annotation" ); } @@ -257,7 +254,7 @@ private static IdentifierGeneratorDefinition makeIdentifierGeneratorDefinition( private static GenerationType interpretGenerationType(GeneratedValue generatedValueAnn) { // todo (jpa32) : when can this ever be null? - final GenerationType strategy = generatedValueAnn.strategy(); + final var strategy = generatedValueAnn.strategy(); return strategy == null ? AUTO : strategy; } @@ -265,24 +262,20 @@ public static void visitIdGeneratorDefinitions( AnnotationTarget annotatedElement, Consumer consumer, MetadataBuildingContext buildingContext) { - final ModelsContext modelsContext = buildingContext.getBootstrapContext().getModelsContext(); - + final var modelsContext = buildingContext.getBootstrapContext().getModelsContext(); annotatedElement.forEachAnnotationUsage( TableGenerator.class, modelsContext, usage -> consumer.accept( buildTableIdGenerator( usage ) ) ); - annotatedElement.forEachAnnotationUsage( SequenceGenerator.class, modelsContext, usage -> consumer.accept( buildSequenceIdGenerator( usage ) ) ); - annotatedElement.forEachAnnotationUsage( GenericGenerator.class, modelsContext, usage -> consumer.accept( buildIdGenerator( usage ) ) ); - } public static void registerGlobalGenerators( AnnotationTarget annotatedElement, MetadataBuildingContext context) { if ( context.getBootstrapContext().getJpaCompliance().isGlobalGeneratorScopeEnabled() ) { - final InFlightMetadataCollector metadataCollector = context.getMetadataCollector(); + final var metadataCollector = context.getMetadataCollector(); visitIdGeneratorDefinitions( annotatedElement, definition -> { @@ -296,10 +289,9 @@ public static void registerGlobalGenerators( } private static IdentifierGeneratorDefinition buildIdGenerator(GenericGenerator generatorAnnotation) { - final IdentifierGeneratorDefinition.Builder definitionBuilder = - new IdentifierGeneratorDefinition.Builder(); + final var definitionBuilder = new IdentifierGeneratorDefinition.Builder(); definitionBuilder.setName( generatorAnnotation.name() ); - final Class generatorClass = generatorAnnotation.type(); + final var generatorClass = generatorAnnotation.type(); final String strategy = generatorClass.equals( Generator.class ) ? generatorAnnotation.strategy() @@ -315,7 +307,7 @@ private static IdentifierGeneratorDefinition buildIdGenerator(GenericGenerator g } private static IdentifierGeneratorDefinition buildSequenceIdGenerator(SequenceGenerator generatorAnnotation) { - final IdentifierGeneratorDefinition.Builder definitionBuilder = new IdentifierGeneratorDefinition.Builder(); + final var definitionBuilder = new IdentifierGeneratorDefinition.Builder(); interpretSequenceGenerator( generatorAnnotation, definitionBuilder ); if ( LOG.isTraceEnabled() ) { LOG.tracev( "Added sequence generator with name: {0}", definitionBuilder.getName() ); @@ -324,7 +316,7 @@ private static IdentifierGeneratorDefinition buildSequenceIdGenerator(SequenceGe } private static IdentifierGeneratorDefinition buildTableIdGenerator(TableGenerator generatorAnnotation) { - final IdentifierGeneratorDefinition.Builder definitionBuilder = new IdentifierGeneratorDefinition.Builder(); + final var definitionBuilder = new IdentifierGeneratorDefinition.Builder(); interpretTableGenerator( generatorAnnotation, definitionBuilder ); if ( LOG.isTraceEnabled() ) { LOG.tracev( "Added sequence generator with name: {0}", definitionBuilder.getName() ); @@ -357,10 +349,10 @@ private static GeneratorCreator generatorCreator( Value value, Annotation annotation, BeanContainer beanContainer) { - final Class annotationType = annotation.annotationType(); - final ValueGenerationType generatorAnnotation = annotationType.getAnnotation( ValueGenerationType.class ); + final var annotationType = annotation.annotationType(); + final var generatorAnnotation = annotationType.getAnnotation( ValueGenerationType.class ); assert generatorAnnotation != null; - final Class generatorClass = generatorAnnotation.generatedBy(); + final var generatorClass = generatorAnnotation.generatedBy(); checkGeneratorClass( generatorClass ); checkGeneratorInterfaces( generatorClass ); return creationContext -> { @@ -409,10 +401,10 @@ private static GeneratorCreator identifierGeneratorCreator( Annotation annotation, SimpleValue identifierValue, BeanContainer beanContainer) { - final Class annotationType = annotation.annotationType(); - final IdGeneratorType idGeneratorAnnotation = annotationType.getAnnotation( IdGeneratorType.class ); + final var annotationType = annotation.annotationType(); + final var idGeneratorAnnotation = annotationType.getAnnotation( IdGeneratorType.class ); assert idGeneratorAnnotation != null; - final Class generatorClass = idGeneratorAnnotation.value(); + final var generatorClass = idGeneratorAnnotation.value(); checkGeneratorClass( generatorClass ); return creationContext -> { final Generator generator = @@ -593,7 +585,7 @@ public static void callInitialize( // a programming error of the generation type developer and thus should show up during testing, we don't // check this explicitly; If required, this could be done e.g. using ClassMate @SuppressWarnings("unchecked") - final AnnotationBasedGenerator generation = (AnnotationBasedGenerator) generator; + final var generation = (AnnotationBasedGenerator) generator; generation.initialize( annotation, memberDetails.toJavaMember(), creationContext ); } } @@ -661,9 +653,8 @@ private static void createIdGenerator( PersistentClass persistentClass, MetadataBuildingContext context) { // NOTE: `generatedValue` is never null here - final GeneratedValue generatedValue = castNonNull( idMember.getDirectAnnotationUsage( GeneratedValue.class ) ); - - final InFlightMetadataCollector metadataCollector = context.getMetadataCollector(); + final var generatedValue = castNonNull( idMember.getDirectAnnotationUsage( GeneratedValue.class ) ); + final var metadataCollector = context.getMetadataCollector(); if ( isGlobalGeneratorNameGlobal( context ) ) { // process and register any generators defined on the member. // according to JPA these are also global. @@ -726,7 +717,7 @@ public static void makeIdGenerator( if ( definition != null ) { // see if the specified generator name matches a registered - final IdentifierGeneratorDefinition generatorDef = + final var generatorDef = sourceDocument.getMetadataCollector() .getIdentifierGenerator( definition.getName() ); final Map configuration = new HashMap<>(); @@ -799,12 +790,10 @@ static void createIdGeneratorsFromGeneratorAnnotations( PropertyData inferredData, SimpleValue idValue, MetadataBuildingContext buildingContext) { - final ModelsContext modelsContext = buildingContext.getBootstrapContext().getModelsContext(); - final MemberDetails idAttributeMember = inferredData.getAttributeMember(); - final List idGeneratorAnnotations = - idAttributeMember.getMetaAnnotated( IdGeneratorType.class, modelsContext ); - final List generatorAnnotations = - idAttributeMember.getMetaAnnotated( ValueGenerationType.class, modelsContext ); + final var modelsContext = buildingContext.getBootstrapContext().getModelsContext(); + final var idMemberDetails = inferredData.getAttributeMember(); + final var idGeneratorAnnotations = idMemberDetails.getMetaAnnotated( IdGeneratorType.class, modelsContext ); + final var generatorAnnotations = idMemberDetails.getMetaAnnotated( ValueGenerationType.class, modelsContext ); // Since these collections may contain Proxies created by common-annotations module we cannot reliably use simple remove/removeAll // collection methods as those proxies do not implement hashcode/equals and even a simple `a.equals(a)` will return `false`. // Instead, we will check the annotation types, since generator annotations should not be "repeatable" we should have only @@ -823,14 +812,14 @@ static void createIdGeneratorsFromGeneratorAnnotations( } if ( !idGeneratorAnnotations.isEmpty() ) { idValue.setCustomIdGeneratorCreator( identifierGeneratorCreator( - idAttributeMember, + idMemberDetails, idGeneratorAnnotations.get(0), idValue, beanContainer( buildingContext ) ) ); } else if ( !generatorAnnotations.isEmpty() ) { -// idValue.setCustomGeneratorCreator( generatorCreator( idAttributeMember, generatorAnnotation ) ); +// idValue.setCustomGeneratorCreator( generatorCreator( idMemberDetails, generatorAnnotation ) ); throw new AnnotationException( String.format( Locale.ROOT, "Identifier attribute '%s' is annotated '%s' which is not an '@IdGeneratorType'", @@ -838,8 +827,8 @@ else if ( !generatorAnnotations.isEmpty() ) { generatorAnnotations.get(0).annotationType().getName() ) ); } - else if ( idAttributeMember.hasDirectAnnotationUsage( GeneratedValue.class ) ) { - createIdGenerator( idAttributeMember, idValue, propertyHolder.getPersistentClass(), buildingContext ); + else if ( idMemberDetails.hasDirectAnnotationUsage( GeneratedValue.class ) ) { + createIdGenerator( idMemberDetails, idValue, propertyHolder.getPersistentClass(), buildingContext ); } } @@ -850,9 +839,9 @@ else if ( idAttributeMember.hasDirectAnnotationUsage( GeneratedValue.class ) ) { static GeneratorCreator createValueGeneratorFromAnnotations( PropertyHolder holder, String propertyName, Value value, MemberDetails property, MetadataBuildingContext buildingContext) { - final ModelsContext modelsContext = buildingContext.getBootstrapContext().getModelsContext(); - final List generatorAnnotations = - property.getMetaAnnotated( ValueGenerationType.class, modelsContext ); + final var generatorAnnotations = + property.getMetaAnnotated( ValueGenerationType.class, + buildingContext.getBootstrapContext().getModelsContext() ); return switch ( generatorAnnotations.size() ) { case 0 -> null; case 1 -> generatorCreator( property, value, generatorAnnotations.get(0), beanContainer( buildingContext ) ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/GeneratorParameters.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/GeneratorParameters.java index c8fd77a4cad3..8a9990b2104d 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/GeneratorParameters.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/GeneratorParameters.java @@ -12,7 +12,7 @@ import org.hibernate.Internal; import org.hibernate.boot.model.IdentifierGeneratorDefinition; import org.hibernate.boot.spi.MetadataBuildingContext; -import org.hibernate.cfg.AvailableSettings; +import org.hibernate.cfg.MappingSettings; import org.hibernate.dialect.Dialect; import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.engine.config.spi.StandardConverters; @@ -31,10 +31,10 @@ import jakarta.persistence.SequenceGenerator; import jakarta.persistence.TableGenerator; -import jakarta.persistence.UniqueConstraint; import org.hibernate.mapping.Value; import static org.hibernate.cfg.MappingSettings.ID_DB_STRUCTURE_NAMING_STRATEGY; +import static org.hibernate.cfg.MappingSettings.PREFERRED_POOLED_OPTIMIZER; import static org.hibernate.id.IdentifierGenerator.CONTRIBUTOR_NAME; import static org.hibernate.id.IdentifierGenerator.ENTITY_NAME; import static org.hibernate.id.IdentifierGenerator.JPA_ENTITY_NAME; @@ -71,7 +71,7 @@ public static Properties collectParameters( RootClass rootClass, Map configuration, ConfigurationService configService) { - final Properties params = new Properties(); + final var params = new Properties(); collectParameters( identifierValue, dialect, rootClass, params::put, configService ); if ( configuration != null ) { params.putAll( configuration ); @@ -94,7 +94,7 @@ public static void collectParameters( public static int fallbackAllocationSize(Annotation generatorAnnotation, MetadataBuildingContext buildingContext) { if ( generatorAnnotation == null ) { - final ConfigurationService configService = buildingContext.getBootstrapContext().getConfigurationService(); + final var configService = buildingContext.getBootstrapContext().getConfigurationService(); final String idNamingStrategy = configService.getSetting( ID_DB_STRUCTURE_NAMING_STRATEGY, StandardConverters.STRING ); if ( LegacyNamingStrategy.STRATEGY_NAME.equals( idNamingStrategy ) || LegacyNamingStrategy.class.getName().equals( idNamingStrategy ) @@ -150,16 +150,16 @@ static void collectBaselineProperties( identifierValue.getBuildingContext().getCurrentContributorName() ); final Map settings = configService.getSettings(); - if ( settings.containsKey( AvailableSettings.PREFERRED_POOLED_OPTIMIZER ) ) { + if ( settings.containsKey( PREFERRED_POOLED_OPTIMIZER ) ) { parameterCollector.accept( - AvailableSettings.PREFERRED_POOLED_OPTIMIZER, - (String) settings.get( AvailableSettings.PREFERRED_POOLED_OPTIMIZER ) + PREFERRED_POOLED_OPTIMIZER, + (String) settings.get( PREFERRED_POOLED_OPTIMIZER ) ); } } public static String identityTablesString(Dialect dialect, RootClass rootClass) { - final StringBuilder tables = new StringBuilder(); + final var tables = new StringBuilder(); for ( Table table : rootClass.getIdentityTables() ) { tables.append( table.getQuotedName( dialect ) ); if ( !tables.isEmpty() ) { @@ -171,7 +171,7 @@ public static String identityTablesString(Dialect dialect, RootClass rootClass) public static int defaultIncrement(ConfigurationService configService) { final String idNamingStrategy = - configService.getSetting( AvailableSettings.ID_DB_STRUCTURE_NAMING_STRATEGY, + configService.getSetting( MappingSettings.ID_DB_STRUCTURE_NAMING_STRATEGY, StandardConverters.STRING, null ); if ( LegacyNamingStrategy.STRATEGY_NAME.equals( idNamingStrategy ) || LegacyNamingStrategy.class.getName().equals( idNamingStrategy ) @@ -252,8 +252,7 @@ public static void interpretTableGenerator( ); // TODO : implement unique-constraint support - final UniqueConstraint[] uniqueConstraints = tableGeneratorAnnotation.uniqueConstraints(); - if ( isNotEmpty( uniqueConstraints ) ) { + if ( isNotEmpty( tableGeneratorAnnotation.uniqueConstraints() ) ) { LOG.ignoringTableGeneratorConstraints( tableGeneratorAnnotation.name() ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagBinder.java index 93bfe24d656f..3a35031fd874 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagBinder.java @@ -50,7 +50,7 @@ protected Collection createCollection(PersistentClass owner) { protected boolean bindStarToManySecondPass(Map persistentClasses) { boolean result = super.bindStarToManySecondPass( persistentClasses ); - final CollectionId collectionIdAnn = property.getDirectAnnotationUsage( CollectionId.class ); + final var collectionIdAnn = property.getDirectAnnotationUsage( CollectionId.class ); if ( collectionIdAnn == null ) { throw new MappingException( "idbag mapping missing '@CollectionId' annotation" ); } @@ -67,7 +67,7 @@ protected boolean bindStarToManySecondPass(Map persiste "id" ); - final AnnotatedColumns idColumns = AnnotatedColumn.buildColumnsFromAnnotations( + final var idColumns = AnnotatedColumn.buildColumnsFromAnnotations( new Column[]{collectionIdAnn.column()}, // null, null, @@ -79,12 +79,11 @@ protected boolean bindStarToManySecondPass(Map persiste ); //we need to make sure all id columns must be not-null. - for ( AnnotatedColumn idColumn : idColumns.getColumns() ) { + for ( var idColumn : idColumns.getColumns() ) { idColumn.setNullable( false ); } - final BasicValueBinder valueBinder = - new BasicValueBinder( BasicValueBinder.Kind.COLLECTION_ID, buildingContext ); + final var valueBinder = new BasicValueBinder( BasicValueBinder.Kind.COLLECTION_ID, buildingContext ); final Table table = collection.getCollectionTable(); valueBinder.setTable( table ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagIdGeneratorResolverSecondPass.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagIdGeneratorResolverSecondPass.java index 3a560330f9ec..ad19c144e355 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagIdGeneratorResolverSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagIdGeneratorResolverSecondPass.java @@ -12,12 +12,7 @@ import org.hibernate.boot.models.JpaAnnotations; import org.hibernate.boot.models.annotations.internal.SequenceGeneratorJpaAnnotation; import org.hibernate.boot.models.annotations.internal.TableGeneratorJpaAnnotation; -import org.hibernate.boot.models.spi.GlobalRegistrations; -import org.hibernate.boot.models.spi.SequenceGeneratorRegistration; -import org.hibernate.boot.models.spi.TableGeneratorRegistration; -import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.boot.spi.MetadataBuildingContext; -import org.hibernate.generator.Generator; import org.hibernate.id.PersistentIdentifierGenerator; import org.hibernate.mapping.IdentifierBag; import org.hibernate.mapping.PersistentClass; @@ -69,8 +64,7 @@ public IdBagIdGeneratorResolverSecondPass( @Override public void doSecondPass(Map idGeneratorDefinitionMap) throws MappingException { - final GeneratedValue generatedValue = idBagMember.getDirectAnnotationUsage( GeneratedValue.class ); - switch ( generatedValue.strategy() ) { + switch ( idBagMember.getDirectAnnotationUsage( GeneratedValue.class ).strategy() ) { case UUID -> handleUuidStrategy( idValue, idBagMember, @@ -107,10 +101,9 @@ private void handleTableStrategy( SimpleValue idValue, MemberDetails idBagMember, MetadataBuildingContext buildingContext) { - final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector(); - - final TableGeneratorRegistration globalTableGenerator = - metadataCollector.getGlobalRegistrations() + final var collector = buildingContext.getMetadataCollector(); + final var globalTableGenerator = + collector.getGlobalRegistrations() .getTableGeneratorRegistrations() .get( generatorName ); if ( globalTableGenerator != null ) { @@ -121,30 +114,30 @@ private void handleTableStrategy( idBagMember, buildingContext ); - return; } - - final TableGenerator localizedTableMatch = findLocalizedMatch( - JpaAnnotations.TABLE_GENERATOR, - idBagMember, - buildingContext.getMetadataCollector().getClassDetailsRegistry() - .getClassDetails( entityMapping.getClassName() ), - TableGenerator::name, - generatorName, - buildingContext - ); - if ( localizedTableMatch != null ) { - handleTableGenerator( generatorName, localizedTableMatch, idValue, idBagMember, buildingContext ); - return; + else { + final var localizedTableMatch = findLocalizedMatch( + JpaAnnotations.TABLE_GENERATOR, + idBagMember, + collector.getClassDetailsRegistry() + .getClassDetails( entityMapping.getClassName() ), + TableGenerator::name, + generatorName, + buildingContext + ); + if ( localizedTableMatch != null ) { + handleTableGenerator( generatorName, localizedTableMatch, idValue, idBagMember, buildingContext ); + } + else { + handleTableGenerator( + generatorName, + new TableGeneratorJpaAnnotation( buildingContext.getBootstrapContext().getModelsContext() ), + idValue, + idBagMember, + buildingContext + ); + } } - - handleTableGenerator( - generatorName, - new TableGeneratorJpaAnnotation( buildingContext.getBootstrapContext().getModelsContext() ), - idValue, - idBagMember, - buildingContext - ); } private void handleSequenceStrategy( @@ -152,10 +145,9 @@ private void handleSequenceStrategy( SimpleValue idValue, MemberDetails idBagMember, MetadataBuildingContext buildingContext) { - final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector(); - - final SequenceGeneratorRegistration globalSequenceGenerator = - metadataCollector.getGlobalRegistrations() + final var collector = buildingContext.getMetadataCollector(); + final var globalSequenceGenerator = + collector.getGlobalRegistrations() .getSequenceGeneratorRegistrations() .get( generatorName ); if ( globalSequenceGenerator != null ) { @@ -166,30 +158,30 @@ private void handleSequenceStrategy( idBagMember, buildingContext ); - return; } - - final SequenceGenerator localizedSequencedMatch = findLocalizedMatch( - JpaAnnotations.SEQUENCE_GENERATOR, - idBagMember, - buildingContext.getMetadataCollector().getClassDetailsRegistry() - .getClassDetails( entityMapping.getClassName() ), - SequenceGenerator::name, - generatorName, - buildingContext - ); - if ( localizedSequencedMatch != null ) { - handleSequenceGenerator( generatorName, localizedSequencedMatch, idValue, idBagMember, buildingContext ); - return; + else { + final var localizedSequencedMatch = findLocalizedMatch( + JpaAnnotations.SEQUENCE_GENERATOR, + idBagMember, + collector.getClassDetailsRegistry() + .getClassDetails( entityMapping.getClassName() ), + SequenceGenerator::name, + generatorName, + buildingContext + ); + if ( localizedSequencedMatch != null ) { + handleSequenceGenerator( generatorName, localizedSequencedMatch, idValue, idBagMember, buildingContext ); + } + else { + handleSequenceGenerator( + generatorName, + new SequenceGeneratorJpaAnnotation( buildingContext.getBootstrapContext().getModelsContext() ), + idValue, + idBagMember, + buildingContext + ); + } } - - handleSequenceGenerator( - generatorName, - new SequenceGeneratorJpaAnnotation( buildingContext.getBootstrapContext().getModelsContext() ), - idValue, - idBagMember, - buildingContext - ); } private void handleAutoStrategy( @@ -197,10 +189,9 @@ private void handleAutoStrategy( SimpleValue idValue, MemberDetails idBagMember, MetadataBuildingContext buildingContext) { - final GlobalRegistrations globalRegistrations = - buildingContext.getMetadataCollector().getGlobalRegistrations(); + final var globalRegistrations = buildingContext.getMetadataCollector().getGlobalRegistrations(); - final SequenceGeneratorRegistration globalSequenceGenerator = + final var globalSequenceGenerator = globalRegistrations.getSequenceGeneratorRegistrations().get( generatorName ); if ( globalSequenceGenerator != null ) { handleSequenceGenerator( @@ -213,7 +204,7 @@ private void handleAutoStrategy( return; } - final TableGeneratorRegistration globalTableGenerator = + final var globalTableGenerator = globalRegistrations.getTableGeneratorRegistrations().get( generatorName ); if ( globalTableGenerator != null ) { handleTableGenerator( @@ -227,7 +218,7 @@ private void handleAutoStrategy( } - final Class legacyNamedGenerator = mapLegacyNamedGenerator( generatorName, idValue ); + final var legacyNamedGenerator = mapLegacyNamedGenerator( generatorName, idValue ); if ( legacyNamedGenerator != null ) { //generator settings if ( idValue.getColumnSpan() == 1 ) { @@ -242,7 +233,7 @@ private void handleAutoStrategy( return; } - final SequenceGenerator localizedSequencedMatch = findLocalizedMatch( + final var localizedSequencedMatch = findLocalizedMatch( JpaAnnotations.SEQUENCE_GENERATOR, idBagMember, buildingContext.getMetadataCollector().getClassDetailsRegistry() @@ -256,7 +247,7 @@ private void handleAutoStrategy( return; } - final TableGenerator localizedTableMatch = findLocalizedMatch( + final var localizedTableMatch = findLocalizedMatch( JpaAnnotations.TABLE_GENERATOR, idBagMember, buildingContext.getMetadataCollector().getClassDetailsRegistry() diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdGeneratorResolverSecondPass.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdGeneratorResolverSecondPass.java index d3528263136e..6281fbc4c1e9 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdGeneratorResolverSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdGeneratorResolverSecondPass.java @@ -13,12 +13,7 @@ import org.hibernate.boot.models.HibernateAnnotations; import org.hibernate.boot.models.JpaAnnotations; import org.hibernate.boot.models.annotations.internal.GenericGeneratorAnnotation; -import org.hibernate.boot.models.spi.GenericGeneratorRegistration; -import org.hibernate.boot.models.spi.GlobalRegistrations; -import org.hibernate.boot.models.spi.SequenceGeneratorRegistration; -import org.hibernate.boot.models.spi.TableGeneratorRegistration; import org.hibernate.boot.spi.MetadataBuildingContext; -import org.hibernate.generator.Generator; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.SimpleValue; import org.hibernate.models.spi.MemberDetails; @@ -56,7 +51,7 @@ public IdGeneratorResolverSecondPass( protected void handleUnnamedSequenceGenerator() { // todo (7.0) : null or entityMapping.getJpaEntityName() for "name from GeneratedValue"? - final SequenceGenerator localizedMatch = findLocalizedMatch( + final var localizedMatch = findLocalizedMatch( JpaAnnotations.SEQUENCE_GENERATOR, idMember, buildingContext.getMetadataCollector().getClassDetailsRegistry() @@ -67,20 +62,20 @@ protected void handleUnnamedSequenceGenerator() { ); if ( localizedMatch != null ) { handleSequenceGenerator( null, localizedMatch, idValue, idMember, buildingContext ); - return; } - - handleSequenceGenerator( null, null, idValue, idMember, buildingContext ); + else { + handleSequenceGenerator( null, null, idValue, idMember, buildingContext ); + } } @Override protected void handleNamedSequenceGenerator() { final String generator = generatedValue.generator(); - - final SequenceGenerator localizedMatch = findLocalizedMatch( + final var collector = buildingContext.getMetadataCollector(); + final var localizedMatch = findLocalizedMatch( JpaAnnotations.SEQUENCE_GENERATOR, idMember, - buildingContext.getMetadataCollector().getClassDetailsRegistry() + collector.getClassDetailsRegistry() .getClassDetails( entityMapping.getClassName() ), SequenceGenerator::name, generator, @@ -88,34 +83,30 @@ protected void handleNamedSequenceGenerator() { ); if ( localizedMatch != null ) { handleSequenceGenerator( generator, localizedMatch, idValue, idMember, buildingContext ); - return; } - - // look for the matching global registration, if one. - final SequenceGeneratorRegistration globalMatch = - buildingContext.getMetadataCollector() - .getGlobalRegistrations() - .getSequenceGeneratorRegistrations() - .get( generator ); - if ( globalMatch != null ) { - handleSequenceGenerator( generator, globalMatch.configuration(), idValue, idMember, buildingContext ); - return; + else { + // look for the matching global registration, if one. + final var globalMatch = + collector.getGlobalRegistrations() + .getSequenceGeneratorRegistrations() + .get( generator ); + if ( globalMatch != null ) { + handleSequenceGenerator( generator, globalMatch.configuration(), idValue, idMember, buildingContext ); + } + else { + validateSequenceGeneration(); + handleSequenceGenerator( generator, null, idValue, idMember, buildingContext ); + } } - - validateSequenceGeneration(); - - handleSequenceGenerator( generator, null, idValue, idMember, buildingContext ); } private void validateSequenceGeneration() { // basically, make sure there is neither a TableGenerator nor GenericGenerator with this name - final GlobalRegistrations globalRegistrations = - buildingContext.getMetadataCollector().getGlobalRegistrations(); + final var globalRegistrations = buildingContext.getMetadataCollector().getGlobalRegistrations(); final String generator = generatedValue.generator(); - final TableGeneratorRegistration globalTableMatch = - globalRegistrations.getTableGeneratorRegistrations().get( generator ); + final var globalTableMatch = globalRegistrations.getTableGeneratorRegistrations().get( generator ); if ( globalTableMatch != null ) { throw new MappingException( String.format( @@ -127,8 +118,7 @@ private void validateSequenceGeneration() { ); } - final GenericGeneratorRegistration globalGenericMatch = - globalRegistrations.getGenericGeneratorRegistrations().get( generator ); + final var globalGenericMatch = globalRegistrations.getGenericGeneratorRegistrations().get( generator ); if ( globalGenericMatch != null ) { throw new MappingException( String.format( @@ -149,7 +139,7 @@ private void validateSequenceGeneration() { protected void handleUnnamedTableGenerator() { // todo (7.0) : null or entityMapping.getJpaEntityName() for "name from GeneratedValue"? - final TableGenerator localizedMatch = findLocalizedMatch( + final var localizedMatch = findLocalizedMatch( JpaAnnotations.TABLE_GENERATOR, idMember, buildingContext.getMetadataCollector().getClassDetailsRegistry() @@ -164,11 +154,11 @@ protected void handleUnnamedTableGenerator() { @Override protected void handleNamedTableGenerator() { final String generator = generatedValue.generator(); - - final TableGenerator localizedTableMatch = findLocalizedMatch( + final var collector = buildingContext.getMetadataCollector(); + final var localizedTableMatch = findLocalizedMatch( JpaAnnotations.TABLE_GENERATOR, idMember, - buildingContext.getMetadataCollector().getClassDetailsRegistry() + collector.getClassDetailsRegistry() .getClassDetails( entityMapping.getClassName() ), TableGenerator::name, generator, @@ -176,32 +166,29 @@ protected void handleNamedTableGenerator() { ); if ( localizedTableMatch != null ) { handleTableGenerator( generator, localizedTableMatch ); - return; } - - // look for the matching global registration, if one. - final TableGeneratorRegistration globalMatch = - buildingContext.getMetadataCollector().getGlobalRegistrations() - .getTableGeneratorRegistrations().get( generator ); - if ( globalMatch != null ) { - handleTableGenerator( generator, globalMatch.configuration() ); - return; + else { + // look for the matching global registration, if one. + final var globalMatch = + collector.getGlobalRegistrations() + .getTableGeneratorRegistrations().get( generator ); + if ( globalMatch != null ) { + handleTableGenerator( generator, globalMatch.configuration() ); + } + else { + validateTableGeneration(); + handleTableGenerator( generator, null ); + } } - - validateTableGeneration(); - - handleTableGenerator( generator, null ); } private void validateTableGeneration() { // basically, make sure there is neither a SequenceGenerator nor a GenericGenerator with this name - final GlobalRegistrations globalRegistrations = - buildingContext.getMetadataCollector().getGlobalRegistrations(); + final var globalRegistrations = buildingContext.getMetadataCollector().getGlobalRegistrations(); final String generator = generatedValue.generator(); - final SequenceGeneratorRegistration globalSequenceMatch = - globalRegistrations.getSequenceGeneratorRegistrations().get( generator ); + final var globalSequenceMatch = globalRegistrations.getSequenceGeneratorRegistrations().get( generator ); if ( globalSequenceMatch != null ) { throw new MappingException( String.format( @@ -213,8 +200,7 @@ private void validateTableGeneration() { ); } - final GenericGeneratorRegistration globalGenericMatch = - globalRegistrations.getGenericGeneratorRegistrations().get( generator ); + final var globalGenericMatch = globalRegistrations.getGenericGeneratorRegistrations().get( generator ); if ( globalGenericMatch != null ) { throw new MappingException( String.format( @@ -235,11 +221,12 @@ private void validateTableGeneration() { protected void handleUnnamedAutoGenerator() { // todo (7.0) : null or entityMapping.getJpaEntityName() for "name from GeneratedValue"? - final SequenceGenerator localizedSequenceMatch = findLocalizedMatch( + final var classDetailsRegistry = buildingContext.getMetadataCollector().getClassDetailsRegistry(); + + final var localizedSequenceMatch = findLocalizedMatch( JpaAnnotations.SEQUENCE_GENERATOR, idMember, - buildingContext.getMetadataCollector().getClassDetailsRegistry() - .getClassDetails( entityMapping.getClassName() ), + classDetailsRegistry.getClassDetails( entityMapping.getClassName() ), null, null, buildingContext @@ -249,11 +236,10 @@ protected void handleUnnamedAutoGenerator() { return; } - final TableGenerator localizedTableMatch = findLocalizedMatch( + final var localizedTableMatch = findLocalizedMatch( JpaAnnotations.TABLE_GENERATOR, idMember, - buildingContext.getMetadataCollector().getClassDetailsRegistry() - .getClassDetails( entityMapping.getClassName() ), + classDetailsRegistry.getClassDetails( entityMapping.getClassName() ), null, null, buildingContext @@ -263,11 +249,10 @@ protected void handleUnnamedAutoGenerator() { return; } - final GenericGenerator localizedGenericMatch = findLocalizedMatch( + final var localizedGenericMatch = findLocalizedMatch( HibernateAnnotations.GENERIC_GENERATOR, idMember, - buildingContext.getMetadataCollector().getClassDetailsRegistry() - .getClassDetails( entityMapping.getClassName() ), + classDetailsRegistry.getClassDetails( entityMapping.getClassName() ), null, null, buildingContext @@ -292,8 +277,7 @@ protected void handleUnnamedAutoGenerator() { GeneratorAnnotationHelper.handleUuidStrategy( idValue, idMember, - buildingContext.getMetadataCollector().getClassDetailsRegistry() - .getClassDetails( entityMapping.getClassName() ), + classDetailsRegistry.getClassDetails( entityMapping.getClassName() ), buildingContext ); return; @@ -317,7 +301,7 @@ protected void handleNamedAutoGenerator() { } final String generator = generatedValue.generator(); - final Class legacyNamedGenerator = mapLegacyNamedGenerator( generator, buildingContext ); + final var legacyNamedGenerator = mapLegacyNamedGenerator( generator, buildingContext ); if ( legacyNamedGenerator != null ) { //generator settings GeneratorBinder.createGeneratorFrom( @@ -353,7 +337,8 @@ protected void handleNamedAutoGenerator() { private boolean handleAsLocalAutoGenerator() { if ( "increment".equals( generatedValue.generator() ) ) { - final GenericGeneratorAnnotation incrementGenerator = new GenericGeneratorAnnotation( buildingContext.getBootstrapContext().getModelsContext() ); + final var incrementGenerator = + new GenericGeneratorAnnotation( buildingContext.getBootstrapContext().getModelsContext() ); incrementGenerator.name( "increment" ); incrementGenerator.strategy( "increment" ); @@ -370,11 +355,12 @@ private boolean handleAsLocalAutoGenerator() { final String generator = generatedValue.generator(); assert !generator.isEmpty(); - final SequenceGenerator localizedSequenceMatch = findLocalizedMatch( + final var classDetailsRegistry = buildingContext.getMetadataCollector().getClassDetailsRegistry(); + + final var localizedSequenceMatch = findLocalizedMatch( JpaAnnotations.SEQUENCE_GENERATOR, idMember, - buildingContext.getMetadataCollector().getClassDetailsRegistry() - .getClassDetails( entityMapping.getClassName() ), + classDetailsRegistry.getClassDetails( entityMapping.getClassName() ), SequenceGenerator::name, generator, buildingContext @@ -384,11 +370,10 @@ private boolean handleAsLocalAutoGenerator() { return true; } - final TableGenerator localizedTableMatch = findLocalizedMatch( + final var localizedTableMatch = findLocalizedMatch( JpaAnnotations.TABLE_GENERATOR, idMember, - buildingContext.getMetadataCollector().getClassDetailsRegistry() - .getClassDetails( entityMapping.getClassName() ), + classDetailsRegistry.getClassDetails( entityMapping.getClassName() ), TableGenerator::name, generator, buildingContext @@ -398,11 +383,10 @@ private boolean handleAsLocalAutoGenerator() { return true; } - final GenericGenerator localizedGenericMatch = findLocalizedMatch( + final var localizedGenericMatch = findLocalizedMatch( HibernateAnnotations.GENERIC_GENERATOR, idMember, - buildingContext.getMetadataCollector().getClassDetailsRegistry() - .getClassDetails( entityMapping.getClassName() ), + classDetailsRegistry.getClassDetails( entityMapping.getClassName() ), GenericGenerator::name, generator, buildingContext @@ -422,26 +406,22 @@ private boolean handleAsLocalAutoGenerator() { } private boolean handleAsNamedGlobalAutoGenerator() { - final GlobalRegistrations globalRegistrations = - buildingContext.getMetadataCollector().getGlobalRegistrations(); + final var globalRegistrations = buildingContext.getMetadataCollector().getGlobalRegistrations(); final String generator = generatedValue.generator(); - final SequenceGeneratorRegistration globalSequenceMatch = - globalRegistrations.getSequenceGeneratorRegistrations().get( generator ); + final var globalSequenceMatch = globalRegistrations.getSequenceGeneratorRegistrations().get( generator ); if ( globalSequenceMatch != null ) { handleSequenceGenerator( generator, globalSequenceMatch.configuration(), idValue, idMember, buildingContext ); return true; } - final TableGeneratorRegistration globalTableMatch = - globalRegistrations.getTableGeneratorRegistrations().get( generator ); + final var globalTableMatch = globalRegistrations.getTableGeneratorRegistrations().get( generator ); if ( globalTableMatch != null ) { handleTableGenerator( generator, globalTableMatch.configuration() ); return true; } - final GenericGeneratorRegistration globalGenericMatch = - globalRegistrations.getGenericGeneratorRegistrations().get( generator ); + final var globalGenericMatch = globalRegistrations.getGenericGeneratorRegistrations().get( generator ); if ( globalGenericMatch != null ) { GeneratorAnnotationHelper.handleGenericGenerator( generator, diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ImplicitToOneJoinTableSecondPass.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ImplicitToOneJoinTableSecondPass.java index d95cd78c9897..6cbca2917d80 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ImplicitToOneJoinTableSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ImplicitToOneJoinTableSecondPass.java @@ -7,14 +7,12 @@ import java.util.Map; import org.hibernate.annotations.NotFoundAction; -import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.PropertyData; import org.hibernate.boot.spi.SecondPass; import org.hibernate.mapping.Join; import org.hibernate.mapping.ManyToOne; import org.hibernate.mapping.PersistentClass; -import org.hibernate.mapping.Property; import org.hibernate.mapping.Table; import jakarta.persistence.JoinTable; @@ -65,10 +63,9 @@ public ImplicitToOneJoinTableSecondPass( private void inferJoinTableName(TableBinder tableBinder, Map persistentClasses) { if ( isEmpty( tableBinder.getName() ) ) { - final PersistentClass owner = propertyHolder.getPersistentClass(); - final InFlightMetadataCollector collector = context.getMetadataCollector(); - final PersistentClass targetEntity = - persistentClasses.get( getReferenceEntityName( inferredData, context ) ); + final var owner = propertyHolder.getPersistentClass(); + final var collector = context.getMetadataCollector(); + final var targetEntity = persistentClasses.get( getReferenceEntityName( inferredData, context ) ); //default value tableBinder.setDefaultName( owner.getClassName(), @@ -85,7 +82,7 @@ private void inferJoinTableName(TableBinder tableBinder, Map persistentClasses) { - final TableBinder tableBinder = createTableBinder(); + final var tableBinder = createTableBinder(); inferJoinTableName( tableBinder, persistentClasses ); - final Table table = tableBinder.bind(); + final var table = tableBinder.bind(); value.setTable( table ); final Join join = propertyHolder.addJoin( joinTable, table, true ); - final PersistentClass owner = propertyHolder.getPersistentClass(); - final Property property = owner.getProperty( inferredData.getPropertyName() ); + final var owner = propertyHolder.getPersistentClass(); + final var property = owner.getProperty( inferredData.getPropertyName() ); assert property != null; // move the property from the main table to the new join table owner.removeProperty( property ); @@ -126,7 +123,7 @@ public void doSecondPass(Map persistentClasses) { if ( notFoundAction != null ) { join.disableForeignKeyCreation(); } - for ( AnnotatedJoinColumn joinColumn : joinColumns.getJoinColumns() ) { + for ( var joinColumn : joinColumns.getJoinColumns() ) { joinColumn.setExplicitTableName( join.getTable().getName() ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IndexBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IndexBinder.java index 081d041a18f1..879d8d1ca51d 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IndexBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IndexBinder.java @@ -162,7 +162,7 @@ private void createIndexOrUniqueKey( boolean declaredAsIndex, String options, Selectable[] columns) { - final IndexOrUniqueKeyNameSource source = + final var source = new IndexOrUniqueKeyNameSource( context, table, columnNames, originalKeyName, declaredAsIndex ); boolean hasFormula = false; for ( Selectable selectable : columns ) { @@ -197,8 +197,8 @@ private void createIndexOrUniqueKey( } void bindIndexes(Table table, jakarta.persistence.Index[] indexes) { - for ( jakarta.persistence.Index index : indexes ) { - final StringTokenizer tokenizer = new StringTokenizer( index.columnList(), "," ); + for ( var index : indexes ) { + final var tokenizer = new StringTokenizer( index.columnList(), "," ); final List parsed = new ArrayList<>(); while ( tokenizer.hasMoreElements() ) { final String trimmed = tokenizer.nextToken().trim(); @@ -227,7 +227,7 @@ void bindIndexes(Table table, jakarta.persistence.Index[] indexes) { } void bindUniqueConstraints(Table table, UniqueConstraint[] constraints) { - for ( UniqueConstraint constraint : constraints ) { + for ( var constraint : constraints ) { final String name = constraint.name(); final String[] columnNames = constraint.columnNames(); final String options = constraint.options(); @@ -323,11 +323,12 @@ private List toIdentifiers(String[] names) { if ( names == null ) { return emptyList(); } - - final List columnNames = arrayList( names.length ); - for ( String name : names ) { - columnNames.add( getDatabase().toIdentifier( name ) ); + else { + final List columnNames = arrayList( names.length ); + for ( String name : names ) { + columnNames.add( getDatabase().toIdentifier( name ) ); + } + return columnNames; } - return columnNames; } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IndexColumn.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IndexColumn.java index 6b755d8750e8..a9b5588bbadd 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IndexColumn.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IndexColumn.java @@ -62,7 +62,7 @@ private static void createParent( Map secondaryTables, IndexColumn column, MetadataBuildingContext context) { - final AnnotatedColumns parent = new AnnotatedColumns(); + final var parent = new AnnotatedColumns(); parent.setPropertyHolder( propertyHolder ); parent.setJoins( secondaryTables ); parent.setBuildingContext( context ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/InheritanceState.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/InheritanceState.java index 483dd8a7899d..031bb8793cfc 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/InheritanceState.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/InheritanceState.java @@ -71,14 +71,14 @@ public InheritanceState( } private void extractInheritanceType(ClassDetails classDetails) { - final Inheritance inheritanceAnn = classDetails.getDirectAnnotationUsage( Inheritance.class ); - final MappedSuperclass mappedSuperAnn = classDetails.getDirectAnnotationUsage( MappedSuperclass.class ); - if ( mappedSuperAnn != null ) { + final var inheritance = classDetails.getDirectAnnotationUsage( Inheritance.class ); + final var mappedSuperclass = classDetails.getDirectAnnotationUsage( MappedSuperclass.class ); + if ( mappedSuperclass != null ) { setEmbeddableSuperclass( true ); - setType( inheritanceAnn == null ? null : inheritanceAnn.strategy() ); + setType( inheritance == null ? null : inheritance.strategy() ); } else { - setType( inheritanceAnn == null ? SINGLE_TABLE : inheritanceAnn.strategy() ); + setType( inheritance == null ? SINGLE_TABLE : inheritance.strategy() ); } } @@ -96,7 +96,7 @@ public static InheritanceState getInheritanceStateOfSuperEntity( ClassDetails candidate = classDetails; do { candidate = candidate.getSuperClass(); - final InheritanceState currentState = states.get( candidate ); + final var currentState = states.get( candidate ); if ( currentState != null && !currentState.isEmbeddableSuperclass() ) { return currentState; } @@ -193,7 +193,7 @@ else if ( classDetails.hasDirectAnnotationUsage( IdClass.class ) ) { return classDetails; } else { - final InheritanceState state = getSuperclassInheritanceState( classDetails, inheritanceStatePerClass ); + final var state = getSuperclassInheritanceState( classDetails, inheritanceStatePerClass ); return state == null ? null : state.getClassWithIdClass( true ); } } @@ -234,7 +234,7 @@ private ElementsToProcess getElementsToProcess() { final ArrayList elements = new ArrayList<>(); int idPropertyCount = 0; for ( ClassDetails classToProcessForMappedSuperclass : classesToProcessForMappedSuperclass ) { - final PropertyContainer container = + final var container = new PropertyContainer( classToProcessForMappedSuperclass, classDetails, accessType ); idPropertyCount = addElementsOfClass( elements, container, buildingContext, idPropertyCount ); } @@ -332,7 +332,7 @@ private org.hibernate.mapping.MappedSuperclass processMappedSuperclass(Table imp // todo (jpa32) : causes the mapped-superclass Class reference to be loaded... // - but this is how it's always worked, so... final var mappedSuperclassDetails = classesToProcessForMappedSuperclass.get( index ); - final Class mappedSuperclassJavaType = mappedSuperclassDetails.toJavaClass(); + final var mappedSuperclassJavaType = mappedSuperclassDetails.toJavaClass(); //add MappedSuperclass if not already there mappedSuperclass = metadataCollector.getMappedSuperclass( mappedSuperclassJavaType ); if ( mappedSuperclass == null ) { diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ListBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ListBinder.java index d83df6db7f87..bc5d0dbe70cb 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ListBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ListBinder.java @@ -65,7 +65,7 @@ private void bindIndex() { } indexColumn.getParent().setPropertyHolder( valueHolder ); - final BasicValueBinder valueBinder = new BasicValueBinder( BasicValueBinder.Kind.LIST_INDEX, buildingContext ); + final var valueBinder = new BasicValueBinder( BasicValueBinder.Kind.LIST_INDEX, buildingContext ); valueBinder.setColumns( indexColumn.getParent() ); valueBinder.setReturnedClassName( Integer.class.getName() ); valueBinder.setType( property, getElementType(), null, null ); @@ -89,8 +89,8 @@ private void createBackref() { && !collection.getKey().isNullable() && !collection.isInverse() ) { final String entityName = ( (OneToMany) collection.getElement() ).getReferencedEntityName(); - final PersistentClass referenced = buildingContext.getMetadataCollector().getEntityBinding( entityName ); - final IndexBackref backref = new IndexBackref(); + final var referenced = buildingContext.getMetadataCollector().getEntityBinding( entityName ); + final var backref = new IndexBackref(); backref.setName( '_' + propertyName + "IndexBackref" ); backref.setOptional( true ); backref.setUpdatable( false ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/MapBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/MapBinder.java index fb4ba5db6eb6..2440b6cf8ec4 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/MapBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/MapBinder.java @@ -43,7 +43,6 @@ import jakarta.persistence.AttributeOverride; import jakarta.persistence.AttributeOverrides; import jakarta.persistence.ConstraintMode; -import jakarta.persistence.ForeignKey; import jakarta.persistence.InheritanceType; import jakarta.persistence.MapKeyClass; import jakarta.persistence.MapKeyColumn; @@ -116,8 +115,8 @@ protected boolean mappingDefinedAttributeOverrideOnElement(MemberDetails propert return namedMapValue( property.getDirectAnnotationUsage( AttributeOverride.class ) ); } if ( property.hasDirectAnnotationUsage( AttributeOverrides.class ) ) { - final AttributeOverrides annotations = property.getDirectAnnotationUsage( AttributeOverrides.class ); - for ( AttributeOverride attributeOverride : annotations.value() ) { + final var annotations = property.getDirectAnnotationUsage( AttributeOverrides.class ); + for ( var attributeOverride : annotations.value() ) { if ( namedMapValue( attributeOverride ) ) { return true; } @@ -131,17 +130,17 @@ private static boolean namedMapValue(AttributeOverride annotation) { } private void makeOneToManyMapKeyColumnNullableIfNotInProperty(MemberDetails property) { - final Map map = (Map) this.collection; + final var map = (Map) this.collection; if ( map.isOneToMany() && property.hasDirectAnnotationUsage( MapKeyColumn.class ) ) { final Value indexValue = map.getIndex(); if ( indexValue.getColumnSpan() != 1 ) { throw new AssertionFailure( "Map key mapped by @MapKeyColumn does not have 1 column" ); } - final Selectable selectable = indexValue.getSelectables().get(0); + final var selectable = indexValue.getSelectables().get(0); if ( selectable.isFormula() ) { throw new AssertionFailure( "Map key mapped by @MapKeyColumn is a Formula" ); } - final Column column = (Column) selectable; + final var column = (Column) selectable; if ( !column.isNullable() ) { final PersistentClass persistentClass = ( (OneToMany) map.getElement() ).getAssociatedClass(); // check if the index column has been mapped by the associated entity to a property; @@ -157,8 +156,8 @@ private void makeOneToManyMapKeyColumnNullableIfNotInProperty(MemberDetails prop } private boolean propertiesContainColumn(List properties, Column column) { - for ( Property property : properties ) { - for ( Selectable selectable: property.getSelectables() ) { + for ( var property : properties ) { + for ( var selectable: property.getSelectables() ) { if ( column.equals( selectable ) ) { final Column iteratedColumn = (Column) selectable; if ( column.getValue().getTable().equals( iteratedColumn.getValue().getTable() ) ) { @@ -196,17 +195,17 @@ private void handleMapKey( AnnotatedColumns mapKeyColumns, AnnotatedJoinColumns mapKeyManyToManyColumns) { final String mapKeyType = getKeyType( property ); - final PersistentClass collectionEntity = persistentClasses.get( mapKeyType ); + final var collectionEntity = persistentClasses.get( mapKeyType ); final boolean isKeyedByEntities = collectionEntity != null; if ( isKeyedByEntities ) { - final ManyToOne element = handleCollectionKeyedByEntities( mapKeyType ); + final var element = handleCollectionKeyedByEntities( mapKeyType ); handleForeignKey( property, element ); // a map key column has no unique constraint, so pass 'unique=false' here bindManyToManyInverseForeignKey( collectionEntity, mapKeyManyToManyColumns, element, false ); } else { - final ClassDetails keyClass = mapKeyClass( mapKeyType ); - final TypeDetails keyTypeDetails = new ClassTypeDetailsImpl( keyClass, TypeDetails.Kind.CLASS ); + final var keyClass = mapKeyClass( mapKeyType ); + final var keyTypeDetails = new ClassTypeDetailsImpl( keyClass, TypeDetails.Kind.CLASS ); handleMapKey( property, mapKeyColumns, @@ -220,7 +219,7 @@ private void handleMapKey( //FIXME pass the Index Entity JoinColumns if ( !collection.isOneToMany() ) { //index column should not be null - for ( AnnotatedJoinColumn column : mapKeyManyToManyColumns.getJoinColumns() ) { + for ( var column : mapKeyManyToManyColumns.getJoinColumns() ) { column.forceNotNull(); } } @@ -254,8 +253,8 @@ private ClassDetails mapKeyClass(String mapKeyType) { private static String getKeyType(MemberDetails property) { //target has priority over reflection for the map key type //JPA 2 has priority - final MapKeyClass mapKeyClassAnn = property.getDirectAnnotationUsage( MapKeyClass.class ); - final Class target = mapKeyClassAnn != null ? mapKeyClassAnn.value() : void.class; + final var mapKeyClassAnn = property.getDirectAnnotationUsage( MapKeyClass.class ); + final var target = mapKeyClassAnn != null ? mapKeyClassAnn.value() : void.class; return void.class.equals( target ) ? property.getMapKeyType().getName() : target.getName(); } @@ -263,7 +262,7 @@ private void handleMapKeyProperty( TypeDetails elementType, java.util.Map persistentClasses, String mapKeyPropertyName) { - final PersistentClass associatedClass = persistentClasses.get( elementType.getName() ); + final var associatedClass = persistentClasses.get( elementType.getName() ); if ( associatedClass == null ) { throw new AnnotationException( "Association '" + safeCollectionRole() + "'" + targetEntityMessage( elementType ) ); @@ -274,7 +273,7 @@ private void handleMapKeyProperty( + "' not found in target entity '" + associatedClass.getEntityName() + "'" ); } // HHH-11005 - if InheritanceType.JOINED then need to find class defining the column - final PersistentClass targetEntity = + final var targetEntity = inheritanceStatePerClass.get( elementType.determineRawClass() ).getType() == InheritanceType.JOINED ? mapProperty.getPersistentClass() : associatedClass; @@ -292,7 +291,7 @@ private CollectionPropertyHolder buildCollectionPropertyHolder( private CollectionPropertyHolder buildCollectionPropertyHolder( MemberDetails property, ClassDetails keyClass) { - final CollectionPropertyHolder holder = + final var holder = buildPropertyHolder( collection, getPath(), keyClass, property, propertyHolder, buildingContext ); // 'propertyHolder' is the PropertyHolder for the owner of the collection // 'holder' is the CollectionPropertyHolder. @@ -307,7 +306,7 @@ private String getPath() { } private void handleForeignKey(MemberDetails property, ManyToOne element) { - final ForeignKey foreignKey = getMapKeyForeignKey( property ); + final var foreignKey = getMapKeyForeignKey( property ); if ( foreignKey != null ) { final ConstraintMode constraintMode = foreignKey.value(); if ( constraintMode == ConstraintMode.NO_CONSTRAINT @@ -326,7 +325,7 @@ && getBuildingContext().getBuildingOptions().isNoConstraintByDefault() ) { //similar to CollectionBinder.handleCollectionOfEntities() private ManyToOne handleCollectionKeyedByEntities( String mapKeyType) { - final ManyToOne element = new ManyToOne( buildingContext, collection.getCollectionTable() ); + final var element = new ManyToOne( buildingContext, collection.getCollectionTable() ); getMap().setIndex( element ); element.setReferencedEntityName( mapKeyType ); //element.setFetchMode( fetchMode ); @@ -346,8 +345,7 @@ private void handleMapKey( AnnotatedClassType classType, CollectionPropertyHolder holder, AccessType accessType) { - final Class> compositeUserType - = resolveCompositeUserType( property, keyTypeDetails, buildingContext ); + final var compositeUserType = resolveCompositeUserType( property, keyTypeDetails, buildingContext ); if ( classType == EMBEDDABLE || compositeUserType != null ) { handleCompositeMapKey( keyTypeDetails, holder, accessType, compositeUserType ); } @@ -363,9 +361,9 @@ private void handleMapKey( TypeDetails keyTypeDetails, CollectionPropertyHolder holder, AccessType accessType) { - final BasicValueBinder elementBinder = new BasicValueBinder( BasicValueBinder.Kind.MAP_KEY, buildingContext ); + final var elementBinder = new BasicValueBinder( BasicValueBinder.Kind.MAP_KEY, buildingContext ); elementBinder.setReturnedClassName(mapKeyType); - final AnnotatedColumns keyColumns = createElementColumnsIfNecessary( + final var keyColumns = createElementColumnsIfNecessary( collection, mapKeyColumns, Collection.DEFAULT_KEY_COLUMN_NAME, @@ -420,7 +418,7 @@ private static Class> resolveCompositeUserType( MemberDetails property, TypeDetails returnedClass, MetadataBuildingContext context) { - final MapKeyCompositeType compositeType = property.getDirectAnnotationUsage( MapKeyCompositeType.class ); + final var compositeType = property.getDirectAnnotationUsage( MapKeyCompositeType.class ); if ( compositeType != null ) { return compositeType.value(); } @@ -434,12 +432,12 @@ else if ( returnedClass != null ) { } private jakarta.persistence.ForeignKey getMapKeyForeignKey(MemberDetails property) { - final MapKeyJoinColumns mapKeyJoinColumns = property.getDirectAnnotationUsage( MapKeyJoinColumns.class ); + final var mapKeyJoinColumns = property.getDirectAnnotationUsage( MapKeyJoinColumns.class ); if ( mapKeyJoinColumns != null ) { return mapKeyJoinColumns.foreignKey(); } - final MapKeyJoinColumn mapKeyJoinColumn = property.getDirectAnnotationUsage( MapKeyJoinColumn.class ); + final var mapKeyJoinColumn = property.getDirectAnnotationUsage( MapKeyJoinColumn.class ); if ( mapKeyJoinColumn != null ) { return mapKeyJoinColumn.foreignKey(); } @@ -448,14 +446,14 @@ private jakarta.persistence.ForeignKey getMapKeyForeignKey(MemberDetails propert } private boolean mappingDefinedAttributeOverrideOnMapKey(MemberDetails property) { - final AttributeOverride overrideAnn = property.getDirectAnnotationUsage( AttributeOverride.class ); + final var overrideAnn = property.getDirectAnnotationUsage( AttributeOverride.class ); if ( overrideAnn != null ) { return namedMapKey( overrideAnn ); } - final AttributeOverrides overridesAnn = property.getDirectAnnotationUsage( AttributeOverrides.class ); + final var overridesAnn = property.getDirectAnnotationUsage( AttributeOverrides.class ); if ( overridesAnn != null ) { - for ( AttributeOverride nestedAnn : overridesAnn.value() ) { + for ( var nestedAnn : overridesAnn.value() ) { if ( namedMapKey( nestedAnn ) ) { return true; } @@ -499,7 +497,7 @@ else if ( value instanceof SimpleValue simpleValue ) { private SimpleValue createTargetValue(Table mapKeyTable, SimpleValue sourceValue) { final SimpleValue targetValue; if ( sourceValue instanceof ManyToOne sourceManyToOne ) { - final ManyToOne targetManyToOne = new ManyToOne( getBuildingContext(), mapKeyTable); + final var targetManyToOne = new ManyToOne( getBuildingContext(), mapKeyTable); targetManyToOne.setFetchMode( FetchMode.DEFAULT ); targetManyToOne.setLazy( true ); //targetValue.setIgnoreNotFound( ); does not make sense for a map key @@ -510,14 +508,14 @@ private SimpleValue createTargetValue(Table mapKeyTable, SimpleValue sourceValue targetValue = new BasicValue( getBuildingContext(), mapKeyTable); targetValue.copyTypeFrom( sourceValue ); } - for ( Selectable selectable : sourceValue.getSelectables() ) { + for ( var selectable : sourceValue.getSelectables() ) { addSelectable( targetValue, selectable ); } return targetValue; } private DependantBasicValue createDependantBasicValue(Table mapKeyTable, BasicValue sourceValue) { - final DependantBasicValue dependantBasicValue = new DependantBasicValue( + final var dependantBasicValue = new DependantBasicValue( getBuildingContext(), mapKeyTable, sourceValue, @@ -538,10 +536,10 @@ else if ( selectable instanceof Formula formula ) { } private Component createIndexComponent(Collection collection, PersistentClass associatedClass, Component component) { - final Component indexComponent = new Component( getBuildingContext(), collection ); + final var indexComponent = new Component( getBuildingContext(), collection ); indexComponent.setComponentClassName( component.getComponentClassName() ); - for ( Property property : component.getProperties() ) { - final Property newProperty = new Property(); + for ( var property : component.getProperties() ) { + final var newProperty = new Property(); newProperty.setCascade( property.getCascade() ); newProperty.setValueGeneratorCreator( property.getValueGeneratorCreator() ); newProperty.setInsertable( false ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/NaturalIdBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/NaturalIdBinder.java index ac924887708c..626c1d6d4081 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/NaturalIdBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/NaturalIdBinder.java @@ -10,10 +10,8 @@ import org.hibernate.boot.model.naming.ImplicitUniqueKeyNameSource; import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.boot.spi.MetadataBuildingContext; -import org.hibernate.mapping.Property; import org.hibernate.mapping.Selectable; import org.hibernate.mapping.Table; -import org.hibernate.mapping.UniqueKey; import org.hibernate.models.spi.MemberDetails; import java.util.List; @@ -34,9 +32,9 @@ static void addNaturalIds( MetadataBuildingContext context) { // Natural ID columns must reside in one single UniqueKey within the Table. // For now, simply ensure consistent naming. - final NaturalId naturalId = property.getDirectAnnotationUsage( NaturalId.class ); + final var naturalId = property.getDirectAnnotationUsage( NaturalId.class ); if ( naturalId != null ) { - final AnnotatedColumns annotatedColumns = joinColumns != null ? joinColumns : columns; + final var annotatedColumns = joinColumns != null ? joinColumns : columns; final Identifier name = uniqueKeyName( context, annotatedColumns ); if ( inSecondPass ) { addColumnsToUniqueKey( annotatedColumns, name ); @@ -54,10 +52,10 @@ private static Identifier uniqueKeyName(MetadataBuildingContext context, Annotat } private static void addColumnsToUniqueKey(AnnotatedColumns columns, Identifier name) { - final InFlightMetadataCollector collector = columns.getBuildingContext().getMetadataCollector(); + final var collector = columns.getBuildingContext().getMetadataCollector(); final Table table = columns.getTable(); - final UniqueKey uniqueKey = table.getOrCreateUniqueKey( name.render( collector.getDatabase().getDialect() ) ); - final Property property = columns.resolveProperty(); + final var uniqueKey = table.getOrCreateUniqueKey( name.render( collector.getDatabase().getDialect() ) ); + final var property = columns.resolveProperty(); if ( property.isComposite() ) { for ( Selectable selectable : property.getValue().getSelectables() ) { if ( selectable instanceof org.hibernate.mapping.Column column) { @@ -66,7 +64,7 @@ private static void addColumnsToUniqueKey(AnnotatedColumns columns, Identifier n } } else { - for ( AnnotatedColumn column : columns.getColumns() ) { + for ( var column : columns.getColumns() ) { uniqueKey.addColumn( tableColumn( column.getMappingColumn(), table, collector ) ); } } @@ -75,7 +73,7 @@ private static void addColumnsToUniqueKey(AnnotatedColumns columns, Identifier n private static org.hibernate.mapping.Column tableColumn( org.hibernate.mapping.Column column, Table table, InFlightMetadataCollector collector) { final String columnName = collector.getLogicalColumnName( table, column.getQuotedName() ); - final org.hibernate.mapping.Column tableColumn = table.getColumn( collector, columnName ); + final var tableColumn = table.getColumn( collector, columnName ); if ( tableColumn == null ) { throw new AnnotationException( "Table '" + table.getName() + "' has no column named '" + columnName diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/OneToOneSecondPass.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/OneToOneSecondPass.java index 371a59eb2f9f..594a0f2ef724 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/OneToOneSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/OneToOneSecondPass.java @@ -16,7 +16,6 @@ import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.PropertyData; import org.hibernate.boot.spi.SecondPass; -import org.hibernate.mapping.Column; import org.hibernate.mapping.Component; import org.hibernate.mapping.DependantValue; import org.hibernate.mapping.Join; @@ -25,7 +24,6 @@ import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; import org.hibernate.mapping.SortableValue; -import org.hibernate.mapping.Value; import org.hibernate.models.spi.MemberDetails; import org.hibernate.type.ForeignKeyDirection; @@ -87,34 +85,34 @@ public OneToOneSecondPass( @Override public void doSecondPass(Map persistentClasses) throws MappingException { - final OneToOne value = + final var oneToOne = new OneToOne( buildingContext, propertyHolder.getTable(), propertyHolder.getPersistentClass() ); final String propertyName = inferredData.getPropertyName(); - value.setPropertyName( propertyName ); - value.setReferencedEntityName( referencedEntityName ); + oneToOne.setPropertyName( propertyName ); + oneToOne.setReferencedEntityName( referencedEntityName ); MemberDetails property = inferredData.getAttributeMember(); - defineFetchingStrategy( value, property, inferredData, propertyHolder ); + defineFetchingStrategy( oneToOne, property, inferredData, propertyHolder ); //value.setFetchMode( fetchMode ); - value.setOnDeleteAction( onDeleteAction ); + oneToOne.setOnDeleteAction( onDeleteAction ); //value.setLazy( fetchMode != FetchMode.JOIN ); - value.setConstrained( !optional ); - value.setForeignKeyType( getForeignKeyDirection() ); - bindForeignKeyNameAndDefinition( value, property, + oneToOne.setConstrained( !optional ); + oneToOne.setForeignKeyType( getForeignKeyDirection() ); + bindForeignKeyNameAndDefinition( oneToOne, property, property.getDirectAnnotationUsage( ForeignKey.class ), buildingContext ); - final PropertyBinder binder = new PropertyBinder(); + final var binder = new PropertyBinder(); binder.setName( propertyName ); binder.setMemberDetails( property ); - binder.setValue( value ); + binder.setValue( oneToOne ); binder.setCascade( cascadeStrategy ); binder.setAccessType( inferredData.getDefaultAccess() ); binder.setBuildingContext( buildingContext ); binder.setHolder( propertyHolder ); - final LazyGroup lazyGroupAnnotation = property.getDirectAnnotationUsage( LazyGroup.class ); + final var lazyGroupAnnotation = property.getDirectAnnotationUsage( LazyGroup.class ); if ( lazyGroupAnnotation != null ) { binder.setLazyGroup( lazyGroupAnnotation.value() ); } @@ -122,13 +120,13 @@ public void doSecondPass(Map persistentClasses) throws final Property result = binder.makeProperty(); result.setOptional( optional ); if ( mappedBy == null ) { - bindOwned( persistentClasses, value, propertyName, result ); + bindOwned( persistentClasses, oneToOne, propertyName, result ); } else { - bindUnowned( persistentClasses, value, result ); + bindUnowned( persistentClasses, oneToOne, result ); } binder.callAttributeBindersInSecondPass( result ); - value.sortProperties(); + oneToOne.sortProperties(); } private ForeignKeyDirection getForeignKeyDirection() { @@ -138,7 +136,7 @@ private ForeignKeyDirection getForeignKeyDirection() { private void bindUnowned(Map persistentClasses, OneToOne oneToOne, Property property) { oneToOne.setMappedByProperty( mappedBy ); final String targetEntityName = oneToOne.getReferencedEntityName(); - final PersistentClass targetEntity = persistentClasses.get( targetEntityName ); + final var targetEntity = persistentClasses.get( targetEntityName ); if ( targetEntity == null ) { final String problem = annotatedEntity ? " which does not belong to the same persistence unit" @@ -146,8 +144,8 @@ private void bindUnowned(Map persistentClasses, OneToOn throw new MappingException( "Association '" + getPath( propertyHolder, inferredData ) + "' targets the type '" + targetEntityName + "'" + problem ); } - final Property targetProperty = targetProperty( oneToOne, targetEntity ); - final Value targetPropertyValue = targetProperty.getValue(); + final var targetProperty = targetProperty( oneToOne, targetEntity ); + final var targetPropertyValue = targetProperty.getValue(); if ( targetPropertyValue instanceof OneToOne ) { propertyHolder.addProperty( property, inferredData.getAttributeMember(), inferredData.getDeclaringClass() ); } @@ -176,7 +174,7 @@ private void bindTargetManyToOne( PersistentClass targetEntity, Property targetProperty) { Join otherSideJoin = null; - for ( Join otherSideJoinValue : targetEntity.getJoins() ) { + for ( var otherSideJoinValue : targetEntity.getJoins() ) { if ( otherSideJoinValue.containsProperty(targetProperty) ) { otherSideJoin = otherSideJoinValue; break; @@ -187,10 +185,10 @@ private void bindTargetManyToOne( final Join mappedByJoin = buildJoinFromMappedBySide( persistentClasses.get( ownerEntity ), targetProperty, otherSideJoin ); - final ManyToOne manyToOne = createManyToOne( oneToOne, mappedByJoin ); + final var manyToOne = createManyToOne( oneToOne, mappedByJoin ); property.setValue( manyToOne ); - for ( Column column: otherSideJoin.getKey().getColumns() ) { - Column copy = column.clone(); + for ( var column: otherSideJoin.getKey().getColumns() ) { + final var copy = column.clone(); copy.setValue( manyToOne ); manyToOne.addColumn( copy ); } @@ -205,7 +203,7 @@ private void bindTargetManyToOne( // HHH-6813 // Foo: @Id long id, @OneToOne(mappedBy="foo") Bar bar // Bar: @Id @OneToOne Foo foo - boolean referenceToPrimaryKey = mappedBy == null + final boolean referenceToPrimaryKey = mappedBy == null || targetEntity.getIdentifier() instanceof Component compositeId && compositeId.matchesAllProperties( mappedBy ); oneToOne.setReferenceToPrimaryKey( referenceToPrimaryKey ); @@ -232,7 +230,7 @@ private ManyToOne createManyToOne(OneToOne oneToOne, Join mappedByJoin) { private Property targetProperty(OneToOne oneToOne, PersistentClass targetEntity) { try { - final Property targetProperty = findPropertyByName( targetEntity, mappedBy ); + final var targetProperty = findPropertyByName( targetEntity, mappedBy ); if ( targetProperty != null ) { return targetProperty; } @@ -272,14 +270,13 @@ private void bindOwned( * the owning side. */ private Join buildJoinFromMappedBySide(PersistentClass persistentClass, Property otherSideProperty, Join originalJoin) { - final Join join = new Join(); + final var join = new Join(); join.setPersistentClass( persistentClass ); //no check constraints available on joins join.setTable( originalJoin.getTable() ); join.setInverse( true ); - final DependantValue key = - new DependantValue( buildingContext, join.getTable(), persistentClass.getIdentifier() ); + final var key = new DependantValue( buildingContext, join.getTable(), persistentClass.getIdentifier() ); if ( notFoundAction != null ) { join.disableForeignKeyCreation(); @@ -289,8 +286,8 @@ private Join buildJoinFromMappedBySide(PersistentClass persistentClass, Property //perhaps not quite per-spec, but a Good Thing anyway join.setOptional( true ); key.setOnDeleteAction( null ); - for ( Column column: otherSideProperty.getValue().getColumns() ) { - Column copy = column.clone(); + for ( var column: otherSideProperty.getValue().getColumns() ) { + final var copy = column.clone(); copy.setValue( key ); key.addColumn( copy ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyBinder.java index 2ef0f9b6ac24..e3d32cc51c2a 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyBinder.java @@ -43,7 +43,6 @@ import org.hibernate.annotations.Parent; import org.hibernate.binder.AttributeBinder; import org.hibernate.boot.spi.AccessType; -import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.PropertyData; import org.hibernate.engine.OptimisticLockStyle; @@ -63,15 +62,11 @@ import org.hibernate.mapping.ToOne; import org.hibernate.mapping.Value; import org.hibernate.metamodel.spi.EmbeddableInstantiator; -import org.hibernate.models.spi.AnnotationDescriptor; -import org.hibernate.models.spi.AnnotationDescriptorRegistry; import org.hibernate.models.spi.ArrayTypeDetails; import org.hibernate.models.spi.ClassDetails; -import org.hibernate.models.spi.ClassDetailsRegistry; import org.hibernate.models.spi.MemberDetails; import org.hibernate.models.spi.ModelsContext; import org.hibernate.models.spi.TypeDetails; -import org.hibernate.models.spi.TypeVariableScope; import org.hibernate.usertype.CompositeUserType; import java.lang.annotation.Annotation; @@ -101,7 +96,6 @@ import static org.hibernate.boot.model.internal.ToOneBinder.bindOneToOne; import static org.hibernate.id.IdentifierGeneratorHelper.getForeignId; import static org.hibernate.internal.util.StringHelper.qualify; -import static org.hibernate.internal.util.collections.CollectionHelper.isEmpty; /** * A stateful binder responsible for creating {@link Property} objects. @@ -293,30 +287,27 @@ private boolean autoApplyConverters() { @SuppressWarnings({"rawtypes", "unchecked"}) private void callAttributeBinders(Property property, Map persistentClasses) { - final List metaAnnotatedTargets = + final var metaAnnotatedTargets = memberDetails.getMetaAnnotated( AttributeBinderType.class, getSourceModelContext() ); - - if ( !isEmpty( metaAnnotatedTargets ) ) { - final AnnotationDescriptorRegistry descriptorRegistry = - getSourceModelContext().getAnnotationDescriptorRegistry(); - for ( int i = 0; i < metaAnnotatedTargets.size(); i++ ) { - final Annotation metaAnnotatedTarget = metaAnnotatedTargets.get( i ); - final AnnotationDescriptor metaAnnotatedDescriptor = - descriptorRegistry.getDescriptor( metaAnnotatedTarget.annotationType() ); - final AttributeBinderType binderTypeAnn = - metaAnnotatedDescriptor.getDirectAnnotationUsage( AttributeBinderType.class ); - try { - final AttributeBinder binder = binderTypeAnn.binder().getConstructor().newInstance(); - final PersistentClass persistentClass = entityBinder != null - ? entityBinder.getPersistentClass() - : persistentClasses.get( holder.getEntityName() ); - binder.bind( metaAnnotatedTarget, buildingContext, persistentClass, property ); - } - catch ( Exception e ) { - throw new AnnotationException( "error processing @AttributeBinderType annotation '" - + metaAnnotatedDescriptor.getAnnotationType().getName() + "' for property '" - + qualify( holder.getPath(), name ) + "'", e ); - } + final var descriptorRegistry = getSourceModelContext().getAnnotationDescriptorRegistry(); + for ( int i = 0; i < metaAnnotatedTargets.size(); i++ ) { + final Annotation metaAnnotatedTarget = metaAnnotatedTargets.get( i ); + final var metaAnnotatedDescriptor = + descriptorRegistry.getDescriptor( metaAnnotatedTarget.annotationType() ); + final var binderTypeAnn = + metaAnnotatedDescriptor.getDirectAnnotationUsage( AttributeBinderType.class ); + try { + final AttributeBinder binder = binderTypeAnn.binder().getConstructor().newInstance(); + final var persistentClass = + entityBinder != null + ? entityBinder.getPersistentClass() + : persistentClasses.get( holder.getEntityName() ); + binder.bind( metaAnnotatedTarget, buildingContext, persistentClass, property ); + } + catch ( Exception e ) { + throw new AnnotationException( "error processing @AttributeBinderType annotation '" + + metaAnnotatedDescriptor.getAnnotationType().getName() + "' for property '" + + qualify( holder.getPath(), name ) + "'", e ); } } } @@ -347,7 +338,7 @@ private Property bind(Property property) { } void callAttributeBindersInSecondPass(Property property) { - final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector(); + final var metadataCollector = buildingContext.getMetadataCollector(); if ( metadataCollector.isInSecondPass() ) { callAttributeBinders( property, metadataCollector.getEntityBindingMap() ); } @@ -357,7 +348,7 @@ void callAttributeBindersInSecondPass(Property property) { } private void bindId(Property property) { - final RootClass rootClass = (RootClass) holder.getPersistentClass(); + final var rootClass = (RootClass) holder.getPersistentClass(); if ( toMany || entityBinder.wrapIdsInEmbeddedComponents() ) { // If an XxxToMany, it has to be wrapped today. // This poses a problem as the PK is the class instead of the @@ -372,7 +363,7 @@ private void bindId(Property property) { } else { rootClass.setIdentifierProperty( property ); - final MappedSuperclass superclass = + final var superclass = getMappedSuperclassOrNull( declaringClass, inheritanceStatePerClass, buildingContext ); setDeclaredIdentifier( rootClass, superclass, property ); } @@ -415,13 +406,13 @@ private Component getOrCreateCompositeId(RootClass rootClass) { private Class resolveCustomInstantiator( MemberDetails property, ClassDetails embeddableClass) { - final org.hibernate.annotations.EmbeddableInstantiator onEmbedded = + final var onEmbedded = property.getDirectAnnotationUsage( org.hibernate.annotations.EmbeddableInstantiator.class ); if ( onEmbedded != null ) { return onEmbedded.value(); } - final org.hibernate.annotations.EmbeddableInstantiator onEmbeddable = + final var onEmbeddable = embeddableClass.getDirectAnnotationUsage( org.hibernate.annotations.EmbeddableInstantiator.class ); if ( onEmbeddable != null ) { return onEmbeddable.value(); @@ -506,7 +497,7 @@ private void handleOptional(Property property) { private void handleNaturalId(Property property) { if ( memberDetails != null && entityBinder != null ) { - final NaturalId naturalId = memberDetails.getDirectAnnotationUsage( NaturalId.class ); + final var naturalId = memberDetails.getDirectAnnotationUsage( NaturalId.class ); if ( naturalId != null ) { if ( !entityBinder.isRootEntity() ) { throw new AnnotationException( "Property '" + qualify( holder.getPath(), name ) @@ -527,7 +518,7 @@ private void inferOptimisticLocking(Property property) { property.setOptimisticLocked( collection.isOptimisticLocked() ); } else if ( memberDetails != null && memberDetails.hasDirectAnnotationUsage( OptimisticLock.class ) ) { - final OptimisticLock optimisticLock = memberDetails.getDirectAnnotationUsage( OptimisticLock.class ); + final var optimisticLock = memberDetails.getDirectAnnotationUsage( OptimisticLock.class ); final boolean excluded = optimisticLock.excluded(); validateOptimisticLock( excluded ); property.setOptimisticLocked( !excluded ); @@ -539,7 +530,7 @@ else if ( memberDetails != null && memberDetails.hasDirectAnnotationUsage( Optim private void validateAnnotationsAgainstType() { if ( memberDetails != null ) { - final TypeDetails type = memberDetails.getType(); + final var type = memberDetails.getType(); if ( !(type instanceof ArrayTypeDetails) ) { checkAnnotation( OrderColumn.class, List.class ); if ( memberDetails.hasDirectAnnotationUsage( OrderBy.class ) @@ -599,7 +590,7 @@ static int addElementsOfClass( PropertyContainer propertyContainer, MetadataBuildingContext context, int idPropertyCounter) { - for ( MemberDetails property : propertyContainer.propertyIterator() ) { + for ( var property : propertyContainer.propertyIterator() ) { idPropertyCounter = addProperty( propertyContainer, property, elements, context, idPropertyCounter ); } return idPropertyCounter; @@ -611,11 +602,11 @@ private static int addProperty( List inFlightPropertyDataList, MetadataBuildingContext context, int idPropertyCounter) { - final InFlightMetadataCollector collector = context.getMetadataCollector(); + final var collector = context.getMetadataCollector(); // see if inFlightPropertyDataList already contains a PropertyData for this name, // and if so, skip it... - for ( PropertyData propertyData : inFlightPropertyDataList ) { + for ( var propertyData : inFlightPropertyDataList ) { if ( propertyData.getPropertyName().equals( property.resolveAttributeName() ) ) { checkIdProperty( property, propertyData, context.getBootstrapContext().getModelsContext() ); // EARLY EXIT!!! @@ -623,9 +614,9 @@ private static int addProperty( } } - final TypeVariableScope ownerType = propertyContainer.getTypeAtStake(); + final var ownerType = propertyContainer.getTypeAtStake(); - final PropertyData propertyAnnotatedElement = new PropertyInferredData( + final var propertyAnnotatedElement = new PropertyInferredData( propertyContainer.getDeclaringClass(), ownerType, property, @@ -635,7 +626,7 @@ private static int addProperty( // put element annotated by @Id in front, since it has to be parsed // before any association by Hibernate - final MemberDetails element = propertyAnnotatedElement.getAttributeMember(); + final var element = propertyAnnotatedElement.getAttributeMember(); if ( hasIdAnnotation( element ) ) { inFlightPropertyDataList.add( idPropertyCounter, propertyAnnotatedElement ); if ( hasToOneAnnotation( element ) ) { @@ -655,9 +646,9 @@ private static int addProperty( private static void checkIdProperty(MemberDetails property, PropertyData propertyData, ModelsContext context) { final boolean incomingIdProperty = hasIdAnnotation( property ); - final MemberDetails attributeMember = propertyData.getAttributeMember(); - final boolean existingIdProperty = hasIdAnnotation( attributeMember ); if ( incomingIdProperty ) { + final var memberDetails = propertyData.getAttributeMember(); + final boolean existingIdProperty = hasIdAnnotation( memberDetails ); if ( existingIdProperty ) { if ( property.hasDirectAnnotationUsage( GeneratedValue.class ) || !property.getMetaAnnotated( IdGeneratorType.class, context ).isEmpty() ) { @@ -666,9 +657,9 @@ private static void checkIdProperty(MemberDetails property, PropertyData propert // generator, but for now we don't seem to be able to detect // that case here throw new AnnotationException( - "Attribute '" + attributeMember.getName() + "Attribute '" + memberDetails.getName() + "' is declared as an '@Id' or '@EmbeddedId' property by '" - + attributeMember.getDeclaringType().getName() + + memberDetails.getDeclaringType().getName() + "' and so '" + property.getDeclaringType().getName() + "' may not respecify the generation strategy" ); } @@ -679,8 +670,8 @@ private static void checkIdProperty(MemberDetails property, PropertyData propert // as an @Id field, but for now we don't seem to be able // to detect that case here throw new AnnotationException( - "Attribute '" + attributeMember.getName() - + "' is declared by '" + attributeMember.getDeclaringType().getName() + "Attribute '" + memberDetails.getName() + + "' is declared by '" + memberDetails.getDeclaringType().getName() + "' and may not be redeclared as an '@Id' or '@EmbeddedId' by '" + property.getDeclaringType().getName() + "'" ); } @@ -704,15 +695,16 @@ public static void processElementAnnotations( boolean isComponentEmbedded, boolean inSecondPass, MetadataBuildingContext context, - Map inheritanceStatePerClass) throws MappingException { + Map inheritanceStatePerClass) + throws MappingException { if ( !alreadyProcessedBySuper( propertyHolder, inferredData, entityBinder ) ) { // inSecondPass can only be used to apply right away the second pass of a composite-element // Because it's a value type, there is no bidirectional association, hence second pass // ordering does not matter - final MemberDetails property = inferredData.getAttributeMember(); - if ( property.hasDirectAnnotationUsage( Parent.class ) ) { - handleParentProperty( propertyHolder, inferredData, property ); + final var memberDetails = inferredData.getAttributeMember(); + if ( memberDetails.hasDirectAnnotationUsage( Parent.class ) ) { + handleParentProperty( propertyHolder, inferredData, memberDetails ); } else { //prepare PropertyBinder @@ -757,20 +749,20 @@ private static void buildProperty( MetadataBuildingContext context, Map inheritanceStatePerClass) { - final MemberDetails property = inferredData.getAttributeMember(); + final var memberDetails = inferredData.getAttributeMember(); if ( isPropertyOfRegularEmbeddable( propertyHolder, isComponentEmbedded ) - && property.hasDirectAnnotationUsage(Id.class)) { - throw new AnnotationException("Member '" + property.getName() + && memberDetails.hasDirectAnnotationUsage( Id.class ) ) { + throw new AnnotationException("Member '" + memberDetails.getName() + "' of embeddable class " + propertyHolder.getClassName() + " is annotated '@Id'"); } - final TypeDetails attributeTypeDetails = + final var attributeTypeDetails = inferredData.getAttributeMember().isPlural() ? inferredData.getAttributeMember().getType() : inferredData.getClassOrElementType(); - final PropertyBinder propertyBinder = propertyBinder( + final var propertyBinder = propertyBinder( propertyHolder, inferredData, entityBinder, @@ -780,16 +772,16 @@ private static void buildProperty( attributeTypeDetails ); - final LazyGroup lazyGroupAnnotation = property.getDirectAnnotationUsage( LazyGroup.class ); + final var lazyGroupAnnotation = memberDetails.getDirectAnnotationUsage( LazyGroup.class ); if ( lazyGroupAnnotation != null ) { propertyBinder.setLazyGroup( lazyGroupAnnotation.value() ); } - final ColumnsBuilder columnsBuilder = - new ColumnsBuilder( propertyHolder, nullability, property, inferredData, entityBinder, context ) + final var columnsBuilder = + new ColumnsBuilder( propertyHolder, nullability, memberDetails, inferredData, entityBinder, context ) .extractMetadata(); - final AnnotatedJoinColumns joinColumns = columnsBuilder.getJoinColumns(); - final AnnotatedColumns columns = propertyBinder.bindProperty( + final var joinColumns = columnsBuilder.getJoinColumns(); + final var columns = propertyBinder.bindProperty( propertyHolder, nullability, inferredData, @@ -800,7 +792,7 @@ private static void buildProperty( attributeTypeDetails.determineRawClass(), columnsBuilder ); - addNaturalIds( inSecondPass, property, columns, joinColumns, context ); + addNaturalIds( inSecondPass, memberDetails, columns, joinColumns, context ); } private static PropertyBinder propertyBinder( @@ -811,13 +803,13 @@ private static PropertyBinder propertyBinder( MetadataBuildingContext context, Map inheritanceStatePerClass, TypeDetails attributeTypeDetails) { - final MemberDetails property = inferredData.getAttributeMember(); - final PropertyBinder propertyBinder = new PropertyBinder(); + final var memberDetails = inferredData.getAttributeMember(); + final var propertyBinder = new PropertyBinder(); propertyBinder.setName( inferredData.getPropertyName() ); propertyBinder.setReturnedClassName( inferredData.getTypeName() ); propertyBinder.setAccessType( inferredData.getDefaultAccess() ); propertyBinder.setHolder( propertyHolder ); - propertyBinder.setMemberDetails( property ); + propertyBinder.setMemberDetails( memberDetails ); propertyBinder.setReturnedClass( attributeTypeDetails ); propertyBinder.setBuildingContext( context ); if ( isIdentifierMapper ) { @@ -827,7 +819,7 @@ private static PropertyBinder propertyBinder( propertyBinder.setDeclaringClass( inferredData.getDeclaringClass() ); propertyBinder.setEntityBinder( entityBinder ); propertyBinder.setInheritanceStatePerClass( inheritanceStatePerClass ); - propertyBinder.setId( !entityBinder.isIgnoreIdAnnotations() && hasIdAnnotation( property ) ); + propertyBinder.setId( !entityBinder.isIgnoreIdAnnotations() && hasIdAnnotation( memberDetails ) ); return propertyBinder; } @@ -847,7 +839,7 @@ private AnnotatedColumns bindProperty( boolean inSecondPass, ClassDetails returnedClass, ColumnsBuilder columnsBuilder) { - final MemberDetails property = inferredData.getAttributeMember(); + final var property = inferredData.getAttributeMember(); if ( isVersion( property ) ) { bindVersionProperty( propertyHolder, @@ -950,15 +942,15 @@ private void bindVersionProperty( boolean isIdentifierMapper, AnnotatedColumns columns) { checkVersionProperty( propertyHolder, isIdentifierMapper ); - final RootClass rootClass = (RootClass) propertyHolder.getPersistentClass(); + final var rootClass = (RootClass) propertyHolder.getPersistentClass(); setColumns( columns ); - final Property property = makePropertyValueAndBind(); + final var property = makePropertyValueAndBind(); getBasicValueBinder().setVersion( true ); rootClass.setVersion( property ); //If version is on a mapped superclass, update the mapping - final ClassDetails declaringClass = inferredData.getDeclaringClass(); - final MappedSuperclass mappedSuperclass = + final var declaringClass = inferredData.getDeclaringClass(); + final var mappedSuperclass = getMappedSuperclassOrNull( declaringClass, inheritanceStatePerClass, buildingContext ); if ( mappedSuperclass != null ) { // Don't overwrite an existing version property @@ -1000,24 +992,24 @@ private AnnotatedColumns bindBasicOrComposite( ColumnsBuilder columnsBuilder, AnnotatedColumns columns, ClassDetails returnedClass) { - final MemberDetails property = inferredData.getAttributeMember(); + final var memberDetails = inferredData.getAttributeMember(); // overrides from @MapsId or @IdClass if needed final PropertyData overridingProperty = - overridingProperty( propertyHolder, isIdentifierMapper, property ); + overridingProperty( propertyHolder, isIdentifierMapper, memberDetails ); final AnnotatedColumns actualColumns; final boolean isComposite; if ( overridingProperty != null ) { setReferencedEntityName( overridingProperty.getClassOrElementName() ); actualColumns = columnsBuilder.overrideColumnFromMapperOrMapsIdProperty( overridingProperty ); - isComposite = isComposite( property, returnedClass, overridingProperty ); + isComposite = isComposite( memberDetails, returnedClass, overridingProperty ); } else { actualColumns = columns; - isComposite = isEmbedded( property, returnedClass ); + isComposite = isEmbedded( memberDetails, returnedClass ); } - final PropertyBinder propertyBinder = propertyBinder( + final var propertyBinder = propertyBinder( propertyHolder, nullability, inferredData, @@ -1045,9 +1037,9 @@ private PropertyData overridingProperty( boolean isIdentifierMapper, MemberDetails property) { if ( isIdentifierMapper - || isId - || propertyHolder.isOrWithinEmbeddedId() - || propertyHolder.isInIdClass() ) { + || isId + || propertyHolder.isOrWithinEmbeddedId() + || propertyHolder.isInIdClass() ) { // the associated entity could be using an @IdClass making the overridden property a component return getPropertyOverriddenByMapperOrMapsId( isId, @@ -1074,13 +1066,12 @@ private PropertyBinder propertyBinder( AnnotatedColumns actualColumns, PropertyData overridingProperty) { - final Class> compositeUserType = - resolveCompositeUserType( inferredData, buildingContext ); + final var compositeUserType = resolveCompositeUserType( inferredData, buildingContext ); - final MemberDetails property = inferredData.getAttributeMember(); + final var memberDetails = inferredData.getAttributeMember(); if ( isComposite || compositeUserType != null ) { - if ( property.isArray() && property.getElementType() != null - && isEmbedded( property, property.getElementType() ) ) { + if ( memberDetails.isArray() && memberDetails.getElementType() != null + && isEmbedded( memberDetails, memberDetails.getElementType() ) ) { // This is a special kind of basic aggregate component array type aggregateBinder( propertyHolder, @@ -1088,7 +1079,7 @@ && isEmbedded( property, property.getElementType() ) ) { entityBinder, isIdentifierMapper, isComponentEmbedded, - property, + memberDetails, columns, returnedClass, compositeUserType, @@ -1104,7 +1095,7 @@ && isEmbedded( property, property.getElementType() ) ) { isComponentEmbedded, buildingContext, inheritanceStatePerClass, - property, + memberDetails, actualColumns, returnedClass, isId(), @@ -1114,8 +1105,8 @@ && isEmbedded( property, property.getElementType() ) ) { ); } } - else if ( property.isPlural() && property.getElementType() != null - && isEmbedded( property, property.getElementType() ) ) { + else if ( memberDetails.isPlural() && memberDetails.getElementType() != null + && isEmbedded( memberDetails, memberDetails.getElementType() ) ) { // This is a special kind of basic aggregate component array type aggregateBinder( propertyHolder, @@ -1123,9 +1114,9 @@ && isEmbedded( property, property.getElementType() ) ) { entityBinder, isIdentifierMapper, isComponentEmbedded, - property, + memberDetails, columns, - property.getElementType().determineRawClass(), + memberDetails.getElementType().determineRawClass(), null, actualColumns ); @@ -1135,7 +1126,7 @@ && isEmbedded( property, property.getElementType() ) ) { propertyHolder, inferredData, nullability, - property, + memberDetails, actualColumns ); } @@ -1202,16 +1193,15 @@ private boolean isComposite( MemberDetails property, ClassDetails returnedClass, PropertyData overridingProperty) { - final InheritanceState state = - inheritanceStatePerClass.get( overridingProperty.getClassOrElementType().determineRawClass() ); + final var state = inheritanceStatePerClass.get( overridingProperty.getClassOrElementType().determineRawClass() ); return state != null ? state.hasIdClassOrEmbeddedId() : isEmbedded( property, returnedClass ); } private void handleGeneratorsForOverriddenId( PropertyHolder propertyHolder, PropertyData mapsIdProperty) { - final SimpleValue idValue = (SimpleValue) getValue(); - final RootClass rootClass = propertyHolder.getPersistentClass().getRootClass(); + final var idValue = (SimpleValue) getValue(); + final var rootClass = propertyHolder.getPersistentClass().getRootClass(); final String propertyName = mapsIdProperty.getPropertyName(); final String entityName = rootClass.getEntityName(); idValue.setCustomIdGeneratorCreator( creationContext -> @@ -1277,7 +1267,7 @@ private boolean shouldForceNotNull(Nullability nullability, boolean optional) { * The intention is really whether non-optional is explicit */ private static boolean isExplicitlyOptional(MemberDetails attributeMember) { - final Basic basic = attributeMember.getDirectAnnotationUsage( Basic.class ); + final var basic = attributeMember.getDirectAnnotationUsage( Basic.class ); // things are optional (nullable) by default. // If there is no annotation, that cannot be altered return basic == null || basic.optional(); @@ -1288,7 +1278,7 @@ private static boolean isExplicitlyOptional(MemberDetails attributeMember) { * whether it is primitive? */ public static boolean isOptional(MemberDetails attributeMember, PropertyHolder propertyHolder) { - final Basic basic = attributeMember.getDirectAnnotationUsage( Basic.class ); + final var basic = attributeMember.getDirectAnnotationUsage( Basic.class ); if ( basic != null ) { return basic.optional() && attributeMember.getType().getTypeKind() != TypeDetails.Kind.PRIMITIVE; @@ -1308,26 +1298,25 @@ else if ( attributeMember.isPlural() ) { } private static boolean isLazy(MemberDetails property) { - final Basic annotationUsage = property.getDirectAnnotationUsage( Basic.class ); + final var annotationUsage = property.getDirectAnnotationUsage( Basic.class ); return annotationUsage != null && annotationUsage.fetch() == LAZY; } private static Class> resolveCompositeUserType( PropertyData inferredData, MetadataBuildingContext buildingContext) { - final ModelsContext modelsContext = buildingContext.getBootstrapContext().getModelsContext(); + final var modelsContext = buildingContext.getBootstrapContext().getModelsContext(); - final MemberDetails attributeMember = inferredData.getAttributeMember(); - final TypeDetails classOrElementType = inferredData.getClassOrElementType(); - final ClassDetails returnedClass = classOrElementType.determineRawClass(); + final var attributeMember = inferredData.getAttributeMember(); + final var classOrElementType = inferredData.getClassOrElementType(); + final var returnedClass = classOrElementType.determineRawClass(); if ( attributeMember != null ) { - final CompositeType compositeType = - attributeMember.locateAnnotationUsage( CompositeType.class, modelsContext ); + final var compositeType = attributeMember.locateAnnotationUsage( CompositeType.class, modelsContext ); if ( compositeType != null ) { return compositeType.value(); } - final Class> compositeUserType = + final var compositeUserType = resolveTimeZoneStorageCompositeUserType( attributeMember, returnedClass, buildingContext ); if ( compositeUserType != null ) { return compositeUserType; @@ -1335,7 +1324,7 @@ private static Class> resolveCompositeUserType( } if ( returnedClass != null ) { - final Class embeddableClass = returnedClass.toJavaClass(); + final var embeddableClass = returnedClass.toJavaClass(); if ( embeddableClass != null ) { return buildingContext.getMetadataCollector().findRegisteredCompositeUserType( embeddableClass ); } @@ -1349,15 +1338,15 @@ private static PropertyData getPropertyOverriddenByMapperOrMapsId( PropertyHolder propertyHolder, String propertyName, MetadataBuildingContext buildingContext) { - final ClassDetailsRegistry classDetailsRegistry = + final var classDetailsRegistry = buildingContext.getBootstrapContext().getModelsContext().getClassDetailsRegistry(); final PersistentClass persistentClass = propertyHolder.getPersistentClass(); final String name = StringHelper.isEmpty( persistentClass.getClassName() ) ? persistentClass.getEntityName() : persistentClass.getClassName(); - final ClassDetails classDetails = classDetailsRegistry.resolveClassDetails( name ); - final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector(); + final var classDetails = classDetailsRegistry.resolveClassDetails( name ); + final var metadataCollector = buildingContext.getMetadataCollector(); if ( propertyHolder.isInIdClass() ) { final PropertyData data = metadataCollector.getPropertyAnnotatedWithIdAndToOne( classDetails, propertyName ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyContainer.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyContainer.java index 8b28a84b4f72..3c7618404c11 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyContainer.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyContainer.java @@ -22,14 +22,11 @@ import org.hibernate.boot.jaxb.Origin; import org.hibernate.boot.jaxb.SourceType; import org.hibernate.boot.spi.AccessType; -import org.hibernate.internal.util.StringHelper; -import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.models.spi.ClassDetails; import org.hibernate.models.spi.FieldDetails; import org.hibernate.models.spi.MemberDetails; import org.hibernate.models.spi.MethodDetails; import org.hibernate.models.spi.RecordComponentDetails; -import org.hibernate.models.spi.TypeDetails; import org.hibernate.models.spi.TypeVariableScope; @@ -41,6 +38,9 @@ import jakarta.persistence.OneToOne; import jakarta.persistence.Transient; +import static org.hibernate.internal.util.StringHelper.qualify; +import static org.hibernate.internal.util.collections.CollectionHelper.toSmallList; + /** * Access to the members of a {@linkplain ClassDetails class} which define a persistent attribute * as defined by the JPA specification and AccessType. @@ -90,15 +90,12 @@ private static List resolveAttributeMembers( ClassDetails classDetails, TypeVariableScope typeAtStake, AccessType classLevelAccessType) { - final List fields = collectPotentialAttributeMembers( classDetails.getFields() ); - final List getters = collectPotentialAttributeMembers( classDetails.getMethods() ); - final List recordComponents = collectPotentialAttributeMembers( classDetails.getRecordComponents() ); + final var fields = collectPotentialAttributeMembers( classDetails.getFields() ); + final var getters = collectPotentialAttributeMembers( classDetails.getMethods() ); + final var recordComponents = collectPotentialAttributeMembers( classDetails.getRecordComponents() ); - final Map attributeMemberMap = buildAttributeMemberMap( - recordComponents, - fields, - getters - ); + final Map attributeMemberMap = + buildAttributeMemberMap( recordComponents, fields, getters ); final Map persistentAttributesFromGetters = new HashMap<>(); final Map persistentAttributesFromComponents = new HashMap<>(); @@ -169,46 +166,40 @@ private static void collectPersistentAttributesUsingLocalAccessType( // Check fields... for ( int i = 0; i < fields.size(); i++ ) { - final FieldDetails fieldDetails = fields.get( i ); - final Access localAccessAnnotation = fieldDetails.getDirectAnnotationUsage( Access.class ); - if ( localAccessAnnotation == null - || localAccessAnnotation.value() != jakarta.persistence.AccessType.FIELD ) { - continue; + final var fieldDetails = fields.get( i ); + final var localAccessAnnotation = fieldDetails.getDirectAnnotationUsage( Access.class ); + if ( localAccessAnnotation != null + && localAccessAnnotation.value() == jakarta.persistence.AccessType.FIELD ) { + persistentAttributeMap.put( fieldDetails.getName(), fieldDetails ); } - persistentAttributeMap.put( fieldDetails.getName(), fieldDetails ); } // Check getters... for ( int i = 0; i < getters.size(); i++ ) { - final MethodDetails getterDetails = getters.get( i ); - final Access localAccessAnnotation = getterDetails.getDirectAnnotationUsage( Access.class ); - if ( localAccessAnnotation == null - || localAccessAnnotation.value() != jakarta.persistence.AccessType.PROPERTY ) { - continue; - } - - final String name = getterDetails.resolveAttributeName(); - - // HHH-10242 detect registration of the same property getter twice - eg boolean isId() + UUID getId() - final MethodDetails previous = persistentAttributesFromGetters.get( name ); - if ( previous != null ) { - throwAmbiguousPropertyException( classDetails, previous, getterDetails ); + final var getterDetails = getters.get( i ); + final var localAccessAnnotation = getterDetails.getDirectAnnotationUsage( Access.class ); + if ( localAccessAnnotation != null + && localAccessAnnotation.value() == jakarta.persistence.AccessType.PROPERTY ) { + final String name = getterDetails.resolveAttributeName(); + // HHH-10242 detect registration of the same property getter twice - eg boolean isId() + UUID getId() + final var previous = persistentAttributesFromGetters.get( name ); + if ( previous != null ) { + throwAmbiguousPropertyException( classDetails, previous, getterDetails ); + } + persistentAttributeMap.put( name, getterDetails ); + persistentAttributesFromGetters.put( name, getterDetails ); } - persistentAttributeMap.put( name, getterDetails ); - persistentAttributesFromGetters.put( name, getterDetails ); } // Check record components... for ( int i = 0; i < recordComponents.size(); i++ ) { - final RecordComponentDetails componentDetails = recordComponents.get( i ); - final Access localAccessAnnotation = componentDetails.getDirectAnnotationUsage( Access.class ); - if ( localAccessAnnotation == null ) { - continue; + final var recordComponentDetails = recordComponents.get( i ); + if ( recordComponentDetails.hasDirectAnnotationUsage( Access.class ) ) { + final String name = recordComponentDetails.getName(); + persistentAttributeMap.put( name, recordComponentDetails ); + persistentAttributesFromComponents.put( name, recordComponentDetails ); } - final String name = componentDetails.getName(); - persistentAttributeMap.put( name, componentDetails ); - persistentAttributesFromComponents.put( name, componentDetails ); } } @@ -302,30 +293,25 @@ private static List verifyAndInitializePersistentAttributes( TypeVariableScope typeAtStake, Map attributeMemberMap) { final ArrayList output = new ArrayList<>( attributeMemberMap.size() ); - for ( MemberDetails attributeMemberDetails : attributeMemberMap.values() ) { - final TypeDetails memberType = attributeMemberDetails.resolveRelativeType( typeAtStake ); - if ( !memberType.isResolved() - && !discoverTypeWithoutReflection( classDetails, attributeMemberDetails ) ) { - final String msg = "Property '" + StringHelper.qualify( classDetails.getName(), attributeMemberDetails.getName() ) + + for ( var attributeMemberDetails : attributeMemberMap.values() ) { + if ( !attributeMemberDetails.resolveRelativeType( typeAtStake ).isResolved() + && !discoverTypeWithoutReflection( attributeMemberDetails ) ) { + final String msg = "Property '" + qualify( classDetails.getName(), attributeMemberDetails.getName() ) + "' has an unbound type and no explicit target entity (resolve this generics usage issue" + " or set an explicit target attribute with '@OneToMany(target=)' or use an explicit '@Type')"; throw new AnnotationException( msg ); } output.add( attributeMemberDetails ); } - return CollectionHelper.toSmallList( output ); + return toSmallList( output ); } private AccessType determineLocalClassDefinedAccessStrategy() { - AccessType classDefinedAccessType = AccessType.DEFAULT; - final Access access = classDetails.getDirectAnnotationUsage( Access.class ); - if ( access != null ) { - classDefinedAccessType = AccessType.getAccessStrategy( access.value() ); - } - return classDefinedAccessType; + final var access = classDetails.getDirectAnnotationUsage( Access.class ); + return access == null ? AccessType.DEFAULT : AccessType.getAccessStrategy( access.value() ); } - private static boolean discoverTypeWithoutReflection(ClassDetails classDetails, MemberDetails memberDetails) { + private static boolean discoverTypeWithoutReflection(MemberDetails memberDetails) { if ( memberDetails.hasDirectAnnotationUsage( TargetEmbeddable.class ) ) { return true; } @@ -342,22 +328,22 @@ private static boolean discoverTypeWithoutReflection(ClassDetails classDetails, return true; } - final OneToOne oneToOneAnn = memberDetails.getDirectAnnotationUsage( OneToOne.class ); + final var oneToOneAnn = memberDetails.getDirectAnnotationUsage( OneToOne.class ); if ( oneToOneAnn != null ) { return oneToOneAnn.targetEntity() != void.class; } - final OneToMany oneToManyAnn = memberDetails.getDirectAnnotationUsage( OneToMany.class ); + final var oneToManyAnn = memberDetails.getDirectAnnotationUsage( OneToMany.class ); if ( oneToManyAnn != null ) { return oneToManyAnn.targetEntity() != void.class; } - final ManyToOne manyToOneAnn = memberDetails.getDirectAnnotationUsage( ManyToOne.class ); + final var manyToOneAnn = memberDetails.getDirectAnnotationUsage( ManyToOne.class ); if ( manyToOneAnn != null ) { return manyToOneAnn.targetEntity() != void.class; } - final ManyToMany manyToManyAnn = memberDetails.getDirectAnnotationUsage( ManyToMany.class ); + final var manyToManyAnn = memberDetails.getDirectAnnotationUsage( ManyToMany.class ); if ( manyToManyAnn != null ) { return manyToManyAnn.targetEntity() != void.class; } @@ -366,7 +352,7 @@ private static boolean discoverTypeWithoutReflection(ClassDetails classDetails, return true; } - final ManyToAny manToAnyAnn = memberDetails.getDirectAnnotationUsage( ManyToAny.class ); + final var manToAnyAnn = memberDetails.getDirectAnnotationUsage( ManyToAny.class ); if ( manToAnyAnn != null ) { return true; } @@ -387,6 +373,7 @@ private static boolean discoverTypeWithoutReflection(ClassDetails classDetails, private static boolean mustBeSkipped(MemberDetails memberDetails) { //TODO make those hardcoded tests more portable (through the bytecode provider?) return memberDetails.hasDirectAnnotationUsage( Transient.class ) - || (memberDetails.getType() != null && "net.sf.cglib.transform.impl.InterceptFieldCallback".equals( memberDetails.getType().getName() ) ); + || memberDetails.getType() != null + && "net.sf.cglib.transform.impl.InterceptFieldCallback".equals( memberDetails.getType().getName() ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyInferredData.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyInferredData.java index f2f3d3ce0870..9072e3528c4e 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyInferredData.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyInferredData.java @@ -16,7 +16,6 @@ import org.hibernate.models.internal.ClassTypeDetailsImpl; import org.hibernate.models.internal.dynamic.DynamicClassDetails; import org.hibernate.models.spi.ClassDetails; -import org.hibernate.models.spi.ClassDetailsRegistry; import org.hibernate.models.spi.MemberDetails; import org.hibernate.models.spi.ModelsContext; import org.hibernate.models.spi.TypeDetails; @@ -66,7 +65,7 @@ public AccessType getDefaultAccess() throws MappingException { AccessType jpaAccessType = AccessType.DEFAULT; - Access access = propertyMember.getDirectAnnotationUsage( Access.class ); + final var access = propertyMember.getDirectAnnotationUsage( Access.class ); if ( access != null ) { jpaAccessType = AccessType.getAccessStrategy( access.value() ); } @@ -84,11 +83,11 @@ public String getPropertyName() throws MappingException { @Override public TypeDetails getPropertyType() throws MappingException { - final org.hibernate.boot.internal.Target targetAnnotation = propertyMember.getDirectAnnotationUsage( org.hibernate.boot.internal.Target.class ); - final ModelsContext sourceModelContext = buildingContext.getBootstrapContext().getModelsContext(); + final var sourceModelContext = buildingContext.getBootstrapContext().getModelsContext(); + final var targetAnnotation = propertyMember.getDirectAnnotationUsage( org.hibernate.boot.internal.Target.class ); if ( targetAnnotation != null ) { final String targetName = targetAnnotation.value(); - final ClassDetails classDetails = ModelsHelper.resolveClassDetails( + final var classDetails = ModelsHelper.resolveClassDetails( targetName, sourceModelContext.getClassDetailsRegistry(), () -> new DynamicClassDetails( targetName, sourceModelContext ) @@ -96,7 +95,7 @@ public TypeDetails getPropertyType() throws MappingException { return new ClassTypeDetailsImpl( classDetails, Kind.CLASS ); } - final TargetEmbeddable targetEmbeddable = getTargetEmbeddableAnnotation( propertyMember ); + final var targetEmbeddable = getTargetEmbeddableAnnotation( propertyMember ); if ( targetEmbeddable != null ) { return resolveTargetEmbeddableAnnotation( targetEmbeddable, sourceModelContext ); } @@ -106,7 +105,7 @@ public TypeDetails getPropertyType() throws MappingException { private static TargetEmbeddable getTargetEmbeddableAnnotation(MemberDetails memberDetails) { // first we look for the annotation on the member itself - final TargetEmbeddable memberAnnotation = memberDetails.getDirectAnnotationUsage( TargetEmbeddable.class ); + final var memberAnnotation = memberDetails.getDirectAnnotationUsage( TargetEmbeddable.class ); if ( memberAnnotation != null ) { // this should only be allowed for embedded or collections-of-embeddables. // NOTE: this is tricky to check for collections-of-embeddables as it @@ -137,18 +136,19 @@ private static TargetEmbeddable getTargetEmbeddableAnnotation(MemberDetails memb private static ClassTypeDetailsImpl resolveTargetEmbeddableAnnotation( TargetEmbeddable targetEmbeddable, ModelsContext sourceModelContext) { - final ClassDetailsRegistry classDetailsRegistry = sourceModelContext.getClassDetailsRegistry(); - final ClassDetails targetClassDetails = classDetailsRegistry.resolveClassDetails( targetEmbeddable.value().getName() ); + final var targetClassDetails = + sourceModelContext.getClassDetailsRegistry() + .resolveClassDetails( targetEmbeddable.value().getName() ); return new ClassTypeDetailsImpl( targetClassDetails, Kind.CLASS ); } @Override public TypeDetails getClassOrElementType() throws MappingException { - final ModelsContext modelsContext = buildingContext.getBootstrapContext().getModelsContext(); - final org.hibernate.boot.internal.Target annotationUsage = propertyMember.getDirectAnnotationUsage( org.hibernate.boot.internal.Target.class ); + final var modelsContext = buildingContext.getBootstrapContext().getModelsContext(); + final var annotationUsage = propertyMember.getDirectAnnotationUsage( org.hibernate.boot.internal.Target.class ); if ( annotationUsage != null ) { final String targetName = annotationUsage.value(); - final ClassDetails classDetails = ModelsHelper.resolveClassDetails( + final var classDetails = ModelsHelper.resolveClassDetails( targetName, modelsContext.getClassDetailsRegistry(), () -> new DynamicClassDetails( targetName, modelsContext ) @@ -156,7 +156,7 @@ public TypeDetails getClassOrElementType() throws MappingException { return new ClassTypeDetailsImpl( classDetails, Kind.CLASS ); } - final TargetEmbeddable targetEmbeddable = getTargetEmbeddableAnnotation(propertyMember); + final var targetEmbeddable = getTargetEmbeddableAnnotation(propertyMember); if ( targetEmbeddable != null ) { return resolveTargetEmbeddableAnnotation( targetEmbeddable, modelsContext ); } @@ -166,22 +166,22 @@ public TypeDetails getClassOrElementType() throws MappingException { @Override public ClassDetails getClassOrPluralElement() throws MappingException { - final org.hibernate.boot.internal.Target xmlTarget = propertyMember.getDirectAnnotationUsage( org.hibernate.boot.internal.Target.class ); + final var xmlTarget = propertyMember.getDirectAnnotationUsage( org.hibernate.boot.internal.Target.class ); if ( xmlTarget != null ) { - return buildingContext.getMetadataCollector().getClassDetailsRegistry().getClassDetails( xmlTarget.value() ); + return buildingContext.getMetadataCollector().getClassDetailsRegistry() + .getClassDetails( xmlTarget.value() ); } - final TargetEmbeddable targetEmbeddable = getTargetEmbeddableAnnotation(propertyMember); + final var targetEmbeddable = getTargetEmbeddableAnnotation( propertyMember ); if ( targetEmbeddable != null ) { final String targetName = targetEmbeddable.value().getName(); - return buildingContext.getMetadataCollector().getClassDetailsRegistry().getClassDetails( targetName ); + return buildingContext.getMetadataCollector().getClassDetailsRegistry() + .getClassDetails( targetName ); } - if ( propertyMember.isPlural() ) { - return propertyMember.getElementType().determineRawClass(); - } - - return propertyMember.getAssociatedType().determineRawClass(); + return propertyMember.isPlural() + ? propertyMember.getElementType().determineRawClass() + : propertyMember.getAssociatedType().determineRawClass(); } @Override @@ -204,5 +204,4 @@ public ClassDetails getDeclaringClass() { return declaringClass; } - } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/QueryBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/QueryBinder.java index 95fbccca00ea..112bbca4c707 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/QueryBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/QueryBinder.java @@ -23,9 +23,6 @@ import org.hibernate.boot.internal.NamedHqlQueryDefinitionImpl; import org.hibernate.boot.internal.NamedProcedureCallDefinitionImpl; import org.hibernate.boot.models.JpaAnnotations; -import org.hibernate.boot.models.annotations.internal.NamedStoredProcedureQueryJpaAnnotation; -import org.hibernate.boot.models.annotations.internal.QueryHintJpaAnnotation; -import org.hibernate.boot.models.annotations.internal.StoredProcedureParameterJpaAnnotation; import org.hibernate.boot.query.NamedHqlQueryDefinition; import org.hibernate.boot.query.NamedNativeQueryDefinition; import org.hibernate.boot.query.NamedProcedureCallDefinition; @@ -47,6 +44,7 @@ import java.util.List; import java.util.function.Supplier; +import static java.lang.Character.isWhitespace; import static org.hibernate.internal.CoreLogging.messageLogger; import static org.hibernate.internal.util.StringHelper.nullIfEmpty; import static org.hibernate.internal.util.collections.ArrayHelper.isEmpty; @@ -73,7 +71,7 @@ public static void bindQuery( if ( namedQuery != null ) { final String queryName = namedQuery.name(); final String queryString = namedQuery.query(); - final Class resultClass = namedQuery.resultClass(); + final var resultClass = namedQuery.resultClass(); if ( queryName.isBlank() ) { throw new AnnotationException( @@ -85,15 +83,16 @@ public static void bindQuery( queryString.replace( '\n', ' ' ) ); } - final QueryHintDefinition hints = new QueryHintDefinition( queryName, namedQuery.hints() ); - final NamedHqlQueryDefinition queryMapping = + final var hints = new QueryHintDefinition( queryName, namedQuery.hints() ); + final var queryMapping = createNamedQueryDefinition( queryName, queryString, resultClass, hints.determineLockOptions( namedQuery ), hints, annotationTarget ); + final var collector = context.getMetadataCollector(); if ( isDefault ) { - context.getMetadataCollector().addDefaultQuery( queryMapping ); + collector.addDefaultQuery( queryMapping ); } else { - context.getMetadataCollector().addNamedQuery( queryMapping ); + collector.addNamedQuery( queryMapping ); } } } @@ -121,37 +120,38 @@ public static void bindNativeQuery( MetadataBuildingContext context, AnnotationTarget location, boolean isDefault) { - if ( namedNativeQuery == null ) { - return; - } + if ( namedNativeQuery != null ) { + final String registrationName = namedNativeQuery.name(); + final String queryString = namedNativeQuery.query(); - final String registrationName = namedNativeQuery.name(); - final String queryString = namedNativeQuery.query(); - - if ( registrationName.isBlank() ) { - throw new AnnotationException( "Class or package level '@NamedNativeQuery' annotation must specify a 'name'" ); - } + if ( registrationName.isBlank() ) { + throw new AnnotationException( + "Class or package level '@NamedNativeQuery' annotation must specify a 'name'" ); + } - final QueryHintDefinition hints = new QueryHintDefinition( registrationName, namedNativeQuery.hints() ); + final var hints = new QueryHintDefinition( registrationName, namedNativeQuery.hints() ); - final String resultSetMappingName = namedNativeQuery.resultSetMapping(); - final Class resultClassDetails = namedNativeQuery.resultClass(); - final Class resultClass = void.class == resultClassDetails ? null : resultClassDetails; + final String resultSetMappingName = namedNativeQuery.resultSetMapping(); + final var resultClassDetails = namedNativeQuery.resultClass(); + final var resultClass = void.class == resultClassDetails ? null : resultClassDetails; - final NamedNativeQueryDefinition queryDefinition = - createNamedQueryDefinition( registrationName, queryString, resultClass, resultSetMappingName, hints, location ); + final var queryDefinition = + createNamedQueryDefinition( registrationName, queryString, resultClass, resultSetMappingName, hints, + location ); - if ( LOG.isTraceEnabled() ) { - LOG.tracef( "Binding named native query '%s' to [%s]", - queryDefinition.getRegistrationName(), - queryDefinition.getSqlQueryString().replace( '\n', ' ' ) ); - } + if ( LOG.isTraceEnabled() ) { + LOG.tracef( "Binding named native query '%s' to [%s]", + queryDefinition.getRegistrationName(), + queryDefinition.getSqlQueryString().replace( '\n', ' ' ) ); + } - if ( isDefault ) { - context.getMetadataCollector().addDefaultNamedNativeQuery( queryDefinition ); - } - else { - context.getMetadataCollector().addNamedNativeQuery( queryDefinition ); + final var collector = context.getMetadataCollector(); + if ( isDefault ) { + collector.addDefaultNamedNativeQuery( queryDefinition ); + } + else { + collector.addNamedNativeQuery( queryDefinition ); + } } } @@ -195,7 +195,7 @@ public static void bindNativeQuery( ); } - final SqlResultSetMapping resultSetMapping = sqlSelect.resultSetMapping(); + final var resultSetMapping = sqlSelect.resultSetMapping(); if ( !isEmpty( resultSetMapping.columns() ) || !isEmpty( resultSetMapping.entities() ) || !isEmpty( resultSetMapping.classes() ) ) { @@ -211,36 +211,35 @@ public static void bindNativeQuery( org.hibernate.annotations.NamedNativeQuery namedNativeQuery, MetadataBuildingContext context, AnnotationTarget location) { - if ( namedNativeQuery == null ) { - return; - } + if ( namedNativeQuery != null ) { + final String registrationName = namedNativeQuery.name(); - final String registrationName = namedNativeQuery.name(); - - if ( registrationName.isBlank() ) { - throw new AnnotationException( "Class or package level '@NamedNativeQuery' annotation must specify a 'name'" ); - } + if ( registrationName.isBlank() ) { + throw new AnnotationException( + "Class or package level '@NamedNativeQuery' annotation must specify a 'name'" ); + } - final String resultSetMappingName = namedNativeQuery.resultSetMapping(); - final Class resultClassDetails = namedNativeQuery.resultClass(); - final Class resultClass = resultClassDetails == void.class ? null : resultClassDetails; + final String resultSetMappingName = namedNativeQuery.resultSetMapping(); + final var resultClassDetails = namedNativeQuery.resultClass(); + final var resultClass = resultClassDetails == void.class ? null : resultClassDetails; - final String[] querySpacesList = namedNativeQuery.querySpaces(); - final HashSet querySpaces = new HashSet<>( determineProperSizing( querySpacesList.length ) ); - Collections.addAll( querySpaces, querySpacesList ); + final String[] querySpacesList = namedNativeQuery.querySpaces(); + final HashSet querySpaces = new HashSet<>( determineProperSizing( querySpacesList.length ) ); + Collections.addAll( querySpaces, querySpacesList ); - final NamedNativeQueryDefinition.Builder builder = - createQueryDefinition( namedNativeQuery, registrationName, resultSetMappingName, resultClass, - namedNativeQuery.timeout(), namedNativeQuery.fetchSize(), querySpaces, location ); - final NamedNativeQueryDefinition queryDefinition = builder.build(); - if ( LOG.isTraceEnabled() ) { - LOG.tracef( - "Binding named native query '%' to [%s]", - queryDefinition.getRegistrationName(), - queryDefinition.getSqlQueryString().replace( '\n', ' ' ) - ); + final var builder = + createQueryDefinition( namedNativeQuery, registrationName, resultSetMappingName, resultClass, + namedNativeQuery.timeout(), namedNativeQuery.fetchSize(), querySpaces, location ); + final var queryDefinition = builder.build(); + if ( LOG.isTraceEnabled() ) { + LOG.tracef( + "Binding named native query '%' to [%s]", + queryDefinition.getRegistrationName(), + queryDefinition.getSqlQueryString().replace( '\n', ' ' ) + ); + } + context.getMetadataCollector().addNamedNativeQuery( queryDefinition ); } - context.getMetadataCollector().addNamedNativeQuery( queryDefinition ); } private static NamedNativeQueryDefinition.Builder createQueryDefinition( @@ -281,37 +280,34 @@ public static NamedProcedureCallDefinition createStoredProcedure( } final JdbcCall jdbcCall = parseJdbcCall( sqlString, exceptionProducer ); - final ModelsContext modelsContext = context.getBootstrapContext().getModelsContext(); - final NamedStoredProcedureQueryJpaAnnotation nameStoredProcedureQueryAnn = - JpaAnnotations.NAMED_STORED_PROCEDURE_QUERY.createUsage( modelsContext ); - nameStoredProcedureQueryAnn.name( builder.getName() ); - nameStoredProcedureQueryAnn.procedureName( jdbcCall.callableName ); - nameStoredProcedureQueryAnn.parameters( parametersAsAnnotations( builder, context, jdbcCall ) ); + final var modelsContext = context.getBootstrapContext().getModelsContext(); + final var nameStoredProcedureQuery = JpaAnnotations.NAMED_STORED_PROCEDURE_QUERY.createUsage( modelsContext ); + nameStoredProcedureQuery.name( builder.getName() ); + nameStoredProcedureQuery.procedureName( jdbcCall.callableName ); + nameStoredProcedureQuery.parameters( parametersAsAnnotations( builder, context, jdbcCall ) ); final String resultSetMappingName = builder.getResultSetMappingName(); if ( resultSetMappingName != null ) { - nameStoredProcedureQueryAnn.resultSetMappings( new String[] {resultSetMappingName} ); + nameStoredProcedureQuery.resultSetMappings( new String[] {resultSetMappingName} ); } - final Class resultClass = builder.getResultClass(); + final var resultClass = builder.getResultClass(); if ( resultClass != null ) { - nameStoredProcedureQueryAnn.resultClasses( new Class[]{ builder.getResultClass() } ); + nameStoredProcedureQuery.resultClasses( new Class[]{ builder.getResultClass() } ); } - final List hints = hintsAsAnnotations( builder, modelsContext, jdbcCall ); - nameStoredProcedureQueryAnn.hints( hints.toArray(QueryHint[]::new) ); + final var hints = hintsAsAnnotations( builder, modelsContext, jdbcCall ); + nameStoredProcedureQuery.hints( hints.toArray(QueryHint[]::new) ); - return new NamedProcedureCallDefinitionImpl( nameStoredProcedureQueryAnn ); + return new NamedProcedureCallDefinitionImpl( nameStoredProcedureQuery ); } private static StoredProcedureParameter[] parametersAsAnnotations( NamedNativeQueryDefinition.Builder builder, MetadataBuildingContext context, JdbcCall jdbcCall) { - final ModelsContext modelsContext = context.getBootstrapContext().getModelsContext(); - final StoredProcedureParameter[] parameters = - new StoredProcedureParameter[jdbcCall.parameters.size()]; + final var modelsContext = context.getBootstrapContext().getModelsContext(); + final var parameters = new StoredProcedureParameter[jdbcCall.parameters.size()]; for ( int i = 0; i < jdbcCall.parameters.size(); i++ ) { - final StoredProcedureParameterJpaAnnotation param = - JpaAnnotations.STORED_PROCEDURE_PARAMETER.createUsage( modelsContext ); + final var param = JpaAnnotations.STORED_PROCEDURE_PARAMETER.createUsage( modelsContext ); parameters[i] = param; final String paramName = jdbcCall.parameters.get( i ); @@ -319,7 +315,7 @@ private static StoredProcedureParameter[] parametersAsAnnotations( param.mode( ParameterMode.IN ); final String typeName = builder.getParameterTypes().get( paramName ); - final ClassDetails classDetails = + final var classDetails = isEmpty( typeName ) ? ClassDetails.VOID_CLASS_DETAILS : classDetails( context, typeName ); @@ -332,16 +328,14 @@ private static List hintsAsAnnotations( NamedNativeQueryDefinition.Builder builder, ModelsContext modelsContext, JdbcCall jdbcCall) { final List hints = new ArrayList<>(); if ( builder.getQuerySpaces() != null ) { - final QueryHintJpaAnnotation hint = - JpaAnnotations.QUERY_HINT.createUsage( modelsContext ); + final var hint = JpaAnnotations.QUERY_HINT.createUsage( modelsContext ); hint.name( HibernateHints.HINT_NATIVE_SPACES ); hint.value( String.join( " ", builder.getQuerySpaces() ) ); hints.add( hint ); } if ( jdbcCall.resultParameter ) { // Mark native queries that have a result parameter as callable functions - final QueryHintJpaAnnotation hint = - JpaAnnotations.QUERY_HINT.createUsage( modelsContext ); + final var hint = JpaAnnotations.QUERY_HINT.createUsage( modelsContext ); hint.name( HibernateHints.HINT_CALLABLE_FUNCTION ); hint.value( "true" ); hints.add( hint ); @@ -378,17 +372,17 @@ public static void bindQuery( } final String registrationName = namedQuery.name(); - final Class resultClass = namedQuery.resultClass(); + final var resultClass = namedQuery.resultClass(); if ( registrationName.isBlank() ) { throw new AnnotationException( "Class or package level '@NamedQuery' annotation must specify a 'name'" ); } - final NamedHqlQueryDefinition.Builder builder = + final var builder = createQueryDefinition( namedQuery, registrationName, resultClass, namedQuery.timeout(), namedQuery.fetchSize(), location ) ; - final NamedHqlQueryDefinitionImpl hqlQueryDefinition = builder.build(); + final var hqlQueryDefinition = builder.build(); if ( LOG.isTraceEnabled() ) { LOG.tracef( "Binding named query '%s' to [%s]", @@ -446,13 +440,13 @@ public static void bindNamedStoredProcedureQuery( throw new AnnotationException( "Class or package level '@NamedStoredProcedureQuery' annotation must specify a 'name'" ); } - final NamedProcedureCallDefinitionImpl definition = - new NamedProcedureCallDefinitionImpl( namedStoredProcedureQuery ); + final var definition = new NamedProcedureCallDefinitionImpl( namedStoredProcedureQuery ); + final var collector = context.getMetadataCollector(); if ( isDefault ) { - context.getMetadataCollector().addDefaultNamedProcedureCall( definition ); + collector.addDefaultNamedProcedureCall( definition ); } else { - context.getMetadataCollector().addNamedProcedureCallDefinition( definition ); + collector.addNamedProcedureCallDefinition( definition ); } LOG.tracef( "Bound named stored procedure query: %s => %s", definition.getRegistrationName(), @@ -507,7 +501,7 @@ private static JdbcCall parseJdbcCall(String sqlString, Supplier hintsMap = mapOfSize( hints.length ); - for ( QueryHint hint : hints ) { + for ( var hint : hints ) { hintsMap.put( hint.name(), hint.value() ); } this.hintsMap = hintsMap; @@ -138,8 +138,7 @@ public FlushMode getFlushMode() { } public LockMode getLockMode(String query) { - String hitName = HibernateHints.HINT_NATIVE_LOCK_MODE; - String value =(String) hintsMap.get( hitName ); + final var value = (String) hintsMap.get( HibernateHints.HINT_NATIVE_LOCK_MODE ); if ( value == null ) { return null; } @@ -147,16 +146,13 @@ public LockMode getLockMode(String query) { return LockMode.fromExternalForm( value ); } catch ( MappingException e ) { - throw new AnnotationException( "Unknown LockMode in hint: " + query + ":" + hitName, e ); + throw new AnnotationException( "Unknown LockMode in hint: " + query + + ":" + HibernateHints.HINT_NATIVE_LOCK_MODE, e ); } } public LockOptions determineLockOptions(NamedQuery namedQueryAnnotation) { - final LockModeType lockModeType = namedQueryAnnotation.lockMode(); - final Integer lockTimeoutHint = specLockTimeout(); - final Locking.FollowOn followOnStrategy = followOnStrategy(); - - return determineLockOptions( lockModeType, lockTimeoutHint, followOnStrategy ); + return determineLockOptions( namedQueryAnnotation.lockMode(), specLockTimeout(), followOnStrategy() ); } private Integer specLockTimeout() { @@ -174,25 +170,27 @@ private Locking.FollowOn followOnStrategy() { if ( strategyValue instanceof Locking.FollowOn strategy ) { return strategy; } - // assume it is a FollowOn name - return Locking.FollowOn.valueOf( strategyValue.toString() ); + else { + // assume it is a FollowOn name + return Locking.FollowOn.valueOf( strategyValue.toString() ); + } + } + else { + final Boolean lockingValue = getBooleanWrapper( HibernateHints.HINT_FOLLOW_ON_LOCKING ); + return Locking.FollowOn.fromLegacyValue( lockingValue ); } - - final Boolean lockingValue = getBooleanWrapper( HibernateHints.HINT_FOLLOW_ON_LOCKING ); - return Locking.FollowOn.fromLegacyValue( lockingValue ); } private LockOptions determineLockOptions( LockModeType lockModeType, Integer lockTimeoutHint, Locking.FollowOn followOnStrategy) { - LockOptions lockOptions = new LockOptions() + final var lockOptions = new LockOptions() .setLockMode( LockModeConverter.convertToLockMode( lockModeType ) ) .setFollowOnStrategy( followOnStrategy ); if ( lockTimeoutHint != null ) { lockOptions.setTimeout( Timeouts.interpretMilliSeconds( lockTimeoutHint ) ); } - return lockOptions; } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/SoftDeleteHelper.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/SoftDeleteHelper.java index 9ffff83268c5..9a67d40f0bff 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/SoftDeleteHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/SoftDeleteHelper.java @@ -9,8 +9,6 @@ import org.hibernate.boot.model.convert.internal.ConverterDescriptors; import org.hibernate.boot.model.convert.spi.ConverterDescriptor; import org.hibernate.boot.model.naming.Identifier; -import org.hibernate.boot.model.naming.PhysicalNamingStrategy; -import org.hibernate.boot.model.relational.Database; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.mapping.BasicValue; import org.hibernate.mapping.Column; @@ -46,11 +44,9 @@ public static void bindSoftDeleteIndicator( Table table, MetadataBuildingContext context) { assert softDeleteConfig != null; - - final BasicValue softDeleteIndicatorValue = createSoftDeleteIndicatorValue( softDeleteConfig, table, context ); final Column softDeleteIndicatorColumn = createSoftDeleteIndicatorColumn( softDeleteConfig, - softDeleteIndicatorValue, + createSoftDeleteIndicatorValue( softDeleteConfig, table, context ), context ); table.addColumn( softDeleteIndicatorColumn ); @@ -61,7 +57,7 @@ private static BasicValue createSoftDeleteIndicatorValue( SoftDelete softDeleteConfig, Table table, MetadataBuildingContext context) { - final BasicValue softDeleteIndicatorValue = new BasicValue( context, table ); + final var softDeleteIndicatorValue = new BasicValue( context, table ); softDeleteIndicatorValue.makeSoftDelete( softDeleteConfig.strategy() ); if ( softDeleteConfig.strategy() == SoftDeleteType.TIMESTAMP ) { @@ -78,7 +74,7 @@ private static BasicValue createSoftDeleteIndicatorValue( context.getBootstrapContext().getClassmateContext() ); softDeleteIndicatorValue.setJpaAttributeConverterDescriptor( converterDescriptor ); softDeleteIndicatorValue.setImplicitJavaTypeAccess( - (typeConfiguration) -> converterDescriptor.getRelationalValueResolvedType().getErasedType() + typeConfiguration -> converterDescriptor.getRelationalValueResolvedType().getErasedType() ); } @@ -89,7 +85,7 @@ private static Column createSoftDeleteIndicatorColumn( SoftDelete softDeleteConfig, BasicValue softDeleteIndicatorValue, MetadataBuildingContext context) { - final Column softDeleteColumn = new Column(); + final var softDeleteColumn = new Column(); softDeleteColumn.setValue( softDeleteIndicatorValue ); softDeleteIndicatorValue.addColumn( softDeleteColumn ); @@ -121,9 +117,9 @@ private static void applyColumnName( Column softDeleteColumn, SoftDelete softDeleteConfig, MetadataBuildingContext context) { - final Database database = context.getMetadataCollector().getDatabase(); - final PhysicalNamingStrategy namingStrategy = context.getBuildingOptions().getPhysicalNamingStrategy(); - // NOTE : the argument order is strange here - the fallback value comes first + final var database = context.getMetadataCollector().getDatabase(); + final var namingStrategy = context.getBuildingOptions().getPhysicalNamingStrategy(); + // NOTE: the argument order is strange here - the fallback value comes first final String logicalColumnName = coalesce( softDeleteConfig.strategy().getDefaultColumnName(), softDeleteConfig.columnName() @@ -140,10 +136,9 @@ public static SoftDeleteMappingImpl resolveSoftDeleteMapping( SoftDeletable bootMapping, String tableName, MappingModelCreationProcess creationProcess) { - if ( bootMapping.getSoftDeleteColumn() == null ) { - return null; - } - return new SoftDeleteMappingImpl( softDeletableModelPart, bootMapping, tableName, creationProcess ); + return bootMapping.getSoftDeleteColumn() == null + ? null + : new SoftDeleteMappingImpl( softDeletableModelPart, bootMapping, tableName, creationProcess ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/StrictIdGeneratorResolverSecondPass.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/StrictIdGeneratorResolverSecondPass.java index dd96071f4fb6..32f6283a853b 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/StrictIdGeneratorResolverSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/StrictIdGeneratorResolverSecondPass.java @@ -8,11 +8,7 @@ import org.hibernate.boot.models.annotations.internal.SequenceGeneratorJpaAnnotation; import org.hibernate.boot.models.annotations.internal.TableGeneratorJpaAnnotation; -import org.hibernate.boot.models.spi.GenericGeneratorRegistration; import org.hibernate.boot.models.spi.GlobalRegistrations; -import org.hibernate.boot.models.spi.SequenceGeneratorRegistration; -import org.hibernate.boot.models.spi.TableGeneratorRegistration; -import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.SimpleValue; @@ -57,11 +53,9 @@ private ModelsContext modelsContext() { @Override protected void handleUnnamedSequenceGenerator() { - final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector(); - // according to the spec, this should locate a generator with the same name as the entity-name - final SequenceGeneratorRegistration globalMatch = - metadataCollector.getGlobalRegistrations().getSequenceGeneratorRegistrations() + final var globalMatch = + getGlobalRegistrations().getSequenceGeneratorRegistrations() .get( entityMapping.getJpaEntityName() ); if ( globalMatch != null ) { handleSequenceGenerator( @@ -71,25 +65,23 @@ protected void handleUnnamedSequenceGenerator() { idMember, buildingContext ); - return; } - - handleSequenceGenerator( - entityMapping.getJpaEntityName(), - new SequenceGeneratorJpaAnnotation( modelsContext() ), - idValue, - idMember, - buildingContext - ); + else { + handleSequenceGenerator( + entityMapping.getJpaEntityName(), + new SequenceGeneratorJpaAnnotation( modelsContext() ), + idValue, + idMember, + buildingContext + ); + } } @Override protected void handleNamedSequenceGenerator() { - final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector(); - - final SequenceGeneratorRegistration globalMatch = - metadataCollector.getGlobalRegistrations() - .getSequenceGeneratorRegistrations().get( generatedValue.generator() ); + final var globalMatch = + getGlobalRegistrations().getSequenceGeneratorRegistrations() + .get( generatedValue.generator() ); if ( globalMatch != null ) { handleSequenceGenerator( generatedValue.generator(), @@ -98,24 +90,22 @@ protected void handleNamedSequenceGenerator() { idMember, buildingContext ); - return; } - - handleSequenceGenerator( - generatedValue.generator(), - new SequenceGeneratorJpaAnnotation( generatedValue.generator(), modelsContext() ), - idValue, - idMember, - buildingContext - ); + else { + handleSequenceGenerator( + generatedValue.generator(), + new SequenceGeneratorJpaAnnotation( generatedValue.generator(), modelsContext() ), + idValue, + idMember, + buildingContext + ); + } } @Override protected void handleUnnamedTableGenerator() { - final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector(); - - final TableGeneratorRegistration globalMatch = - metadataCollector.getGlobalRegistrations().getTableGeneratorRegistrations() + final var globalMatch = + getGlobalRegistrations().getTableGeneratorRegistrations() .get( entityMapping.getJpaEntityName() ); if ( globalMatch != null ) { handleTableGenerator( @@ -125,24 +115,22 @@ protected void handleUnnamedTableGenerator() { idMember, buildingContext ); - return; } - - handleTableGenerator( - entityMapping.getJpaEntityName(), - new TableGeneratorJpaAnnotation( modelsContext() ), - idValue, - idMember, - buildingContext - ); + else { + handleTableGenerator( + entityMapping.getJpaEntityName(), + new TableGeneratorJpaAnnotation( modelsContext() ), + idValue, + idMember, + buildingContext + ); + } } @Override protected void handleNamedTableGenerator() { - final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector(); - - final TableGeneratorRegistration globalMatch = - metadataCollector.getGlobalRegistrations().getTableGeneratorRegistrations() + final var globalMatch = + getGlobalRegistrations().getTableGeneratorRegistrations() .get( generatedValue.generator() ); if ( globalMatch != null ) { handleTableGenerator( @@ -152,17 +140,16 @@ protected void handleNamedTableGenerator() { idMember, buildingContext ); - - return; } - - handleTableGenerator( - generatedValue.generator(), - new TableGeneratorJpaAnnotation( generatedValue.generator(), modelsContext() ), - idValue, - idMember, - buildingContext - ); + else { + handleTableGenerator( + generatedValue.generator(), + new TableGeneratorJpaAnnotation( generatedValue.generator(), modelsContext() ), + idValue, + idMember, + buildingContext + ); + } } @Override @@ -176,11 +163,10 @@ protected void handleNamedAutoGenerator() { } private void handleAutoGenerator(String globalRegistrationName) { - final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector(); - final GlobalRegistrations globalRegistrations = metadataCollector.getGlobalRegistrations(); - final SequenceGeneratorRegistration globalSequenceMatch = - globalRegistrations.getSequenceGeneratorRegistrations().get( globalRegistrationName ); + final var globalSequenceMatch = + getGlobalRegistrations().getSequenceGeneratorRegistrations() + .get( globalRegistrationName ); if ( globalSequenceMatch != null ) { handleSequenceGenerator( globalRegistrationName, @@ -192,8 +178,9 @@ private void handleAutoGenerator(String globalRegistrationName) { return; } - final TableGeneratorRegistration globalTableMatch = - globalRegistrations.getTableGeneratorRegistrations().get( globalRegistrationName ); + final var globalTableMatch = + getGlobalRegistrations().getTableGeneratorRegistrations() + .get( globalRegistrationName ); if ( globalTableMatch != null ) { handleTableGenerator( globalRegistrationName, @@ -205,8 +192,9 @@ private void handleAutoGenerator(String globalRegistrationName) { return; } - final GenericGeneratorRegistration globalGenericMatch = - globalRegistrations.getGenericGeneratorRegistrations().get( globalRegistrationName ); + final var globalGenericMatch = + getGlobalRegistrations().getGenericGeneratorRegistrations() + .get( globalRegistrationName ); if ( globalGenericMatch != null ) { handleGenericGenerator( globalRegistrationName, @@ -223,8 +211,9 @@ private void handleAutoGenerator(String globalRegistrationName) { } // Implicit handling of UUID generation - if ( idMember.getType().isImplementor( UUID.class ) - || idMember.getType().isImplementor( String.class ) ) { + final var idMemberType = idMember.getType(); + if ( idMemberType.isImplementor( UUID.class ) + || idMemberType.isImplementor( String.class ) ) { handleUuidStrategy( idValue, idMember, @@ -247,4 +236,8 @@ private void handleAutoGenerator(String globalRegistrationName) { buildingContext ); } + + private GlobalRegistrations getGlobalRegistrations() { + return buildingContext.getMetadataCollector().getGlobalRegistrations(); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/TableBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/TableBinder.java index 8392cf29716a..b62c3d5e4542 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/TableBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/TableBinder.java @@ -145,7 +145,7 @@ public Table bind() { final boolean ownerEntityTableQuoted = isQuoted( ownerEntityTable ); final boolean associatedEntityTableQuoted = isQuoted( associatedEntityTable ); - final NamingStrategyHelper namingStrategyHelper = new NamingStrategyHelper() { + final var namingStrategyHelper = new NamingStrategyHelper() { @Override public Identifier determineImplicitName(final MetadataBuildingContext buildingContext) { final ImplicitNamingStrategy namingStrategy = buildingContext.getBuildingOptions().getImplicitNamingStrategy(); @@ -486,7 +486,7 @@ private static Table buildAndFillTable( MetadataBuildingContext buildingContext, String subselect, InFlightMetadataCollector.EntityTableXref denormalizedSuperTableXref) { - final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector(); + final var metadataCollector = buildingContext.getMetadataCollector(); final Table table = addTable( nullIfBlank( schema ), @@ -560,11 +560,11 @@ public static void bindForeignKey( associatedClass = destinationEntity; } else { - final PropertyHolder holder = joinColumns.getPropertyHolder(); + final var holder = joinColumns.getPropertyHolder(); associatedClass = holder == null ? null : holder.getPersistentClass(); } - final AnnotatedJoinColumn firstColumn = joinColumns.getJoinColumns().get(0); + final var firstColumn = joinColumns.getJoinColumns().get(0); if ( joinColumns.hasMappedBy() ) { // use the columns of the property referenced by mappedBy // copy them and link the copy to the actual value @@ -647,7 +647,7 @@ private static void bindPrimaryKeyReference( component.sortProperties(); } // works because the pk has to be on the primary table - final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector(); + final var metadataCollector = buildingContext.getMetadataCollector(); final Dialect dialect = metadataCollector.getDatabase().getJdbcEnvironment().getDialect(); for ( int j = 0; j < key.getColumnSpan(); j++ ) { if ( !matchUpJoinColumnsWithKeyColumns( referencedEntity, joinColumns, value, metadataCollector, dialect, j ) ) { @@ -734,7 +734,7 @@ private static void bindNonPrimaryKeyReference( else if ( value instanceof DependantValue ) { final String propertyName = joinColumns.getPropertyName(); if ( propertyName != null ) { - Collection collection = (Collection) referencedEntity.getRecursiveProperty( propertyName ).getValue(); + final var collection = (Collection) referencedEntity.getRecursiveProperty( propertyName ).getValue(); referencedPropertyName = collection.getReferencedPropertyName(); } else { diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/TimeZoneStorageHelper.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/TimeZoneStorageHelper.java index f747e3b4594f..ffb29ef6da97 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/TimeZoneStorageHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/TimeZoneStorageHelper.java @@ -13,7 +13,6 @@ import org.hibernate.models.spi.AnnotationTarget; import org.hibernate.models.spi.ClassDetails; import org.hibernate.models.spi.MemberDetails; -import org.hibernate.models.spi.TypeDetails; import org.hibernate.usertype.CompositeUserType; import org.hibernate.usertype.internal.OffsetDateTimeCompositeUserType; import org.hibernate.usertype.internal.OffsetTimeCompositeUserType; @@ -59,7 +58,7 @@ public static boolean isOffsetTimeClass(AnnotationTarget element) { } public static boolean isOffsetTimeClass(MemberDetails element) { - final TypeDetails type = element.getType(); + final var type = element.getType(); return type != null && isOffsetTimeClass( type.determineRawClass().getClassName() ); @@ -70,7 +69,7 @@ private static boolean isOffsetTimeClass(String returnedClassName) { } static boolean useColumnForTimeZoneStorage(AnnotationTarget element, MetadataBuildingContext context) { - final TimeZoneStorage timeZoneStorage = element.getDirectAnnotationUsage( TimeZoneStorage.class ); + final var timeZoneStorage = element.getDirectAnnotationUsage( TimeZoneStorage.class ); if ( timeZoneStorage == null ) { return element instanceof MemberDetails attributeMember && isTemporalWithTimeZoneClass( attributeMember.getType().getName() ) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ToOneBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ToOneBinder.java index 7a660ddd516d..ae411f2f5005 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ToOneBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ToOneBinder.java @@ -18,7 +18,6 @@ import org.hibernate.annotations.NotFoundAction; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; -import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.PropertyData; import org.hibernate.internal.CoreMessageLogger; @@ -27,9 +26,7 @@ import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.ToOne; import org.hibernate.models.spi.ClassDetails; -import org.hibernate.models.spi.ClassDetailsRegistry; import org.hibernate.models.spi.MemberDetails; -import org.hibernate.models.spi.ModelsContext; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -78,12 +75,12 @@ static void bindManyToOne( MetadataBuildingContext context, AnnotatedJoinColumns joinColumns, PropertyBinder propertyBinder) { - final MemberDetails property = inferredData.getAttributeMember(); - final ManyToOne manyToOne = property.getDirectAnnotationUsage( ManyToOne.class ); + final var memberDetails = inferredData.getAttributeMember(); + final var manyToOne = memberDetails.getDirectAnnotationUsage( ManyToOne.class ); //check validity - if ( property.hasDirectAnnotationUsage( Column.class ) - || property.hasDirectAnnotationUsage( Columns.class ) ) { + if ( memberDetails.hasDirectAnnotationUsage( Column.class ) + || memberDetails.hasDirectAnnotationUsage( Columns.class ) ) { throw new AnnotationException( "Property '" + getPath( propertyHolder, inferredData ) + "' is a '@ManyToOne' association and may not use '@Column' to specify column mappings (use '@JoinColumn' instead)" @@ -98,7 +95,7 @@ && isIdentifier( propertyHolder, propertyBinder, isIdentifierMapper ) ) { ); } - final Cascade hibernateCascade = property.getDirectAnnotationUsage( Cascade.class ); + final var hibernateCascade = memberDetails.getDirectAnnotationUsage( Cascade.class ); bindManyToOne( aggregateCascadeTypes( manyToOne.cascade(), hibernateCascade, false, context ), joinColumns, @@ -151,15 +148,15 @@ private static void bindManyToOne( boolean inSecondPass, PropertyBinder propertyBinder, MetadataBuildingContext context) { - final MemberDetails property = inferredData.getAttributeMember(); + final var memberDetails = inferredData.getAttributeMember(); - final NotFoundAction notFoundAction = notFoundAction( propertyHolder, property, fetchType ); - final OnDeleteAction onDeleteAction = onDeleteAction( property ); + final var notFoundAction = notFoundAction( propertyHolder, memberDetails, fetchType ); + final var onDeleteAction = onDeleteAction( memberDetails ); - final boolean optional = !isMandatory( explicitlyOptional, property, notFoundAction ); + final boolean optional = !isMandatory( explicitlyOptional, memberDetails, notFoundAction ); - final JoinTable joinTable = propertyHolder.getJoinTable( property ); - final org.hibernate.mapping.ManyToOne manyToOne = + final var joinTable = propertyHolder.getJoinTable( memberDetails ); + final var manyToOne = joinTable == null ? new org.hibernate.mapping.ManyToOne( context, joinColumns.getTable() ) : handleJoinTable( joinColumns, joinTable, notFoundAction, propertyHolder, inferredData, context ); @@ -168,9 +165,9 @@ private static void bindManyToOne( // This is a @OneToOne mapped to a physical o.h.mapping.ManyToOne manyToOne.markAsLogicalOneToOne(); } - final ClassDetails targetEntity = getTargetEntity( inferredData, context ); - manyToOne.setReferencedEntityName( getReferenceEntityName( inferredData, targetEntity ) ); - defineFetchingStrategy( manyToOne, property, inferredData, propertyHolder ); + final var targetEntityClassDetails = getTargetEntity( inferredData, context ); + manyToOne.setReferencedEntityName( getReferenceEntityName( inferredData, targetEntityClassDetails ) ); + defineFetchingStrategy( manyToOne, memberDetails, inferredData, propertyHolder ); //value.setFetchMode( fetchMode ); manyToOne.setNotFoundAction( notFoundAction ); manyToOne.setOnDeleteAction( onDeleteAction ); @@ -181,13 +178,13 @@ private static void bindManyToOne( } } - if ( property.hasDirectAnnotationUsage( MapsId.class ) ) { + if ( memberDetails.hasDirectAnnotationUsage( MapsId.class ) ) { // read-only for ( AnnotatedJoinColumn column : joinColumns.getJoinColumns() ) { column.setInsertable( false ); column.setUpdatable( false ); } - joinColumns.setMapsId( property.getDirectAnnotationUsage( MapsId.class ).value() ); + joinColumns.setMapsId( memberDetails.getDirectAnnotationUsage( MapsId.class ).value() ); } manyToOne.setTypeName( inferredData.getClassOrElementName() ); @@ -196,13 +193,13 @@ private static void bindManyToOne( final String fullPath = qualify( propertyHolder.getPath(), propertyName ); - bindForeignKeyNameAndDefinition( manyToOne, property, propertyHolder.getOverriddenForeignKey( fullPath ), context ); + bindForeignKeyNameAndDefinition( manyToOne, memberDetails, propertyHolder.getOverriddenForeignKey( fullPath ), context ); final FkSecondPass secondPass = new ToOneFkSecondPass( manyToOne, joinColumns, unique, - isTargetAnnotatedEntity( targetEntity, property ), + isTargetAnnotatedEntity( targetEntityClassDetails, memberDetails ), propertyHolder.getPersistentClass(), fullPath, context @@ -222,18 +219,18 @@ private static void bindManyToOne( isIdentifierMapper, propertyBinder, manyToOne, - property, + memberDetails, propertyName ); } private static OnDeleteAction onDeleteAction(MemberDetails property) { - final OnDelete onDelete = property.getDirectAnnotationUsage( OnDelete.class ); + final var onDelete = property.getDirectAnnotationUsage( OnDelete.class ); return onDelete == null ? null : onDelete.action(); } private static NotFoundAction notFoundAction(PropertyHolder propertyHolder, MemberDetails property, FetchType fetchType) { - final NotFound notFound = property.getDirectAnnotationUsage( NotFound.class ); + final var notFound = property.getDirectAnnotationUsage( NotFound.class ); final NotFoundAction notFoundAction = notFound == null ? null : notFound.action(); if ( notFoundAction != null && fetchType == LAZY ) { LOG.ignoreNotFoundWithFetchTypeLazy( propertyHolder.getEntityName(), property.getName() ); @@ -266,7 +263,7 @@ private static org.hibernate.mapping.ManyToOne handleJoinTable( } else { final Join join = propertyHolder.addJoin( joinTable, false ); - for ( AnnotatedJoinColumn joinColumn : joinColumns.getJoinColumns() ) { + for ( var joinColumn : joinColumns.getJoinColumns() ) { joinColumn.setExplicitTableName( join.getTable().getName() ); } if ( notFoundAction != null ) { @@ -278,7 +275,7 @@ private static org.hibernate.mapping.ManyToOne handleJoinTable( } static boolean isTargetAnnotatedEntity(ClassDetails targetEntity, MemberDetails property) { - final ClassDetails target = isDefault( targetEntity ) ? property.getType().determineRawClass() : targetEntity; + final var target = isDefault( targetEntity ) ? property.getType().determineRawClass() : targetEntity; return target.hasDirectAnnotationUsage( Entity.class ); } @@ -309,8 +306,8 @@ private static void processManyToOneProperty( propertyBinder.setMemberDetails( property ); propertyBinder.setToMany( true ); - final JoinColumn joinColumn = property.getDirectAnnotationUsage( JoinColumn.class ); - final JoinColumns joinColumns = property.getDirectAnnotationUsage( JoinColumns.class ); + final var joinColumn = property.getDirectAnnotationUsage( JoinColumn.class ); + final var joinColumns = property.getDirectAnnotationUsage( JoinColumns.class ); propertyBinder.makePropertyAndBind() .setOptional( optional && isNullable( joinColumns, joinColumn ) ); } @@ -320,7 +317,7 @@ private static boolean isNullable(JoinColumns joinColumns, JoinColumn joinColumn return joinColumn.nullable(); } else if ( joinColumns != null ) { - for ( JoinColumn column : joinColumns.value() ) { + for ( var column : joinColumns.value() ) { if ( column.nullable() ) { return true; } @@ -360,9 +357,9 @@ private static void handleFetchProfileOverrides( MemberDetails property, PropertyHolder propertyHolder, PropertyData inferredData) { - final MetadataBuildingContext context = toOne.getBuildingContext(); - final InFlightMetadataCollector collector = context.getMetadataCollector(); - final ModelsContext modelsContext = context.getBootstrapContext().getModelsContext(); + final var context = toOne.getBuildingContext(); + final var collector = context.getMetadataCollector(); + final var modelsContext = context.getBootstrapContext().getModelsContext(); property.forEachAnnotationUsage( FetchProfileOverride.class, modelsContext, usage -> collector.addSecondPass( new FetchSecondPass( usage, propertyHolder, inferredData.getPropertyName(), context ) )); } @@ -401,8 +398,8 @@ private static boolean isEager(MemberDetails property) { } private static FetchType getJpaFetchType(MemberDetails property) { - final ManyToOne manyToOne = property.getDirectAnnotationUsage( ManyToOne.class ); - final OneToOne oneToOne = property.getDirectAnnotationUsage( OneToOne.class ); + final var manyToOne = property.getDirectAnnotationUsage( ManyToOne.class ); + final var oneToOne = property.getDirectAnnotationUsage( OneToOne.class ); if ( manyToOne != null ) { return manyToOne.fetch(); } @@ -423,12 +420,12 @@ static void bindOneToOne( MetadataBuildingContext context, AnnotatedJoinColumns joinColumns, PropertyBinder propertyBinder) { - final MemberDetails property = inferredData.getAttributeMember(); - final OneToOne oneToOne = property.getDirectAnnotationUsage( OneToOne.class ); + final var memberDetails = inferredData.getAttributeMember(); + final var oneToOne = memberDetails.getDirectAnnotationUsage( OneToOne.class ); //check validity - if ( property.hasDirectAnnotationUsage( Column.class ) - || property.hasDirectAnnotationUsage( Columns.class ) ) { + if ( memberDetails.hasDirectAnnotationUsage( Column.class ) + || memberDetails.hasDirectAnnotationUsage( Columns.class ) ) { throw new AnnotationException( "Property '" + getPath( propertyHolder, inferredData ) + "' is a '@OneToOne' association and may not use '@Column' to specify column mappings" @@ -444,9 +441,9 @@ static void bindOneToOne( } //FIXME support a proper PKJCs - final boolean trueOneToOne = property.hasDirectAnnotationUsage( PrimaryKeyJoinColumn.class ) - || property.hasDirectAnnotationUsage( PrimaryKeyJoinColumns.class ); - final Cascade hibernateCascade = property.getDirectAnnotationUsage( Cascade.class ); + final boolean trueOneToOne = memberDetails.hasDirectAnnotationUsage( PrimaryKeyJoinColumn.class ) + || memberDetails.hasDirectAnnotationUsage( PrimaryKeyJoinColumns.class ); + final var hibernateCascade = memberDetails.getDirectAnnotationUsage( Cascade.class ); bindOneToOne( aggregateCascadeTypes( oneToOne.cascade(), hibernateCascade, oneToOne.orphanRemoval(), context ), joinColumns, @@ -523,19 +520,19 @@ private static void bindTrueOneToOne( MetadataBuildingContext context) { //is a true one-to-one //FIXME referencedColumnName ignored => ordering may fail. - final MemberDetails property = inferredData.getAttributeMember(); - final ClassDetails targetEntity = getTargetEntity( inferredData, context ); - final NotFoundAction notFoundAction = notFoundAction( propertyHolder, property, fetchMode ); - final OneToOneSecondPass secondPass = new OneToOneSecondPass( + final var memberDetails = inferredData.getAttributeMember(); + final var targetEntityClassDetails = getTargetEntity( inferredData, context ); + final var notFoundAction = notFoundAction( propertyHolder, memberDetails, fetchMode ); + final var secondPass = new OneToOneSecondPass( mappedBy, propertyHolder.getEntityName(), propertyHolder, inferredData, - getReferenceEntityName( inferredData, targetEntity ), - isTargetAnnotatedEntity( targetEntity, property ), + getReferenceEntityName( inferredData, targetEntityClassDetails ), + isTargetAnnotatedEntity( targetEntityClassDetails, memberDetails ), notFoundAction, - onDeleteAction( property ), - !isMandatory( explicitlyOptional, property, notFoundAction ), + onDeleteAction( memberDetails ), + !isMandatory( explicitlyOptional, memberDetails, notFoundAction ), cascadeStrategy, joinColumns, context @@ -591,8 +588,8 @@ public static void bindForeignKeyNameAndDefinition( value.disableForeignKey(); } else { - final JoinColumn joinColumn = property.getDirectAnnotationUsage( JoinColumn.class ); - final JoinColumns joinColumns = property.getDirectAnnotationUsage( JoinColumns.class ); + final var joinColumn = property.getDirectAnnotationUsage( JoinColumn.class ); + final var joinColumns = property.getDirectAnnotationUsage( JoinColumns.class ); final boolean noConstraintByDefault = context.getBuildingOptions().isNoConstraintByDefault(); if ( joinColumn != null && noConstraint( joinColumn.foreignKey(), noConstraintByDefault ) || joinColumns != null && noConstraint( joinColumns.foreignKey(), noConstraintByDefault ) ) { @@ -611,13 +608,13 @@ else if ( noConstraintByDefault ) { value.disableForeignKey(); } else if ( joinColumns != null ) { - final ForeignKey joinColumnsForeignKey = joinColumns.foreignKey(); + final var joinColumnsForeignKey = joinColumns.foreignKey(); value.setForeignKeyName( nullIfEmpty( joinColumnsForeignKey.name() ) ); value.setForeignKeyDefinition( nullIfEmpty( joinColumnsForeignKey.foreignKeyDefinition() ) ); value.setForeignKeyOptions( joinColumnsForeignKey.options() ); } else if ( joinColumn != null ) { - final ForeignKey joinColumnForeignKey = joinColumn.foreignKey(); + final var joinColumnForeignKey = joinColumn.foreignKey(); value.setForeignKeyName( nullIfEmpty( joinColumnForeignKey.name() ) ); value.setForeignKeyDefinition( nullIfEmpty( joinColumnForeignKey.foreignKeyDefinition() ) ); value.setForeignKeyOptions( joinColumnForeignKey.options() ); @@ -641,13 +638,13 @@ public static ClassDetails getTargetEntity(PropertyData propertyData, MetadataBu } private static ClassDetails getTargetEntityClass(MemberDetails property, MetadataBuildingContext context) { - final ClassDetailsRegistry classDetailsRegistry = + final var classDetailsRegistry = context.getBootstrapContext().getModelsContext().getClassDetailsRegistry(); - final ManyToOne manyToOne = property.getDirectAnnotationUsage( ManyToOne.class ); + final var manyToOne = property.getDirectAnnotationUsage( ManyToOne.class ); if ( manyToOne != null ) { return classDetailsRegistry.resolveClassDetails( manyToOne.targetEntity().getName() ); } - final OneToOne oneToOne = property.getDirectAnnotationUsage( OneToOne.class ); + final var oneToOne = property.getDirectAnnotationUsage( OneToOne.class ); if ( oneToOne != null ) { return classDetailsRegistry.resolveClassDetails( oneToOne.targetEntity().getName() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ToOneFkSecondPass.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ToOneFkSecondPass.java index 5082574699d0..9a945dad9130 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ToOneFkSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ToOneFkSecondPass.java @@ -7,13 +7,11 @@ import org.hibernate.AnnotationException; import org.hibernate.AssertionFailure; import org.hibernate.MappingException; -import org.hibernate.boot.spi.InFlightMetadataCollector; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.mapping.Component; import org.hibernate.mapping.ManyToOne; import org.hibernate.mapping.OneToOne; import org.hibernate.mapping.PersistentClass; -import org.hibernate.mapping.Property; import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.ToOne; @@ -70,9 +68,9 @@ public boolean isInPrimaryKey() { if ( entityClassName == null ) { return false; } - final PersistentClass persistentClass = + final var persistentClass = buildingContext.getMetadataCollector().getEntityBinding( entityClassName ); - final Property property = persistentClass.getIdentifierProperty(); + final var property = persistentClass.getIdentifierProperty(); if ( path == null ) { return false; } @@ -90,8 +88,9 @@ else if ( property != null) { localPath = path.substring( 3 ); } - for ( Property idProperty : component.getProperties() ) { - if ( localPath.equals( idProperty.getName() ) || localPath.startsWith( idProperty.getName() + "." ) ) { + for ( var idProperty : component.getProperties() ) { + if ( localPath.equals( idProperty.getName() ) + || localPath.startsWith( idProperty.getName() + "." ) ) { return true; } } @@ -106,7 +105,7 @@ public void doSecondPass(java.util.Map persistentClasse //TODO: move this validation logic to a separate ManyToOneSecondPass // for consistency with how this is handled for OneToOnes final String targetEntityName = manyToOne.getReferencedEntityName(); - final PersistentClass targetEntity = persistentClasses.get( targetEntityName ); + final var targetEntity = persistentClasses.get( targetEntityName ); if ( targetEntity == null ) { final String problem = annotatedEntity ? " which does not belong to the same persistence unit" @@ -159,7 +158,7 @@ private void handlePropertyRef( manyToOne.setReferenceToPrimaryKey( false ); final String entityName = targetEntity.getEntityName(); - final InFlightMetadataCollector metadataCollector = buildingContext.getMetadataCollector(); + final var metadataCollector = buildingContext.getMetadataCollector(); metadataCollector.addUniquePropertyReference( entityName, referencedPropertyName ); metadataCollector.addPropertyReferencedAssociation( entityName, path, referencedPropertyName ); } From eb9578c22dc35d724a7086471acac2bfe4dbe097 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Mon, 25 Aug 2025 10:13:09 +1000 Subject: [PATCH 3/5] use getRepeatedAnnotationUsages() since we have it now --- .../boot/model/internal/EntityBinder.java | 25 ++++++++++--------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java index fcb37e258222..983969d6df84 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java @@ -51,7 +51,6 @@ import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.StringHelper; -import org.hibernate.internal.util.collections.ArrayHelper; import org.hibernate.jdbc.Expectation; import org.hibernate.mapping.BasicValue; import org.hibernate.mapping.CheckConstraint; @@ -106,6 +105,8 @@ import static org.hibernate.boot.model.internal.PropertyBinder.hasIdAnnotation; import static org.hibernate.boot.model.internal.PropertyBinder.processElementAnnotations; import static org.hibernate.boot.model.internal.PropertyHolderBuilder.buildPropertyHolder; +import static org.hibernate.boot.model.internal.QueryBinder.bindNativeQuery; +import static org.hibernate.boot.model.internal.QueryBinder.bindQuery; import static org.hibernate.boot.model.internal.TableBinder.bindForeignKey; import static org.hibernate.boot.model.naming.Identifier.toIdentifier; import static org.hibernate.engine.OptimisticLockStyle.fromLockType; @@ -342,8 +343,7 @@ private void addCheckToEntity(Check check) { } private void callTypeBinders(PersistentClass persistentClass) { - final var metaAnnotatedList = annotatedClass.getMetaAnnotated( TypeBinderType.class, modelsContext() ); - for ( var metaAnnotated : metaAnnotatedList ) { + for ( var metaAnnotated : annotatedClass.getMetaAnnotated( TypeBinderType.class, modelsContext() ) ) { applyTypeBinder( metaAnnotated, persistentClass ); } } @@ -1157,13 +1157,14 @@ private static AnnotatedJoinColumns subclassJoinColumns( //@Inheritance(JOINED) subclass need to link back to the super entity final var joinColumns = new AnnotatedJoinColumns(); joinColumns.setBuildingContext( context ); - final var modelsContext = context.getBootstrapContext().getModelsContext(); - final var primaryKeyJoinColumns = - clazzToProcess.getAnnotationUsage( PrimaryKeyJoinColumns.class, modelsContext ); - if ( primaryKeyJoinColumns != null - && !ArrayHelper.isEmpty( primaryKeyJoinColumns.value() ) ) { - for ( var column : primaryKeyJoinColumns.value() ) { + if ( clazzToProcess.hasAnnotationUsage( PrimaryKeyJoinColumn.class, modelsContext ) ) { + final var columns = clazzToProcess.getRepeatedAnnotationUsages( PrimaryKeyJoinColumn.class, modelsContext ); + if ( columns.length == 0 ) { + // PrimaryKeyJoinColumns must not be empty according to Javadoc + throw new AnnotationException( "Empty '@PrimaryKeyJoinColumns' annotation" ); + } + for ( var column : columns ) { buildInheritanceJoinColumn( column, null, @@ -1175,7 +1176,7 @@ private static AnnotatedJoinColumns subclassJoinColumns( } else { buildInheritanceJoinColumn( - clazzToProcess.getAnnotationUsage( PrimaryKeyJoinColumn.class, modelsContext ), + null, null, superEntity.getIdentifier(), joinColumns, @@ -1424,14 +1425,14 @@ private void bindCustomSql() { if ( sqlSelect != null ) { final String loaderName = persistentClass.getEntityName() + "$SQLSelect"; persistentClass.setLoaderName( loaderName ); - QueryBinder.bindNativeQuery( loaderName, sqlSelect, annotatedClass, context ); + bindNativeQuery( loaderName, sqlSelect, annotatedClass, context ); } final var hqlSelect = annotatedClass.getAnnotationUsage( HQLSelect.class, modelsContext() ); if ( hqlSelect != null ) { final String loaderName = persistentClass.getEntityName() + "$HQLSelect"; persistentClass.setLoaderName( loaderName ); - QueryBinder.bindQuery( loaderName, hqlSelect, context ); + bindQuery( loaderName, hqlSelect, context ); } } From 7141ee92ce6a953a12e7057249c5a3b51d59bce0 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Mon, 25 Aug 2025 10:26:00 +1000 Subject: [PATCH 4/5] use 'var' in CallbackDefinitionResolver --- .../internal/CallbackDefinitionResolver.java | 29 +++++++------------ 1 file changed, 11 insertions(+), 18 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/jpa/event/internal/CallbackDefinitionResolver.java b/hibernate-core/src/main/java/org/hibernate/jpa/event/internal/CallbackDefinitionResolver.java index ddb960938184..474c0dc99118 100644 --- a/hibernate-core/src/main/java/org/hibernate/jpa/event/internal/CallbackDefinitionResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/jpa/event/internal/CallbackDefinitionResolver.java @@ -4,7 +4,6 @@ */ package org.hibernate.jpa.event.internal; -import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Target; import java.lang.reflect.Method; @@ -20,9 +19,7 @@ import org.hibernate.mapping.Component; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; -import org.hibernate.models.spi.AnnotationDescriptor; import org.hibernate.models.spi.ClassDetails; -import org.hibernate.models.spi.ClassDetailsRegistry; import org.hibernate.models.spi.MethodDetails; import org.hibernate.models.spi.ModelsContext; import org.hibernate.property.access.spi.Getter; @@ -223,7 +220,7 @@ private static List resolveEmbeddableCallbacks( static { //check whether reading annotations of annotations is useful or not useAnnotationAnnotatedByListener = false; - Target target = EntityListeners.class.getAnnotation( Target.class ); + final var target = EntityListeners.class.getAnnotation( Target.class ); if ( target != null ) { for ( ElementType type : target.value() ) { if ( type.equals( ElementType.ANNOTATION_TYPE ) ) { @@ -238,29 +235,25 @@ private static void applyListeners( ClassDetails currentClazz, List listOfListeners, ModelsContext sourceModelContext) { - final ClassDetailsRegistry classDetailsRegistry = sourceModelContext.getClassDetailsRegistry(); + final var classDetailsRegistry = sourceModelContext.getClassDetailsRegistry(); - final EntityListeners entityListeners = currentClazz.getDirectAnnotationUsage( EntityListeners.class ); + final var entityListeners = currentClazz.getDirectAnnotationUsage( EntityListeners.class ); if ( entityListeners != null ) { - final Class[] listeners = entityListeners.value(); - int size = listeners.length; + final var listenerClasses = entityListeners.value(); + int size = listenerClasses.length; for ( int index = size - 1; index >= 0; index-- ) { - listOfListeners.add( classDetailsRegistry.resolveClassDetails( listeners[index].getName() ) ); + listOfListeners.add( classDetailsRegistry.resolveClassDetails( listenerClasses[index].getName() ) ); } } if ( useAnnotationAnnotatedByListener ) { - final List metaAnnotatedUsageList = - currentClazz.getMetaAnnotated( EntityListeners.class, sourceModelContext ); - for ( Annotation metaAnnotatedUsage : metaAnnotatedUsageList ) { - final AnnotationDescriptor descriptor = + for ( var metaAnnotatedUsage : currentClazz.getMetaAnnotated( EntityListeners.class, sourceModelContext ) ) { + final var descriptor = sourceModelContext.getAnnotationDescriptorRegistry() .getDescriptor( metaAnnotatedUsage.getClass() ); - final EntityListeners metaAnnotatedListeners = - descriptor.getDirectAnnotationUsage( EntityListeners.class ); - final Class[] listeners = metaAnnotatedListeners.value(); - for ( int index = listeners.length - 1; index >= 0; index-- ) { - listOfListeners.add( classDetailsRegistry.resolveClassDetails( listeners[index].getName() ) ); + final var listenerClasses = descriptor.getDirectAnnotationUsage( EntityListeners.class ).value(); + for ( int index = listenerClasses.length - 1; index >= 0; index-- ) { + listOfListeners.add( classDetailsRegistry.resolveClassDetails( listenerClasses[index].getName() ) ); } } } From ed16b8a5b00bb222cb57d3d8fec803241c1ac82b Mon Sep 17 00:00:00 2001 From: Gavin King Date: Mon, 25 Aug 2025 14:18:33 +1000 Subject: [PATCH 5/5] further cleanups in boot.model.internal --- .../internal/AggregateComponentBinder.java | 4 +- .../boot/model/internal/BasicValueBinder.java | 7 +- .../boot/model/internal/BinderHelper.java | 67 ++++++------- .../boot/model/internal/EntityBinder.java | 46 ++++----- .../boot/model/internal/IdBagBinder.java | 95 ++++++++----------- .../IdBagIdGeneratorResolverSecondPass.java | 2 - .../boot/model/internal/ListBinder.java | 5 +- .../boot/model/internal/MapBinder.java | 3 +- .../boot/model/internal/PropertyBinder.java | 3 +- 9 files changed, 106 insertions(+), 126 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AggregateComponentBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AggregateComponentBinder.java index 5d38b8f64992..402966899281 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AggregateComponentBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/AggregateComponentBinder.java @@ -19,6 +19,8 @@ import org.hibernate.type.SqlTypes; import org.hibernate.type.descriptor.java.spi.EmbeddableAggregateJavaType; +import static org.hibernate.boot.model.internal.BasicValueBinder.Kind.ATTRIBUTE; + /** * Processes aggregate component annotations from Java classes and produces the Hibernate configuration-time metamodel, * that is, the objects defined in the package {@link org.hibernate.mapping}. @@ -51,7 +53,7 @@ public static void processAggregate( component.setStructColumnNames( determineStructAttributeNames( inferredData, componentClassDetails ) ); // Determine the aggregate column - final var basicValueBinder = new BasicValueBinder( BasicValueBinder.Kind.ATTRIBUTE, component, context ); + final var basicValueBinder = new BasicValueBinder( ATTRIBUTE, component, context ); basicValueBinder.setReturnedClassName( inferredData.getClassOrElementType().getName() ); basicValueBinder.setColumns( columns ); basicValueBinder.setPersistentClassName( propertyHolder.getClassName() ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BasicValueBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BasicValueBinder.java index e950c3256743..6f5b8d665703 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BasicValueBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BasicValueBinder.java @@ -293,11 +293,14 @@ private static JdbcType getDescriptor(TypeConfiguration typeConfiguration, int c return typeConfiguration.getJdbcTypeRegistry().getDescriptor( code ); } + public void setType(MemberDetails value, TypeDetails typeDetails) { + setType( value, typeDetails, null, null ); + } public void setType( MemberDetails value, TypeDetails typeDetails, - String declaringClassName, - @Nullable ConverterDescriptor converterDescriptor) { + @Nullable String declaringClassName, + @Nullable ConverterDescriptor converterDescriptor) { this.memberDetails = value; final boolean isArray = value.isArray(); if ( typeDetails == null && !isArray ) { diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BinderHelper.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BinderHelper.java index 9b21b6c74e08..182f84bac504 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BinderHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/BinderHelper.java @@ -4,7 +4,6 @@ */ package org.hibernate.boot.model.internal; -import jakarta.persistence.ConstraintMode; import jakarta.persistence.FetchType; import jakarta.persistence.ForeignKey; import jakarta.persistence.ManyToOne; @@ -37,7 +36,6 @@ import org.hibernate.mapping.Property; import org.hibernate.mapping.Selectable; import org.hibernate.mapping.SyntheticProperty; -import org.hibernate.mapping.Table; import org.hibernate.mapping.ToOne; import org.hibernate.mapping.Value; import org.hibernate.models.spi.AnnotationTarget; @@ -62,10 +60,11 @@ import static java.util.Collections.addAll; import static org.hibernate.boot.model.internal.AnnotatedColumn.buildColumnOrFormulaFromAnnotation; import static org.hibernate.boot.model.internal.AnyBinder.resolveImplicitDiscriminatorStrategy; +import static org.hibernate.boot.model.internal.BasicValueBinder.Kind.ANY_DISCRIMINATOR; +import static org.hibernate.boot.model.internal.BasicValueBinder.Kind.ANY_KEY; import static org.hibernate.boot.model.internal.ForeignKeyType.NON_PRIMARY_KEY_REFERENCE; import static org.hibernate.internal.log.DeprecationLogger.DEPRECATION_LOGGER; import static org.hibernate.internal.util.StringHelper.isEmpty; -import static org.hibernate.internal.util.StringHelper.isNotBlank; import static org.hibernate.internal.util.StringHelper.qualifier; import static org.hibernate.internal.util.StringHelper.qualify; import static org.hibernate.internal.util.collections.ArrayHelper.isEmpty; @@ -146,16 +145,15 @@ public static void createSyntheticPropertyReference( // figure out which table has the columns by looking // for a PersistentClass or Join in the hierarchy of // the target entity which has the first column - final AttributeContainer columnOwner = - findReferencedColumnOwner( targetEntity, joinColumns.getJoinColumns().get(0), context ); + final var firstJoinColumn = joinColumns.getJoinColumns().get( 0 ); + final var columnOwner = findReferencedColumnOwner( targetEntity, firstJoinColumn, context ); checkColumnInSameTable( joinColumns, targetEntity, associatedEntity, context, columnOwner ); // find all properties mapped to each column - final List properties = - findPropertiesByColumns( columnOwner, joinColumns, associatedEntity, context ); + final var properties = findPropertiesByColumns( columnOwner, joinColumns, associatedEntity, context ); // create a Property along with the new synthetic // Component if necessary (or reuse the existing // Property that matches exactly) - final Property property = referencedProperty( + final var property = referencedProperty( targetEntity, associatedEntity, propertyName, @@ -192,8 +190,8 @@ private static void checkColumnInSameTable( // we should only get called for owning side of association throw new AssertionFailure("no need to create synthetic properties for unowned collections"); } - for ( AnnotatedJoinColumn column: joinColumns.getJoinColumns() ) { - final AttributeContainer owner = findReferencedColumnOwner( targetEntity, column, context ); + for ( var column: joinColumns.getJoinColumns() ) { + final var owner = findReferencedColumnOwner( targetEntity, column, context ); if ( owner == null ) { throw new AnnotationException( "A '@JoinColumn' for association " + associationMessage( associatedEntity, joinColumns ) @@ -202,7 +200,7 @@ private static void checkColumnInSameTable( + targetEntity.getEntityName() + "'" ); } if ( owner != columnOwner) { - final AnnotatedJoinColumn firstColumn = joinColumns.getJoinColumns().get(0); + final var firstColumn = joinColumns.getJoinColumns().get(0); throw new AnnotationException( "The '@JoinColumn's for association " + associationMessage( associatedEntity, joinColumns ) + " reference columns of different tables mapped by the target entity '" @@ -241,7 +239,7 @@ private static Property referencedProperty( && ownerEntity == columnOwner && !( properties.get(0).getValue() instanceof ToOne ) ) { // no need to make a synthetic property - final Property property = properties.get( 0 ); + final var property = properties.get( 0 ); // mark it unique property.getValue().createUniqueKey( context ); return property; @@ -320,9 +318,9 @@ private static Property makeSyntheticComponentProperty( MetadataBuildingContext context, String syntheticPropertyName, List properties) { - final Component embeddedComponent = + final var embeddedComponent = embeddedComponent( ownerEntity, persistentClassOrJoin, context, properties ); - final Property result = new SyntheticProperty(); + final var result = new SyntheticProperty(); result.setName( syntheticPropertyName ); result.setPersistentClass( ownerEntity ); result.setUpdatable( false ); @@ -379,7 +377,7 @@ private static Property cloneProperty(PersistentClass ownerEntity, MetadataBuild copy.addProperty( cloneProperty( ownerEntity, context, subproperty ) ); } copy.sortProperties(); - final Property result = new SyntheticProperty(); + final var result = new SyntheticProperty(); result.setName( property.getName() ); result.setPersistentClass( ownerEntity ); result.setUpdatable( false ); @@ -389,7 +387,7 @@ private static Property cloneProperty(PersistentClass ownerEntity, MetadataBuild return result; } else { - final Property clone = shallowCopy( property ); + final var clone = shallowCopy( property ); clone.setInsertable( false ); clone.setUpdatable( false ); clone.setNaturalIdentifier( false ); @@ -403,7 +401,7 @@ private static Property cloneProperty(PersistentClass ownerEntity, MetadataBuild * and other attributes. */ public static Property shallowCopy(Property property) { - final Property clone = new SyntheticProperty(); + final var clone = new SyntheticProperty(); clone.setCascade( property.getCascade() ); clone.setInsertable( property.isInsertable() ); clone.setLazy( property.isLazy() ); @@ -425,13 +423,12 @@ private static List findPropertiesByColumns( PersistentClass associatedEntity, MetadataBuildingContext context) { - final Table referencedTable = columnOwner.getTable(); - // Build the list of column names in the exact order they were // specified by the @JoinColumn annotations. final List orderedColumns = new ArrayList<>( columns.getJoinColumns().size() ); final Map> columnsToProperty = new HashMap<>(); final var collector = context.getMetadataCollector(); + final var referencedTable = columnOwner.getTable(); for ( var joinColumn : columns.getJoinColumns() ) { if ( joinColumn.isReferenceImplicit() ) { throw new AnnotationException( "Association " + associationMessage( associatedEntity, columns ) @@ -439,7 +436,7 @@ private static List findPropertiesByColumns( + " (when an association has multiple '@JoinColumn's, they must each specify their 'referencedColumnName')"); } final String name = collector.getPhysicalColumnName( referencedTable, joinColumn.getReferencedColumn() ); - final Column column = new Column( name ); + final var column = new Column( name ); orderedColumns.add( column ); columnsToProperty.put( column, new LinkedHashSet<>() ); //need to use a LinkedHashSet here to make it deterministic } @@ -450,7 +447,7 @@ private static List findPropertiesByColumns( if ( columnOwner instanceof PersistentClass persistentClass ) { // Process ToOne associations after Components, Basic and Id properties final List toOneProperties = new ArrayList<>(); - for ( Property property : persistentClass.getReferenceableProperties() ) { + for ( var property : persistentClass.getReferenceableProperties() ) { if ( property.getValue() instanceof ToOne ) { toOneProperties.add( property ); } @@ -464,16 +461,16 @@ private static List findPropertiesByColumns( else { // special case for entities with multiple @Id properties final Component key = persistentClass.getIdentifierMapper(); - for ( Property p : key.getProperties() ) { + for ( var p : key.getProperties() ) { matchColumnsByProperty( p, columnsToProperty ); } } - for ( Property property : toOneProperties ) { + for ( var property : toOneProperties ) { matchColumnsByProperty( property, columnsToProperty ); } } else { - for ( Property property : ((Join) columnOwner).getProperties() ) { + for ( var property : ((Join) columnOwner).getProperties() ) { matchColumnsByProperty( property, columnsToProperty ); } } @@ -582,7 +579,7 @@ private static void matchColumnsByProperty(Property property, Map toAliasTableMap(SqlFragmentAlias[] aliases){ final Map result = new HashMap<>(); for ( var aliasAnnotation : aliases ) { final String table = aliasAnnotation.table(); - if ( isNotBlank( table ) ) { + if ( !table.isBlank() ) { result.put( aliasAnnotation.alias(), table ); } } @@ -903,7 +899,7 @@ public static EnumSet aggregateCascadeTypes( private static EnumSet convertToHibernateCascadeType(jakarta.persistence.CascadeType[] cascades) { final var cascadeTypes = EnumSet.noneOf( CascadeType.class ); if ( cascades != null ) { - for ( jakarta.persistence.CascadeType cascade: cascades ) { + for ( var cascade: cascades ) { cascadeTypes.add( convertCascadeType( cascade ) ); } } @@ -963,7 +959,7 @@ public static void checkMappedByType( PropertyHolder propertyHolder, Map persistentClasses) { if ( targetValue instanceof Collection collection ) { - final ToOne element = (ToOne) collection.getElement(); + final var element = (ToOne) collection.getElement(); checkMappedByType( mappedBy, propertyName, propertyHolder, persistentClasses, element ); } else if ( targetValue instanceof ToOne toOne ) { @@ -982,8 +978,7 @@ private static void checkMappedByType( PersistentClass ownerClass = propertyHolder.getPersistentClass(); while ( ownerClass != null ) { if ( checkReferencedClass( ownerClass, referencedClass ) ) { - // the two entities map to the same table - // so we are good + // the two entities map to the same table, so we are good return; } ownerClass = ownerClass.getSuperPersistentClass(); @@ -1013,7 +1008,7 @@ public static boolean noConstraint(ForeignKey foreignKey, boolean noConstraintBy return false; } else { - final ConstraintMode mode = foreignKey.value(); + final var mode = foreignKey.value(); return mode == NO_CONSTRAINT || mode == PROVIDER_DEFAULT && noConstraintByDefault; } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java index 983969d6df84..507a697f9441 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/EntityBinder.java @@ -1509,16 +1509,16 @@ private String getDefaultFilterCondition(String filterName) { private void bindSynchronize() { final var synchronize = annotatedClass.getAnnotationUsage( Synchronize.class, modelsContext() ); if ( synchronize != null ) { - final var jdbcEnvironment = getDatabase().getJdbcEnvironment(); final boolean logical = synchronize.logical(); for ( String tableName : synchronize.value() ) { - final String physicalName = logical ? toPhysicalName( jdbcEnvironment, tableName ) : tableName; + final String physicalName = logical ? toPhysicalName( tableName ) : tableName; persistentClass.addSynchronizedTable( physicalName ); } } } - private String toPhysicalName(JdbcEnvironment jdbcEnvironment, String logicalName) { + private String toPhysicalName(String logicalName) { + final var jdbcEnvironment = getDatabase().getJdbcEnvironment(); final var identifier = jdbcEnvironment.getIdentifierHelper().toIdentifier( logicalName ); return getPhysicalNamingStrategy() .toPhysicalTableName( identifier, jdbcEnvironment ) @@ -1650,7 +1650,7 @@ private void bindNaturalIdCache() { : annotatedClass.getName() + NATURAL_ID_CACHE_SUFFIX; } else { - naturalIdCacheRegion = naturalIdCache.region(); + naturalIdCacheRegion = region; } } else { @@ -1802,7 +1802,7 @@ private static JdbcEnvironment jdbcEnvironment(MetadataBuildingContext buildingC private void bindTableForDiscriminatedSubclass(String entityName) { if ( !(persistentClass instanceof SingleTableSubclass) ) { throw new AssertionFailure( - "Was expecting a discriminated subclass [" + SingleTableSubclass.class.getName() + + "Expecting a discriminated subclass [" + SingleTableSubclass.class.getName() + "] but found [" + persistentClass.getClass().getName() + "] for entity [" + persistentClass.getEntityName() + "]" ); @@ -1827,27 +1827,18 @@ private void bindTable( String rowId, String viewQuery, InFlightMetadataCollector.EntityTableXref denormalizedSuperTableXref) { - final String entityName = persistentClass.getEntityName(); - - final var namingStrategyHelper = - new EntityTableNamingStrategyHelper( persistentClass.getClassName(), entityName, name ); - final Identifier logicalName = - isNotBlank( tableName ) - ? namingStrategyHelper.handleExplicitName( tableName, context ) - : namingStrategyHelper.determineImplicitName( context ); - + final Identifier logicalTableName = logicalTableName( tableName, entityName ); final Table table = TableBinder.buildAndFillTable( schema, catalog, - logicalName, + logicalTableName, persistentClass.isAbstract(), uniqueConstraints, context, subselect, denormalizedSuperTableXref ); - table.setRowId( rowId ); table.setViewQuery( viewQuery ); @@ -1856,7 +1847,8 @@ private void bindTable( // table.setComment( comment.value() ); // } - getMetadataCollector().addEntityTableXref( entityName, logicalName, table, denormalizedSuperTableXref ); + getMetadataCollector() + .addEntityTableXref( entityName, logicalTableName, table, denormalizedSuperTableXref ); if ( persistentClass instanceof TableOwner tableOwner ) { tableOwner.setTable( table ); @@ -1866,13 +1858,21 @@ private void bindTable( } } + private Identifier logicalTableName(String tableName, String entityName) { + final var namingStrategyHelper = + new EntityTableNamingStrategyHelper( persistentClass.getClassName(), entityName, name ); + return isNotBlank( tableName ) + ? namingStrategyHelper.handleExplicitName( tableName, context ) + : namingStrategyHelper.determineImplicitName( context ); + } + public void finalSecondaryTableBinding(PropertyHolder propertyHolder) { // This operation has to be done after the id definition of the persistence class. // ie after the properties parsing final var joinColumns = secondaryTableJoins.values().iterator(); - for ( var entrySet : secondaryTables.entrySet() ) { - if ( !secondaryTablesFromAnnotation.containsKey( entrySet.getKey() ) ) { - createPrimaryColumnsToSecondaryTable( joinColumns.next(), propertyHolder, entrySet.getValue() ); + for ( var entry : secondaryTables.entrySet() ) { + if ( !secondaryTablesFromAnnotation.containsKey( entry.getKey() ) ) { + createPrimaryColumnsToSecondaryTable( joinColumns.next(), propertyHolder, entry.getValue() ); } } } @@ -1881,9 +1881,9 @@ public void finalSecondaryTableFromAnnotationBinding(PropertyHolder propertyHold // This operation has to be done before the end of the FK second pass processing in order // to find the join columns belonging to secondary tables final var joinColumns = secondaryTableFromAnnotationJoins.values().iterator(); - for ( var entrySet : secondaryTables.entrySet() ) { - if ( secondaryTablesFromAnnotation.containsKey( entrySet.getKey() ) ) { - createPrimaryColumnsToSecondaryTable( joinColumns.next(), propertyHolder, entrySet.getValue() ); + for ( var entry : secondaryTables.entrySet() ) { + if ( secondaryTablesFromAnnotation.containsKey( entry.getKey() ) ) { + createPrimaryColumnsToSecondaryTable( joinColumns.next(), propertyHolder, entry.getValue() ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagBinder.java index 3a35031fd874..ed7e0ac5a6b5 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagBinder.java @@ -12,18 +12,17 @@ import org.hibernate.annotations.CollectionId; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.PropertyData; -import org.hibernate.boot.spi.SecondPass; import org.hibernate.mapping.BasicValue; import org.hibernate.mapping.Collection; import org.hibernate.mapping.IdentifierBag; import org.hibernate.mapping.IdentifierCollection; import org.hibernate.mapping.PersistentClass; -import org.hibernate.mapping.Table; import org.hibernate.resource.beans.spi.ManagedBean; import org.hibernate.usertype.UserCollectionType; import jakarta.persistence.Column; +import static org.hibernate.boot.model.internal.BasicValueBinder.Kind.COLLECTION_ID; import static org.hibernate.boot.model.internal.BinderHelper.isGlobalGeneratorNameGlobal; import static org.hibernate.boot.model.internal.GeneratorBinder.makeIdGenerator; @@ -78,78 +77,58 @@ protected boolean bindStarToManySecondPass(Map persiste buildingContext ); - //we need to make sure all id columns must be not-null. + // we need to make sure all id columns must be not-null. for ( var idColumn : idColumns.getColumns() ) { idColumn.setNullable( false ); } - final var valueBinder = new BasicValueBinder( BasicValueBinder.Kind.COLLECTION_ID, buildingContext ); - - final Table table = collection.getCollectionTable(); - valueBinder.setTable( table ); - valueBinder.setColumns( idColumns ); - - valueBinder.setType( - property, - getElementType(), - null, - null - ); - - final BasicValue id = valueBinder.make(); + final var idValueBinder = new BasicValueBinder( COLLECTION_ID, buildingContext ); + idValueBinder.setTable( collection.getCollectionTable() ); + idValueBinder.setColumns( idColumns ); + idValueBinder.setType( property, getElementType() ); + final BasicValue id = idValueBinder.make(); ( (IdentifierCollection) collection ).setIdentifier( id ); - final String namedGenerator = collectionIdAnn.generator(); - - switch (namedGenerator) { - case "identity": { - throw new MappingException("IDENTITY generation not supported for @CollectionId"); - } - case "assigned": { - throw new MappingException("Assigned generation not supported for @CollectionId"); - } - case "native": { - throw new MappingException("Native generation not supported for @CollectionId"); - } - } - - final String generatorName; - final String generatorType; - - if ( "sequence".equals( namedGenerator ) ) { - generatorType = namedGenerator; - generatorName = ""; - } - else if ( "increment".equals( namedGenerator ) ) { - generatorType = namedGenerator; - generatorName = ""; - } - else { - generatorType = namedGenerator; - generatorName = namedGenerator; - } - + final String generator = collectionIdAnn.generator(); + checkLegalCollectionIdStrategy( generator ); if ( isGlobalGeneratorNameGlobal( buildingContext ) ) { - SecondPass secondPass = new IdBagIdGeneratorResolverSecondPass( - (IdentifierBag) collection, - id, - property, - generatorType, - generatorName, - getBuildingContext() - ); - buildingContext.getMetadataCollector().addSecondPass( secondPass ); + buildingContext.getMetadataCollector() + .addSecondPass( new IdBagIdGeneratorResolverSecondPass( + id, + property, + generator, + generatorName( generator ), + getBuildingContext() + ) ); } else { makeIdGenerator( id, property, - generatorType, - generatorName, + generator, + generatorName( generator ), getBuildingContext(), localGenerators ); } return result; } + + private static String generatorName(String generator) { + return switch ( generator ) { + case "sequence", "increment" -> ""; + default -> generator; + }; + } + + private static void checkLegalCollectionIdStrategy(String namedGenerator) { + switch ( namedGenerator ) { + case "identity": + throw new MappingException("IDENTITY generation not supported for @CollectionId"); + case "assigned": + throw new MappingException("Assigned generation not supported for @CollectionId"); + case "native": + throw new MappingException("Native generation not supported for @CollectionId"); + } + } } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagIdGeneratorResolverSecondPass.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagIdGeneratorResolverSecondPass.java index ad19c144e355..3eefbf4dc17e 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagIdGeneratorResolverSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/IdBagIdGeneratorResolverSecondPass.java @@ -14,7 +14,6 @@ import org.hibernate.boot.models.annotations.internal.TableGeneratorJpaAnnotation; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.id.PersistentIdentifierGenerator; -import org.hibernate.mapping.IdentifierBag; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.SimpleValue; import org.hibernate.models.spi.MemberDetails; @@ -47,7 +46,6 @@ public class IdBagIdGeneratorResolverSecondPass implements IdGeneratorResolver { private final Map configuration; public IdBagIdGeneratorResolverSecondPass( - IdentifierBag idBagMapping, SimpleValue idValue, MemberDetails idBagMember, String generatorType, diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ListBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ListBinder.java index bc5d0dbe70cb..ef8e2c191340 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ListBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/ListBinder.java @@ -19,6 +19,7 @@ import org.hibernate.resource.beans.spi.ManagedBean; import org.hibernate.usertype.UserCollectionType; +import static org.hibernate.boot.model.internal.BasicValueBinder.Kind.LIST_INDEX; import static org.hibernate.boot.model.internal.PropertyHolderBuilder.buildPropertyHolder; import static org.hibernate.internal.util.StringHelper.qualify; @@ -65,10 +66,10 @@ private void bindIndex() { } indexColumn.getParent().setPropertyHolder( valueHolder ); - final var valueBinder = new BasicValueBinder( BasicValueBinder.Kind.LIST_INDEX, buildingContext ); + final var valueBinder = new BasicValueBinder( LIST_INDEX, buildingContext ); valueBinder.setColumns( indexColumn.getParent() ); valueBinder.setReturnedClassName( Integer.class.getName() ); - valueBinder.setType( property, getElementType(), null, null ); + valueBinder.setType( property, getElementType() ); // valueBinder.setExplicitType( "integer" ); final SimpleValue indexValue = valueBinder.make(); indexColumn.linkWithValue( indexValue ); diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/MapBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/MapBinder.java index 2440b6cf8ec4..9cd24c3485a0 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/MapBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/MapBinder.java @@ -51,6 +51,7 @@ import static org.hibernate.boot.model.internal.AnnotatedClassType.EMBEDDABLE; import static org.hibernate.boot.model.internal.AnnotatedClassType.NONE; +import static org.hibernate.boot.model.internal.BasicValueBinder.Kind.MAP_KEY; import static org.hibernate.boot.model.internal.BinderHelper.findPropertyByName; import static org.hibernate.boot.model.internal.BinderHelper.isPrimitive; import static org.hibernate.boot.model.internal.EmbeddableBinder.fillEmbeddable; @@ -361,7 +362,7 @@ private void handleMapKey( TypeDetails keyTypeDetails, CollectionPropertyHolder holder, AccessType accessType) { - final var elementBinder = new BasicValueBinder( BasicValueBinder.Kind.MAP_KEY, buildingContext ); + final var elementBinder = new BasicValueBinder( MAP_KEY, buildingContext ); elementBinder.setReturnedClassName(mapKeyType); final var keyColumns = createElementColumnsIfNecessary( collection, diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyBinder.java index e3d32cc51c2a..32c51ed9bdac 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/internal/PropertyBinder.java @@ -77,6 +77,7 @@ import static jakarta.persistence.FetchType.LAZY; import static org.hibernate.boot.model.internal.AnyBinder.bindAny; +import static org.hibernate.boot.model.internal.BasicValueBinder.Kind.ATTRIBUTE; import static org.hibernate.boot.model.internal.BinderHelper.getMappedSuperclassOrNull; import static org.hibernate.boot.model.internal.BinderHelper.getPath; import static org.hibernate.boot.model.internal.BinderHelper.hasToOneAnnotation; @@ -255,7 +256,7 @@ private Property makePropertyAndValue() { final String containerClassName = holder.getClassName(); holder.startingProperty( memberDetails ); - basicValueBinder = new BasicValueBinder( BasicValueBinder.Kind.ATTRIBUTE, buildingContext ); + basicValueBinder = new BasicValueBinder( ATTRIBUTE, buildingContext ); basicValueBinder.setReturnedClassName( returnedClassName ); basicValueBinder.setColumns( columns ); basicValueBinder.setPersistentClassName( containerClassName );