From 54b9677d99d0e43ae706f566dcb45b07bdabc882 Mon Sep 17 00:00:00 2001 From: Gavin King Date: Wed, 26 Jan 2022 14:04:09 +0100 Subject: [PATCH] get rid of the iterators in the mapping package and clean up a lot of warnings --- .../source/internal/hbm/ModelBinder.java | 307 +++++++----------- .../hibernate/cfg/AnnotatedJoinColumn.java | 24 +- .../org/hibernate/cfg/AnnotationBinder.java | 11 +- .../java/org/hibernate/cfg/BinderHelper.java | 42 ++- .../CopyIdentifierComponentSecondPass.java | 25 +- .../cfg/IndexOrUniqueKeySecondPass.java | 9 +- .../org/hibernate/cfg/OneToOneSecondPass.java | 38 +-- .../PkDrivenByDefaultMapsIdSecondPass.java | 2 +- .../java/org/hibernate/cfg/SecondPass.java | 3 +- .../org/hibernate/cfg/ToOneFkSecondPass.java | 14 +- .../cfg/annotations/CollectionBinder.java | 18 +- .../hibernate/cfg/annotations/MapBinder.java | 30 +- .../ResultsetMappingSecondPass.java | 110 +++---- .../cfg/annotations/TableBinder.java | 68 ++-- .../cfg/beanvalidation/TypeSafeActivator.java | 26 +- ...NullableDiscriminatorColumnSecondPass.java | 5 +- .../dialect/temptable/TemporaryTable.java | 18 +- .../org/hibernate/id/ExportableColumn.java | 16 +- .../util/collections/JoinedIterator.java | 1 + .../internal/util/collections/JoinedList.java | 51 +++ .../org/hibernate/mapping/Collection.java | 23 +- .../java/org/hibernate/mapping/Component.java | 71 ++-- .../org/hibernate/mapping/Constraint.java | 13 +- .../org/hibernate/mapping/Contributable.java | 4 +- .../hibernate/mapping/DenormalizedTable.java | 53 ++- .../mapping/DependantBasicValue.java | 4 +- .../org/hibernate/mapping/FetchProfile.java | 2 +- .../java/org/hibernate/mapping/Fetchable.java | 1 + .../org/hibernate/mapping/ForeignKey.java | 22 +- .../mapping/IdentifierCollection.java | 2 +- .../hibernate/mapping/IndexedCollection.java | 10 +- .../main/java/org/hibernate/mapping/Join.java | 14 +- .../org/hibernate/mapping/JoinedSubclass.java | 6 + .../java/org/hibernate/mapping/ManyToOne.java | 22 +- .../java/org/hibernate/mapping/OneToMany.java | 16 +- .../java/org/hibernate/mapping/OneToOne.java | 37 ++- .../hibernate/mapping/PersistentClass.java | 186 ++++++----- .../java/org/hibernate/mapping/Property.java | 26 +- .../java/org/hibernate/mapping/RootClass.java | 8 +- .../main/java/org/hibernate/mapping/Set.java | 21 +- .../org/hibernate/mapping/SimpleValue.java | 60 ++-- .../mapping/SingleTableSubclass.java | 17 +- .../org/hibernate/mapping/SortableValue.java | 3 - .../java/org/hibernate/mapping/Subclass.java | 19 +- .../java/org/hibernate/mapping/Table.java | 34 +- .../java/org/hibernate/mapping/ToOne.java | 9 +- .../org/hibernate/mapping/UnionSubclass.java | 9 +- .../java/org/hibernate/mapping/Value.java | 57 +++- ...tractEmbeddableRepresentationStrategy.java | 11 +- .../metamodel/internal/AttributeFactory.java | 7 +- ...ityRepresentationStrategyPojoStandard.java | 11 +- .../metamodel/internal/MetadataContext.java | 71 ++-- .../internal/AbstractEmbeddableMapping.java | 5 +- .../internal/EmbeddableMappingTypeImpl.java | 4 +- .../internal/EntityCollectionPart.java | 2 +- .../internal/MappingModelCreationHelper.java | 10 +- .../internal/SelectableMappingsImpl.java | 16 +- .../internal/ToOneAttributeMapping.java | 6 +- .../AbstractCollectionPersister.java | 15 +- .../entity/AbstractEntityPersister.java | 187 +++++------ .../entity/JoinedSubclassEntityPersister.java | 41 ++- .../entity/SingleTableEntityPersister.java | 31 +- .../entity/UnionSubclassEntityPersister.java | 10 +- .../proxy/pojo/ProxyFactoryHelper.java | 4 +- .../org/hibernate/tuple/TenantIdBinder.java | 8 +- .../tuple/entity/EntityMetamodel.java | 26 +- .../org/hibernate/type/ComponentType.java | 4 +- .../java/org/hibernate/type/EnumType.java | 2 +- .../type/SerializableToBlobType.java | 2 +- .../usertype/DynamicParameterizedType.java | 2 +- .../annotations/immutable/ImmutableTest.java | 15 +- .../lazy/proxy/ProxyDeletionTest.java | 1 - .../orm/test/hql/ASTParserLoadingTest.java | 2 +- .../test/unionsubclass/alias/SellCarTest.java | 5 +- 74 files changed, 1036 insertions(+), 1029 deletions(-) create mode 100644 hibernate-core/src/main/java/org/hibernate/internal/util/collections/JoinedList.java diff --git a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java index 4f5dd68dae..63d0cc81cc 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/ModelBinder.java @@ -33,7 +33,6 @@ import org.hibernate.boot.model.naming.ImplicitCollectionTableNameSource; import org.hibernate.boot.model.naming.ImplicitEntityNameSource; import org.hibernate.boot.model.naming.ImplicitIdentifierColumnNameSource; import org.hibernate.boot.model.naming.ImplicitIndexColumnNameSource; -import org.hibernate.boot.model.naming.ImplicitJoinColumnNameSource; import org.hibernate.boot.model.naming.ImplicitMapKeyColumnNameSource; import org.hibernate.boot.model.naming.ImplicitNamingStrategy; import org.hibernate.boot.model.naming.ImplicitUniqueKeyNameSource; @@ -733,29 +732,26 @@ public class ModelBinder { ( (RelationalValueSourceContainer) idSource.getIdentifierAttributeSource() ).getRelationalValueSources(), idValue, false, - new RelationalObjectBinder.ColumnNamingDelegate() { - @Override - public Identifier determineImplicitName(final LocalMetadataBuildingContext context) { - context.getBuildingOptions().getImplicitNamingStrategy().determineIdentifierColumnName( - new ImplicitIdentifierColumnNameSource() { - @Override - public EntityNaming getEntityNaming() { - return hierarchySource.getRoot().getEntityNamingSource(); - } - - @Override - public AttributePath getIdentifierAttributePath() { - return idSource.getIdentifierAttributeSource().getAttributePath(); - } - - @Override - public MetadataBuildingContext getBuildingContext() { - return context; - } + context -> { + context.getBuildingOptions().getImplicitNamingStrategy().determineIdentifierColumnName( + new ImplicitIdentifierColumnNameSource() { + @Override + public EntityNaming getEntityNaming() { + return hierarchySource.getRoot().getEntityNamingSource(); } - ); - return database.toIdentifier( propertyName ); - } + + @Override + public AttributePath getIdentifierAttributePath() { + return idSource.getIdentifierAttributeSource().getAttributePath(); + } + + @Override + public MetadataBuildingContext getBuildingContext() { + return context; + } + } + ); + return database.toIdentifier( propertyName ); } ); @@ -1007,12 +1003,7 @@ public class ModelBinder { versionAttributeSource.getRelationalValueSources(), versionValue, false, - new RelationalObjectBinder.ColumnNamingDelegate() { - @Override - public Identifier determineImplicitName(LocalMetadataBuildingContext context) { - return implicitNamingStrategy.determineBasicColumnName( versionAttributeSource ); - } - } + context -> implicitNamingStrategy.determineBasicColumnName( versionAttributeSource ) ); Property prop = new Property(); @@ -1072,14 +1063,9 @@ public class ModelBinder { hierarchySource.getDiscriminatorSource().getDiscriminatorRelationalValueSource(), discriminatorValue, false, - new RelationalObjectBinder.ColumnNamingDelegate() { - @Override - public Identifier determineImplicitName(final LocalMetadataBuildingContext context) { - return implicitNamingStrategy.determineDiscriminatorColumnName( - hierarchySource.getDiscriminatorSource() - ); - } - } + context -> implicitNamingStrategy.determineDiscriminatorColumnName( + hierarchySource.getDiscriminatorSource() + ) ); rootEntityDescriptor.setPolymorphic( true ); @@ -1124,7 +1110,7 @@ public class ModelBinder { } for ( AttributeSource attributeSource : entitySource.attributeSources() ) { - if ( PluralAttributeSource.class.isInstance( attributeSource ) ) { + if ( attributeSource instanceof PluralAttributeSource ) { // plural attribute final Property attribute = createPluralAttribute( mappingDocument, @@ -1135,7 +1121,7 @@ public class ModelBinder { } else { // singular attribute - if ( SingularAttributeSourceBasic.class.isInstance( attributeSource ) ) { + if ( attributeSource instanceof SingularAttributeSourceBasic ) { final SingularAttributeSourceBasic basicAttributeSource = (SingularAttributeSourceBasic) attributeSource; final Identifier tableName = determineTable( mappingDocument, basicAttributeSource.getName(), basicAttributeSource ); final AttributeContainer attributeContainer; @@ -1170,7 +1156,7 @@ public class ModelBinder { basicAttributeSource.getNaturalIdMutability() ); } - else if ( SingularAttributeSourceEmbedded.class.isInstance( attributeSource ) ) { + else if ( attributeSource instanceof SingularAttributeSourceEmbedded ) { final SingularAttributeSourceEmbedded embeddedAttributeSource = (SingularAttributeSourceEmbedded) attributeSource; final Identifier tableName = determineTable( mappingDocument, embeddedAttributeSource ); final AttributeContainer attributeContainer; @@ -1205,7 +1191,7 @@ public class ModelBinder { embeddedAttributeSource.getNaturalIdMutability() ); } - else if ( SingularAttributeSourceManyToOne.class.isInstance( attributeSource ) ) { + else if ( attributeSource instanceof SingularAttributeSourceManyToOne ) { final SingularAttributeSourceManyToOne manyToOneAttributeSource = (SingularAttributeSourceManyToOne) attributeSource; final Identifier tableName = determineTable( mappingDocument, manyToOneAttributeSource.getName(), manyToOneAttributeSource ); final AttributeContainer attributeContainer; @@ -1240,7 +1226,7 @@ public class ModelBinder { manyToOneAttributeSource.getNaturalIdMutability() ); } - else if ( SingularAttributeSourceOneToOne.class.isInstance( attributeSource ) ) { + else if ( attributeSource instanceof SingularAttributeSourceOneToOne ) { final SingularAttributeSourceOneToOne oneToOneAttributeSource = (SingularAttributeSourceOneToOne) attributeSource; final Table table = entityDescriptor.getTable(); final Property attribute = createOneToOneAttribute( @@ -1258,7 +1244,7 @@ public class ModelBinder { oneToOneAttributeSource.getNaturalIdMutability() ); } - else if ( SingularAttributeSourceAny.class.isInstance( attributeSource ) ) { + else if ( attributeSource instanceof SingularAttributeSourceAny ) { final SingularAttributeSourceAny anyAttributeSource = (SingularAttributeSourceAny) attributeSource; final Identifier tableName = determineTable( mappingDocument, @@ -1458,7 +1444,7 @@ public class ModelBinder { // bind the collection type info String typeName = source.getTypeInformation().getName(); - Map typeParameters = new HashMap(); + Map typeParameters = new HashMap<>(); if ( typeName != null ) { // see if there is a corresponding type-def final TypeDefinition typeDef = mappingDocument.getMetadataCollector().getTypeDefinition( typeName ); @@ -1652,7 +1638,7 @@ public class ModelBinder { Identifier tableName = null; for ( AttributeSource attributeSource : embeddedAttributeSource.getEmbeddableSource().attributeSources() ) { final Identifier determinedName; - if ( RelationalValueSourceContainer.class.isInstance( attributeSource ) ) { + if ( attributeSource instanceof RelationalValueSourceContainer ) { determinedName = determineTable( mappingDocument, embeddedAttributeSource.getAttributeRole().getFullPath(), @@ -1660,10 +1646,10 @@ public class ModelBinder { ); } - else if ( SingularAttributeSourceEmbedded.class.isInstance( attributeSource ) ) { + else if ( attributeSource instanceof SingularAttributeSourceEmbedded ) { determinedName = determineTable( mappingDocument, (SingularAttributeSourceEmbedded) attributeSource ); } - else if ( SingularAttributeSourceAny.class.isInstance( attributeSource ) ) { + else if ( attributeSource instanceof SingularAttributeSourceAny ) { determinedName = determineTable( mappingDocument, attributeSource.getAttributeRole().getFullPath(), @@ -1901,12 +1887,7 @@ public class ModelBinder { attributeSource.getRelationalValueSources(), value, attributeSource.areValuesNullableByDefault(), - new RelationalObjectBinder.ColumnNamingDelegate() { - @Override - public Identifier determineImplicitName(LocalMetadataBuildingContext context) { - return implicitNamingStrategy.determineBasicColumnName( attributeSource ); - } - } + context -> implicitNamingStrategy.determineBasicColumnName( attributeSource ) ); @@ -2181,7 +2162,7 @@ public class ModelBinder { referencedEntityName = manyToOneSource.getReferencedEntityName(); } else { - Class reflectedPropertyClass = Helper.reflectedPropertyClass( sourceDocument, containingClassName, attributeName ); + Class reflectedPropertyClass = Helper.reflectedPropertyClass( sourceDocument, containingClassName, attributeName ); if ( reflectedPropertyClass != null ) { referencedEntityName = reflectedPropertyClass.getName(); } @@ -2615,9 +2596,9 @@ public class ModelBinder { .append( "Mapped property: " ) .append( propertySource.getName() ) .append( " -> [" ); - final Iterator itr = property.getValue().getColumnIterator(); + final Iterator itr = property.getValue().getColumnIterator(); while ( itr.hasNext() ) { - message.append( ( (Selectable) itr.next() ).getText() ); + message.append( itr.next().getText() ); if ( itr.hasNext() ) { message.append( ", " ); } @@ -2706,7 +2687,7 @@ public class ModelBinder { } else if ( componentBinding.getOwner().hasPojoRepresentation() ) { log.tracef( "Attempting to determine component class by reflection %s", role ); - final Class reflectedComponentClass; + final Class reflectedComponentClass; if ( StringHelper.isNotEmpty( containingClassName ) && StringHelper.isNotEmpty( propertyName ) ) { reflectedComponentClass = Helper.reflectedPropertyClass( sourceDocument, @@ -2747,40 +2728,25 @@ public class ModelBinder { if ( embeddableSource.isUnique() ) { final ArrayList cols = new ArrayList<>(); - final Iterator itr = componentBinding.getColumnIterator(); - while ( itr.hasNext() ) { - final Object selectable = itr.next(); - // skip formulas. ugh, yes terrible naming of these methods :( - if ( !Column.class.isInstance( selectable ) ) { - continue; + for ( Selectable selectable: componentBinding.getSelectables() ) { + if ( selectable instanceof Column) { + cols.add( (Column) selectable ); } - cols.add( (Column) selectable ); } // todo : we may need to delay this componentBinding.getOwner().getTable().createUniqueKey( cols ); } } - private void prepareComponentType( - MappingDocument sourceDocument, - String fullRole, - Component componentBinding, - String explicitComponentClassName, - String containingClassName, - String propertyName, - boolean isVirtual, - boolean isDynamic) { - } - private void bindAllCompositeAttributes( MappingDocument sourceDocument, EmbeddableSource embeddableSource, Component component) { for ( AttributeSource attributeSource : embeddableSource.attributeSources() ) { - Property attribute = null; + Property attribute; - if ( SingularAttributeSourceBasic.class.isInstance( attributeSource ) ) { + if ( attributeSource instanceof SingularAttributeSourceBasic ) { attribute = createBasicAttribute( sourceDocument, (SingularAttributeSourceBasic) attributeSource, @@ -2788,7 +2754,7 @@ public class ModelBinder { component.getComponentClassName() ); } - else if ( SingularAttributeSourceEmbedded.class.isInstance( attributeSource ) ) { + else if ( attributeSource instanceof SingularAttributeSourceEmbedded ) { attribute = createEmbeddedAttribute( sourceDocument, (SingularAttributeSourceEmbedded) attributeSource, @@ -2796,7 +2762,7 @@ public class ModelBinder { component.getComponentClassName() ); } - else if ( SingularAttributeSourceManyToOne.class.isInstance( attributeSource ) ) { + else if ( attributeSource instanceof SingularAttributeSourceManyToOne ) { attribute = createManyToOneAttribute( sourceDocument, (SingularAttributeSourceManyToOne) attributeSource, @@ -2804,7 +2770,7 @@ public class ModelBinder { component.getComponentClassName() ); } - else if ( SingularAttributeSourceOneToOne.class.isInstance( attributeSource ) ) { + else if ( attributeSource instanceof SingularAttributeSourceOneToOne ) { attribute = createOneToOneAttribute( sourceDocument, (SingularAttributeSourceOneToOne) attributeSource, @@ -2812,7 +2778,7 @@ public class ModelBinder { component.getComponentClassName() ); } - else if ( SingularAttributeSourceAny.class.isInstance( attributeSource ) ) { + else if ( attributeSource instanceof SingularAttributeSourceAny ) { attribute = createAnyAssociationAttribute( sourceDocument, (SingularAttributeSourceAny) attributeSource, @@ -2820,7 +2786,7 @@ public class ModelBinder { component.getComponentClassName() ); } - else if ( PluralAttributeSource.class.isInstance( attributeSource ) ) { + else if ( attributeSource instanceof PluralAttributeSource ) { attribute = createPluralAttribute( sourceDocument, (PluralAttributeSource) attributeSource, @@ -2917,8 +2883,8 @@ public class ModelBinder { determineSchemaName( tableSpecSource ) ); - final boolean isTable = TableSource.class.isInstance( tableSpecSource ); - final boolean isAbstract = entityDescriptor.isAbstract() == null ? false : entityDescriptor.isAbstract(); + final boolean isTable = tableSpecSource instanceof TableSource; + final boolean isAbstract = entityDescriptor.isAbstract() != null && entityDescriptor.isAbstract(); final String subselect; final Identifier logicalTableName; final Table table; @@ -2991,7 +2957,6 @@ public class ModelBinder { EntityTableXref superEntityTableXref = null; if ( entitySource.getSuperType() != null ) { - //noinspection SuspiciousMethodCalls final String superEntityName = ( (EntitySource) entitySource.getSuperType() ).getEntityNamingSource() .getEntityName(); superEntityTableXref = mappingDocument.getMetadataCollector().getEntityTableXref( superEntityName ); @@ -3406,27 +3371,22 @@ public class ModelBinder { ); key.setForeignKeyName( keySource.getExplicitForeignKeyName() ); key.setCascadeDeleteEnabled( getPluralAttributeSource().getKeySource().isCascadeDeleteEnabled() ); - - final ImplicitJoinColumnNameSource.Nature implicitNamingNature; - if ( getPluralAttributeSource().getElementSource() instanceof PluralAttributeElementSourceManyToMany - || getPluralAttributeSource().getElementSource() instanceof PluralAttributeElementSourceOneToMany ) { - implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ENTITY_COLLECTION; - } - else { - implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ELEMENT_COLLECTION; - } +// +// final ImplicitJoinColumnNameSource.Nature implicitNamingNature; +// if ( getPluralAttributeSource().getElementSource() instanceof PluralAttributeElementSourceManyToMany +// || getPluralAttributeSource().getElementSource() instanceof PluralAttributeElementSourceOneToMany ) { +// implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ENTITY_COLLECTION; +// } +// else { +// implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ELEMENT_COLLECTION; +// } relationalObjectBinder.bindColumnsAndFormulas( mappingDocument, getPluralAttributeSource().getKeySource().getRelationalValueSources(), key, getPluralAttributeSource().getKeySource().areValuesNullableByDefault(), - new RelationalObjectBinder.ColumnNamingDelegate() { - @Override - public Identifier determineImplicitName(final LocalMetadataBuildingContext context) { - return context.getMetadataCollector().getDatabase().toIdentifier( Collection.DEFAULT_KEY_COLUMN_NAME ); - } - } + context -> context.getMetadataCollector().getDatabase().toIdentifier( Collection.DEFAULT_KEY_COLUMN_NAME ) ); key.sortProperties(); @@ -3457,12 +3417,7 @@ public class ModelBinder { idSource.getColumnSource(), idBinding, false, - new RelationalObjectBinder.ColumnNamingDelegate() { - @Override - public Identifier determineImplicitName(LocalMetadataBuildingContext context) { - return database.toIdentifier( IdentifierCollection.DEFAULT_IDENTIFIER_COLUMN_NAME ); - } - } + context -> database.toIdentifier( IdentifierCollection.DEFAULT_IDENTIFIER_COLUMN_NAME ) ); idBagBinding.setIdentifier( idBinding ); @@ -3506,12 +3461,7 @@ public class ModelBinder { elementSource.getRelationalValueSources(), elementBinding, elementSource.areValuesNullableByDefault(), - new RelationalObjectBinder.ColumnNamingDelegate() { - @Override - public Identifier determineImplicitName(LocalMetadataBuildingContext context) { - return context.getMetadataCollector().getDatabase().toIdentifier( Collection.DEFAULT_ELEMENT_COLUMN_NAME ); - } - } + context -> context.getMetadataCollector().getDatabase().toIdentifier( Collection.DEFAULT_ELEMENT_COLUMN_NAME ) ); getCollectionBinding().setElement( elementBinding ); @@ -3593,14 +3543,8 @@ public class ModelBinder { elementSource.getRelationalValueSources(), elementBinding, false, - new RelationalObjectBinder.ColumnNamingDelegate() { - @Override - public Identifier determineImplicitName(final LocalMetadataBuildingContext context) { - return context.getMetadataCollector() - .getDatabase() - .toIdentifier( Collection.DEFAULT_ELEMENT_COLUMN_NAME ); - } - } + context -> context.getMetadataCollector().getDatabase() + .toIdentifier( Collection.DEFAULT_ELEMENT_COLUMN_NAME ) ); elementBinding.setLazy( @@ -3829,10 +3773,10 @@ public class ModelBinder { super.createBackReferences(); boolean indexIsFormula = false; - Iterator itr = getCollectionBinding().getIndex().getColumnIterator(); - while ( itr.hasNext() ) { - if ( ( (Selectable) itr.next() ).isFormula() ) { + for ( Selectable selectable: getCollectionBinding().getIndex().getSelectables() ) { + if ( selectable.isFormula() ) { indexIsFormula = true; + break; } } @@ -3993,24 +3937,19 @@ public class ModelBinder { indexSource.getRelationalValueSources(), indexBinding, attributeSource.getElementSource() instanceof PluralAttributeElementSourceOneToMany, - new RelationalObjectBinder.ColumnNamingDelegate() { - @Override - public Identifier determineImplicitName(final LocalMetadataBuildingContext context) { - return context.getBuildingOptions().getImplicitNamingStrategy().determineListIndexColumnName( - new ImplicitIndexColumnNameSource() { - @Override - public AttributePath getPluralAttributePath() { - return attributeSource.getAttributePath(); - } + context -> context.getBuildingOptions().getImplicitNamingStrategy().determineListIndexColumnName( + new ImplicitIndexColumnNameSource() { + @Override + public AttributePath getPluralAttributePath() { + return attributeSource.getAttributePath(); + } - @Override - public MetadataBuildingContext getBuildingContext() { - return context; - } - } - ); - } - } + @Override + public MetadataBuildingContext getBuildingContext() { + return context; + } + } + ) ); collectionBinding.setIndex( indexBinding ); @@ -4046,12 +3985,7 @@ public class ModelBinder { mapKeySource.getRelationalValueSources(), value, true, - new RelationalObjectBinder.ColumnNamingDelegate() { - @Override - public Identifier determineImplicitName(LocalMetadataBuildingContext context) { - return database.toIdentifier( IndexedCollection.DEFAULT_INDEX_COLUMN_NAME ); - } - } + context -> database.toIdentifier( IndexedCollection.DEFAULT_INDEX_COLUMN_NAME ) ); collectionBinding.setIndex( value ); @@ -4089,24 +4023,19 @@ public class ModelBinder { mapKeySource.getRelationalValueSources(), mapKeyBinding, true, - new RelationalObjectBinder.ColumnNamingDelegate() { - @Override - public Identifier determineImplicitName(final LocalMetadataBuildingContext context) { - return implicitNamingStrategy.determineMapKeyColumnName( - new ImplicitMapKeyColumnNameSource() { - @Override - public AttributePath getPluralAttributePath() { - return pluralAttributeSource.getAttributePath(); - } + context -> implicitNamingStrategy.determineMapKeyColumnName( + new ImplicitMapKeyColumnNameSource() { + @Override + public AttributePath getPluralAttributePath() { + return pluralAttributeSource.getAttributePath(); + } - @Override - public MetadataBuildingContext getBuildingContext() { - return context; - } - } - ); - } - } + @Override + public MetadataBuildingContext getBuildingContext() { + return context; + } + } + ) ); collectionBinding.setIndex( mapKeyBinding ); } @@ -4186,11 +4115,8 @@ public class ModelBinder { manyToOneSource.getRelationalValueSources(), manyToOneBinding, manyToOneSource.areValuesNullableByDefault(), - new RelationalObjectBinder.ColumnNamingDelegate() { - @Override - public Identifier determineImplicitName(LocalMetadataBuildingContext context) { - throw new AssertionFailure( "Argh!!!" ); - } + context -> { + throw new AssertionFailure( "Argh!!!" ); } ); } @@ -4214,29 +4140,24 @@ public class ModelBinder { manyToOneSource.getRelationalValueSources(), manyToOneBinding, manyToOneSource.areValuesNullableByDefault(), - new RelationalObjectBinder.ColumnNamingDelegate() { - @Override - public Identifier determineImplicitName(final LocalMetadataBuildingContext context) { - return implicitNamingStrategy.determineBasicColumnName( - new ImplicitBasicColumnNameSource() { - @Override - public AttributePath getAttributePath() { - return manyToOneSource.getAttributePath(); - } + context -> implicitNamingStrategy.determineBasicColumnName( + new ImplicitBasicColumnNameSource() { + @Override + public AttributePath getAttributePath() { + return manyToOneSource.getAttributePath(); + } - @Override - public boolean isCollectionElement() { - return false; - } + @Override + public boolean isCollectionElement() { + return false; + } - @Override - public MetadataBuildingContext getBuildingContext() { - return context; - } - } - ); - } - } + @Override + public MetadataBuildingContext getBuildingContext() { + return context; + } + } + ) ); } } @@ -4327,10 +4248,8 @@ public class ModelBinder { final UniqueKey uk = new UniqueKey(); uk.setTable( entityBinding.getTable() ); for ( Property attributeBinding : attributeBindings ) { - final Iterator itr = attributeBinding.getColumnIterator(); - while ( itr.hasNext() ) { - final Object selectable = itr.next(); - if ( Column.class.isInstance( selectable ) ) { + for ( Selectable selectable : attributeBinding.getSelectables() ) { + if ( selectable instanceof Column ) { final Column column = (Column) selectable; uk.addColumn( column ); columnNames.add( @@ -4338,7 +4257,7 @@ public class ModelBinder { ); } } - uk.addColumns( attributeBinding.getColumnIterator() ); + uk.addColumns( attributeBinding.getValue() ); } final Identifier ukName = mappingDocument.getBuildingOptions().getImplicitNamingStrategy().determineUniqueKeyName( diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotatedJoinColumn.java b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotatedJoinColumn.java index 0741e63258..defe7b73d2 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotatedJoinColumn.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotatedJoinColumn.java @@ -7,7 +7,6 @@ package org.hibernate.cfg; import java.util.HashSet; -import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.Set; @@ -345,7 +344,7 @@ public class AnnotatedJoinColumn extends AnnotatedColumn { final ObjectNameNormalizer normalizer = context.getObjectNameNormalizer(); - Column col = (Column) identifier.getColumnIterator().next(); + Column col = identifier.getColumns().get(0); String defaultName = context.getMetadataCollector().getLogicalColumnName( identifier.getTable(), col.getQuotedName() @@ -449,17 +448,14 @@ public class AnnotatedJoinColumn extends AnnotatedColumn { } } - - public void copyReferencedStructureAndCreateDefaultJoinColumns( PersistentClass referencedEntity, - Iterator columnIterator, + SimpleValue referencedValue, SimpleValue value) { if ( !isNameDeferred() ) { throw new AssertionFailure( "Building implicit column but the column is not implicit" ); } - while ( columnIterator.hasNext() ) { - Column synthCol = (Column) columnIterator.next(); + for ( Column synthCol: referencedValue.getColumns() ) { this.linkValueUsingDefaultColumnNaming( synthCol, referencedEntity, value ); } //reset for the future @@ -586,8 +582,7 @@ public class AnnotatedJoinColumn extends AnnotatedColumn { .getEntityBinding( mappedByEntityName ); final Property mappedByProperty = mappedByEntityBinding.getProperty( mappedByPropertyName ); final SimpleValue value = (SimpleValue) mappedByProperty.getValue(); - final Iterator selectableValues = value.getColumnIterator(); - if ( !selectableValues.hasNext() ) { + if ( value.getSelectables().isEmpty() ) { throw new AnnotationException( String.format( Locale.ENGLISH, @@ -597,8 +592,8 @@ public class AnnotatedJoinColumn extends AnnotatedColumn { ) ); } - final Selectable selectable = selectableValues.next(); - if ( !Column.class.isInstance( selectable ) ) { + final Selectable selectable = value.getSelectables().get(0); + if ( !(selectable instanceof Column) ) { throw new AnnotationException( String.format( Locale.ENGLISH, @@ -608,7 +603,7 @@ public class AnnotatedJoinColumn extends AnnotatedColumn { ) ); } - if ( selectableValues.hasNext() ) { + if ( value.getSelectables().size()>1 ) { throw new AnnotationException( String.format( Locale.ENGLISH, @@ -817,9 +812,8 @@ public class AnnotatedJoinColumn extends AnnotatedColumn { MetadataBuildingContext context) { //convenient container to find whether a column is an id one or not Set idColumns = new HashSet<>(); - Iterator idColumnsIt = referencedEntity.getKey().getColumnIterator(); - while ( idColumnsIt.hasNext() ) { - idColumns.add( (Column) idColumnsIt.next() ); + for ( Selectable selectable : referencedEntity.getKey().getSelectables() ) { + idColumns.add( (Column) selectable ); } boolean isFkReferencedColumnName = false; diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java index 2a794246d2..c1a420ebb8 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java @@ -133,6 +133,7 @@ import org.hibernate.mapping.KeyValue; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; import org.hibernate.mapping.RootClass; +import org.hibernate.mapping.Selectable; import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.SingleTableSubclass; import org.hibernate.mapping.Subclass; @@ -1284,9 +1285,8 @@ public final class AnnotationBinder { persistentClass.addProperty( property ); entityBinder.setIgnoreIdAnnotations( true ); - Iterator properties = mapper.getPropertyIterator(); - while ( properties.hasNext() ) { - idPropertiesIfIdClass.add( ( ( Property ) properties.next() ).getName() ); + for ( Property prop : mapper.getProperties() ) { + idPropertiesIfIdClass.add( prop.getName() ); } return true; } @@ -3442,15 +3442,12 @@ public final class AnnotationBinder { mapToPK = false; } else { - Iterator idColumns = identifier.getColumnIterator(); List idColumnNames = new ArrayList<>(); - org.hibernate.mapping.Column currentColumn; if ( identifier.getColumnSpan() != joinColumns.length ) { mapToPK = false; } else { - while ( idColumns.hasNext() ) { - currentColumn = ( org.hibernate.mapping.Column ) idColumns.next(); + for ( org.hibernate.mapping.Column currentColumn : identifier.getColumns() ) { idColumnNames.add( currentColumn.getName() ); } for ( AnnotatedJoinColumn col : joinColumns ) { diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/BinderHelper.java b/hibernate-core/src/main/java/org/hibernate/cfg/BinderHelper.java index ce86c5b72a..2fa6d42228 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/BinderHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/BinderHelper.java @@ -34,11 +34,9 @@ import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.cfg.annotations.BasicValueBinder; import org.hibernate.cfg.annotations.EntityBinder; import org.hibernate.cfg.annotations.Nullability; -import org.hibernate.cfg.annotations.TableBinder; import org.hibernate.id.IdentifierGenerator; import org.hibernate.id.PersistentIdentifierGenerator; import org.hibernate.internal.CoreLogging; -import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.StringHelper; import org.hibernate.mapping.Any; import org.hibernate.mapping.BasicValue; @@ -49,6 +47,7 @@ import org.hibernate.mapping.Join; import org.hibernate.mapping.MappedSuperclass; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; +import org.hibernate.mapping.Selectable; import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.SyntheticProperty; import org.hibernate.mapping.Table; @@ -72,7 +71,6 @@ public class BinderHelper { public static final String ANNOTATION_STRING_DEFAULT = ""; - private static final CoreMessageLogger LOG = CoreLogging.messageLogger( BinderHelper.class ); private static final Logger log = CoreLogging.logger( BinderHelper.class ); private BinderHelper() { @@ -126,7 +124,7 @@ public class BinderHelper { columns[0].getPropertyHolder().getPersistentClass() : null; if ( AnnotatedJoinColumn.NON_PK_REFERENCE == fkEnum ) { - /** + /* * Create a synthetic property to refer to including an * embedded component value containing all the properties * mapped to the referenced columns @@ -166,7 +164,7 @@ public class BinderHelper { synthProp.setPropertyAccessorName( "embedded" ); ownerEntity.addProperty( synthProp ); //make it unique - TableBinder.createUniqueConstraint( embeddedComp ); + embeddedComp.createUniqueKey(); } else { //TODO use a ToOne type doing a second select @@ -201,12 +199,12 @@ public class BinderHelper { throw new AnnotationException( columnsList.toString() ); } - /** + /* * creating the property ref to the new synthetic property */ if ( value instanceof ToOne ) { ( (ToOne) value ).setReferencedPropertyName( syntheticPropertyName ); - ( (ToOne) value ).setReferenceToPrimaryKey( syntheticPropertyName == null ); + ( (ToOne) value ).setReferenceToPrimaryKey( false ); context.getMetadataCollector().addUniquePropertyReference( ownerEntity.getEntityName(), syntheticPropertyName @@ -267,11 +265,11 @@ public class BinderHelper { columnsToProperty.put( column, new HashSet<>() ); } boolean isPersistentClass = columnOwner instanceof PersistentClass; - Iterator it = isPersistentClass ? - ( (PersistentClass) columnOwner ).getPropertyIterator() : - ( (Join) columnOwner ).getPropertyIterator(); - while ( it.hasNext() ) { - matchColumnsByProperty( (Property) it.next(), columnsToProperty ); + List properties = isPersistentClass ? + ( (PersistentClass) columnOwner ).getProperties() : + ( (Join) columnOwner ).getProperties(); + for (Property property : properties) { + matchColumnsByProperty( property, columnsToProperty ); } if ( isPersistentClass ) { matchColumnsByProperty( ( (PersistentClass) columnOwner ).getIdentifierProperty(), columnsToProperty ); @@ -314,13 +312,12 @@ public class BinderHelper { // } // } else { - Iterator columnIt = property.getColumnIterator(); - while ( columnIt.hasNext() ) { - //can be a Formula so we don't cast - Object column = columnIt.next(); + for (Selectable selectable : property.getSelectables()) { + //can be a Formula, so we don't cast //noinspection SuspiciousMethodCalls - if ( columnsToProperty.containsKey( column ) ) { - columnsToProperty.get( column ).add( property ); + if ( columnsToProperty.containsKey( selectable ) ) { + //noinspection SuspiciousMethodCalls + columnsToProperty.get( selectable ).add( property ); } } } @@ -526,7 +523,7 @@ public class BinderHelper { if ( id.getColumnSpan() == 1 ) { params.setProperty( PersistentIdentifierGenerator.PK, - ( (Column) id.getColumnIterator().next() ).getName() + id.getColumns().get(0).getName() ); } // YUCK! but cannot think of a clean way to do this given the string-config based scheme @@ -774,7 +771,6 @@ public class BinderHelper { ); } - @SuppressWarnings("ConstantConditions") private static GenerationType interpretGenerationType(GeneratedValue generatedValueAnn) { if ( generatedValueAnn.strategy() == null ) { return GenerationType.AUTO; @@ -854,7 +850,7 @@ public class BinderHelper { ); value.setDiscriminatorValueMappings( discriminatorValueMappings ); - BasicValueBinder keyValueBinder = new BasicValueBinder( BasicValueBinder.Kind.ANY_KEY, context ); + BasicValueBinder keyValueBinder = new BasicValueBinder<>( BasicValueBinder.Kind.ANY_KEY, context ); assert keyColumns.length == 1; keyColumns[0].setTable( value.getTable() ); keyValueBinder.setColumns( keyColumns ); @@ -887,8 +883,8 @@ public class BinderHelper { if ( valuesAnn != null ) { final AnyDiscriminatorValue[] valueAnns = valuesAnn.value(); if ( valueAnns != null && valueAnns.length > 0 ) { - for ( int i = 0; i < valueAnns.length; i++ ) { - consumer.accept( valueAnns[i] ); + for ( AnyDiscriminatorValue ann : valueAnns ) { + consumer.accept(ann); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/CopyIdentifierComponentSecondPass.java b/hibernate-core/src/main/java/org/hibernate/cfg/CopyIdentifierComponentSecondPass.java index 1993a43972..a01a84d515 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/CopyIdentifierComponentSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/CopyIdentifierComponentSecondPass.java @@ -6,7 +6,6 @@ */ package org.hibernate.cfg; -import java.util.Iterator; import java.util.Locale; import java.util.Map; @@ -64,7 +63,6 @@ public class CopyIdentifierComponentSecondPass extends FkSecondPass { } @Override - @SuppressWarnings({ "unchecked" }) public void doSecondPass(Map persistentClasses) throws MappingException { PersistentClass referencedPersistentClass = (PersistentClass) persistentClasses.get( referencedEntityName ); // TODO better error names @@ -78,8 +76,6 @@ public class CopyIdentifierComponentSecondPass extends FkSecondPass { ); } Component referencedComponent = (Component) referencedPersistentClass.getIdentifier(); - Iterator properties = referencedComponent.getPropertyIterator(); - //prepare column name structure boolean isExplicitReference = true; @@ -101,8 +97,7 @@ public class CopyIdentifierComponentSecondPass extends FkSecondPass { } MutableInteger index = new MutableInteger(); - while ( properties.hasNext() ) { - Property referencedProperty = properties.next(); + for ( Property referencedProperty : referencedComponent.getProperties() ) { if ( referencedProperty.isComposite() ) { Property property = createComponentProperty( referencedPersistentClass, isExplicitReference, columnByReferencedName, index, referencedProperty ); component.addProperty( property ); @@ -135,10 +130,7 @@ public class CopyIdentifierComponentSecondPass extends FkSecondPass { value.setComponentClassName( referencedValue.getComponentClassName() ); - Iterator propertyIterator = referencedValue.getPropertyIterator(); - while(propertyIterator.hasNext()) { - Property referencedComponentProperty = propertyIterator.next(); - + for ( Property referencedComponentProperty : referencedValue.getProperties() ) { if ( referencedComponentProperty.isComposite() ) { Property componentProperty = createComponentProperty( referencedValue.getOwner(), isExplicitReference, columnByReferencedName, index, referencedComponentProperty ); value.addProperty( componentProperty ); @@ -169,19 +161,18 @@ public class CopyIdentifierComponentSecondPass extends FkSecondPass { property.setValue( value ); final SimpleValue referencedValue = (SimpleValue) referencedProperty.getValue(); value.copyTypeFrom( referencedValue ); - final Iterator columns = referencedValue.getColumnIterator(); if ( joinColumns[0].isNameDeferred() ) { joinColumns[0].copyReferencedStructureAndCreateDefaultJoinColumns( - referencedPersistentClass, - columns, - value); + referencedPersistentClass, + referencedValue, + value + ); } else { //FIXME take care of Formula - while ( columns.hasNext() ) { - final Selectable selectable = columns.next(); - if ( ! Column.class.isInstance( selectable ) ) { + for ( Selectable selectable : referencedValue.getSelectables() ) { + if ( !(selectable instanceof Column) ) { log.debug( "Encountered formula definition; skipping" ); continue; } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/IndexOrUniqueKeySecondPass.java b/hibernate-core/src/main/java/org/hibernate/cfg/IndexOrUniqueKeySecondPass.java index 9bbf281ec2..c120890f25 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/IndexOrUniqueKeySecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/IndexOrUniqueKeySecondPass.java @@ -18,6 +18,7 @@ import org.hibernate.mapping.Component; import org.hibernate.mapping.Index; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; +import org.hibernate.mapping.Selectable; import org.hibernate.mapping.Table; import org.hibernate.mapping.UniqueKey; @@ -64,7 +65,7 @@ public class IndexOrUniqueKeySecondPass implements SecondPass { } @Override - public void doSecondPass(Map persistentClasses) throws MappingException { + public void doSecondPass(Map persistentClasses) throws MappingException { if ( columns != null ) { for ( String column1 : columns ) { addConstraintToColumn( column1 ); @@ -79,18 +80,18 @@ public class IndexOrUniqueKeySecondPass implements SecondPass { propertyHolder.getPersistentClass().getEntityName() : propertyHolder.getEntityName(); - final PersistentClass persistentClass = (PersistentClass) persistentClasses.get( entityName ); + final PersistentClass persistentClass = persistentClasses.get( entityName ); final Property property = persistentClass.getProperty( column.getPropertyName() ); if ( property.getValue() instanceof Component ) { final Component component = (Component) property.getValue(); List columns = new ArrayList<>(); - component.getColumnIterator().forEachRemaining( selectable -> { + for ( Selectable selectable: component.getSelectables() ) { if ( selectable instanceof Column ) { columns.add( (Column) selectable ); } - } ); + } addConstraintToColumns( columns ); } else { diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/OneToOneSecondPass.java b/hibernate-core/src/main/java/org/hibernate/cfg/OneToOneSecondPass.java index d4fe9060fe..7214edbe48 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/OneToOneSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/OneToOneSecondPass.java @@ -27,7 +27,7 @@ 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.Selectable; import org.hibernate.mapping.SortableValue; import org.hibernate.type.ForeignKeyDirection; @@ -36,18 +36,18 @@ import org.hibernate.type.ForeignKeyDirection; * - */ public class OneToOneSecondPass implements SecondPass { - private MetadataBuildingContext buildingContext; - private String mappedBy; - private String ownerEntity; - private String ownerProperty; - private PropertyHolder propertyHolder; - private boolean ignoreNotFound; - private PropertyData inferredData; - private XClass targetEntity; - private boolean cascadeOnDelete; - private boolean optional; - private String cascadeStrategy; - private AnnotatedJoinColumn[] joinColumns; + private final MetadataBuildingContext buildingContext; + private final String mappedBy; + private final String ownerEntity; + private final String ownerProperty; + private final PropertyHolder propertyHolder; + private final boolean ignoreNotFound; + private final PropertyData inferredData; + private final XClass targetEntity; + private final boolean cascadeOnDelete; + private final boolean optional; + private final String cascadeStrategy; + private final AnnotatedJoinColumn[] joinColumns; //that sucks, we should read that from the property mainly public OneToOneSecondPass( @@ -176,10 +176,10 @@ public class OneToOneSecondPass implements SecondPass { propertyHolder.addProperty( prop, inferredData.getDeclaringClass() ); } else if ( otherSideProperty.getValue() instanceof ManyToOne ) { - Iterator it = otherSide.getJoinIterator(); + Iterator it = otherSide.getJoinIterator(); Join otherSideJoin = null; while ( it.hasNext() ) { - Join otherSideJoinValue = (Join) it.next(); + Join otherSideJoinValue = it.next(); if ( otherSideJoinValue.containsProperty( otherSideProperty ) ) { otherSideJoin = otherSideJoinValue; break; @@ -200,9 +200,7 @@ public class OneToOneSecondPass implements SecondPass { manyToOne.setUnwrapProxy( value.isUnwrapProxy() ); manyToOne.markAsLogicalOneToOne(); prop.setValue( manyToOne ); - Iterator otherSideJoinKeyColumns = otherSideJoin.getKey().getColumnIterator(); - while ( otherSideJoinKeyColumns.hasNext() ) { - Column column = (Column) otherSideJoinKeyColumns.next(); + for ( Column column: otherSideJoin.getKey().getColumns() ) { Column copy = new Column(); copy.setLength( column.getLength() ); copy.setScale( column.getScale() ); @@ -287,9 +285,7 @@ public class OneToOneSecondPass implements SecondPass { //TODO support for inverse and optional join.setOptional( true ); //perhaps not quite per-spec, but a Good Thing anyway key.setCascadeDeleteEnabled( false ); - Iterator mappedByColumns = otherSideProperty.getValue().getColumnIterator(); - while ( mappedByColumns.hasNext() ) { - Column column = (Column) mappedByColumns.next(); + for ( Column column: otherSideProperty.getValue().getColumns() ) { Column copy = new Column(); copy.setLength( column.getLength() ); copy.setScale( column.getScale() ); diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/PkDrivenByDefaultMapsIdSecondPass.java b/hibernate-core/src/main/java/org/hibernate/cfg/PkDrivenByDefaultMapsIdSecondPass.java index f325b9823d..e9c72ba319 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/PkDrivenByDefaultMapsIdSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/PkDrivenByDefaultMapsIdSecondPass.java @@ -50,7 +50,7 @@ public class PkDrivenByDefaultMapsIdSecondPass extends FkSecondPass { } TableBinder.linkJoinColumnWithValueOverridingNameIfImplicit( referencedEntity, - referencedEntity.getKey().getColumnIterator(), + referencedEntity.getKey(), columns, value); } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/SecondPass.java b/hibernate-core/src/main/java/org/hibernate/cfg/SecondPass.java index 5053f967bb..c3b3b48983 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/SecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/SecondPass.java @@ -8,6 +8,7 @@ package org.hibernate.cfg; import java.io.Serializable; import org.hibernate.MappingException; +import org.hibernate.mapping.PersistentClass; /** * Second pass operation @@ -16,7 +17,7 @@ import org.hibernate.MappingException; */ public interface SecondPass extends Serializable { - void doSecondPass(java.util.Map persistentClasses) + void doSecondPass(java.util.Map persistentClasses) throws MappingException; } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/ToOneFkSecondPass.java b/hibernate-core/src/main/java/org/hibernate/cfg/ToOneFkSecondPass.java index 59438c7508..323bf4930f 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/ToOneFkSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/ToOneFkSecondPass.java @@ -30,10 +30,10 @@ import org.hibernate.mapping.ToOne; * @author Emmanuel Bernard */ public class ToOneFkSecondPass extends FkSecondPass { - private MetadataBuildingContext buildingContext; - private boolean unique; - private String path; - private String entityClassName; + private final MetadataBuildingContext buildingContext; + private final boolean unique; + private final String path; + private final String entityClassName; public ToOneFkSecondPass( ToOne value, @@ -76,9 +76,9 @@ public class ToOneFkSecondPass extends FkSecondPass { if ( path.startsWith( "id." ) ) { localPath = path.substring( 3 ); } - Iterator it = ( (Component) valueIdentifier ).getPropertyIterator(); - while ( it.hasNext() ) { - Property idProperty = (Property) it.next(); + + Component component = (Component) valueIdentifier; + for ( Property idProperty : component.getProperties() ) { if ( localPath.equals( idProperty.getName() ) || localPath.startsWith( idProperty.getName() + "." ) ) { return true; } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java index 0adca5c114..af9cb85d5b 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java @@ -1352,9 +1352,7 @@ public abstract class CollectionBinder { private static String buildOrderById(PersistentClass associatedClass, String order) { final StringBuilder sb = new StringBuilder(); - final Iterator columnIterator = associatedClass.getIdentifier().getColumnIterator(); - while ( columnIterator.hasNext() ) { - final Selectable selectable = columnIterator.next(); + for ( Selectable selectable: associatedClass.getIdentifier().getSelectables() ) { sb.append( selectable.getText() ); sb.append( order ); sb.append( ", " ); @@ -1812,7 +1810,7 @@ public abstract class CollectionBinder { } else if ( owner.getIdentifierMapper() != null && owner.getIdentifierMapper().getPropertySpan() > 0 ) { // use the access for the owning entity's "id mapper", if one - Property prop = owner.getIdentifierMapper().getPropertyIterator().next(); + Property prop = owner.getIdentifierMapper().getProperties().get(0); baseAccessType = prop.getPropertyAccessorName().equals( "property" ) ? AccessType.PROPERTY : AccessType.FIELD; @@ -2016,16 +2014,16 @@ public abstract class CollectionBinder { final String mappedBy = columns[0].getMappedBy(); if ( StringHelper.isNotEmpty( mappedBy ) ) { final Property property = referencedEntity.getRecursiveProperty( mappedBy ); - Iterator mappedByColumns; + List mappedByColumns; if ( property.getValue() instanceof Collection ) { - mappedByColumns = ( (Collection) property.getValue() ).getKey().getColumnIterator(); + mappedByColumns = ( (Collection) property.getValue() ).getKey().getSelectables(); } else { //find the appropriate reference key, can be in a join Iterator joinsIt = referencedEntity.getJoinIterator(); KeyValue key = null; while ( joinsIt.hasNext() ) { - Join join = (Join) joinsIt.next(); + Join join = joinsIt.next(); if ( join.containsProperty( property ) ) { key = join.getKey(); break; @@ -2034,10 +2032,10 @@ public abstract class CollectionBinder { if ( key == null ) { key = property.getPersistentClass().getIdentifier(); } - mappedByColumns = key.getColumnIterator(); + mappedByColumns = key.getSelectables(); } - while ( mappedByColumns.hasNext() ) { - Column column = (Column) mappedByColumns.next(); + for ( Selectable selectable: mappedByColumns ) { + Column column = (Column) selectable; columns[0].linkValueUsingAColumnCopy( column, value ); } String referencedPropertyName = diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/MapBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/MapBinder.java index 37aec75024..1f60f9157a 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/MapBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/MapBinder.java @@ -119,11 +119,11 @@ public class MapBinder extends CollectionBinder { if ( indexValue.getColumnSpan() != 1 ) { throw new AssertionFailure( "Map key mapped by @MapKeyColumn does not have 1 column" ); } - final Selectable selectable = indexValue.getColumnIterator().next(); + final Selectable selectable = indexValue.getSelectables().get(0); if ( selectable.isFormula() ) { throw new AssertionFailure( "Map key mapped by @MapKeyColumn is a Formula" ); } - Column column = (Column) map.getIndex().getColumnIterator().next(); + Column 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; @@ -138,11 +138,10 @@ public class MapBinder extends CollectionBinder { } } - private boolean propertyIteratorContainsColumn(Iterator propertyIterator, Column column) { - for ( Iterator it = propertyIterator; it.hasNext(); ) { - final Property property = (Property) it.next(); - for ( Iterator selectableIterator = property.getColumnIterator(); selectableIterator.hasNext(); ) { - final Selectable selectable = selectableIterator.next(); + private boolean propertyIteratorContainsColumn(Iterator propertyIterator, Column column) { + for (; propertyIterator.hasNext(); ) { + final Property property = propertyIterator.next(); + for ( Selectable selectable: property.getSelectables() ) { if ( column.equals( selectable ) ) { final Column iteratedColumn = (Column) selectable; if ( column.getValue().getTable().equals( iteratedColumn.getValue().getTable() ) ) { @@ -190,7 +189,7 @@ public class MapBinder extends CollectionBinder { //this is a true Map mapping //TODO ugly copy/paste from CollectionBinder.bindManyToManySecondPass String mapKeyType; - Class target = void.class; + Class target = void.class; /* * target has priority over reflection for the map key type * JPA 2 has priority @@ -264,8 +263,9 @@ public class MapBinder extends CollectionBinder { : AccessType.FIELD; } else if ( owner.getIdentifierMapper() != null && owner.getIdentifierMapper().getPropertySpan() > 0 ) { - Property prop = (Property) owner.getIdentifierMapper().getPropertyIterator().next(); - accessType = prop.getPropertyAccessorName().equals( "property" ) ? AccessType.PROPERTY + Property prop = owner.getIdentifierMapper().getProperties().get(0); + accessType = prop.getPropertyAccessorName().equals( "property" ) + ? AccessType.PROPERTY : AccessType.FIELD; } else { @@ -301,7 +301,7 @@ public class MapBinder extends CollectionBinder { mapValue.setIndex( component ); } else { - final BasicValueBinder elementBinder = new BasicValueBinder( BasicValueBinder.Kind.MAP_KEY, buildingContext ); + final BasicValueBinder elementBinder = new BasicValueBinder<>( BasicValueBinder.Kind.MAP_KEY, buildingContext ); elementBinder.setReturnedClassName( mapKeyType ); AnnotatedColumn[] elementColumns = mapKeyColumns; @@ -423,11 +423,9 @@ public class MapBinder extends CollectionBinder { if ( value instanceof Component ) { Component component = (Component) value; - Iterator properties = component.getPropertyIterator(); Component indexComponent = new Component( getBuildingContext(), collection ); indexComponent.setComponentClassName( component.getComponentClassName() ); - while ( properties.hasNext() ) { - Property current = (Property) properties.next(); + for ( Property current : component.getProperties() ) { Property newProperty = new Property(); newProperty.setCascade( current.getCascade() ); newProperty.setValueGenerationStrategy( current.getValueGenerationStrategy() ); @@ -489,9 +487,7 @@ public class MapBinder extends CollectionBinder { targetValue = new BasicValue( getBuildingContext(), mapKeyTable ); targetValue.copyTypeFrom( sourceValue ); } - final Iterator columns = sourceValue.getColumnIterator(); - while ( columns.hasNext() ) { - Selectable current = columns.next(); + for ( Selectable current : sourceValue.getSelectables() ) { if ( current instanceof Column ) { targetValue.addColumn( ( (Column) current ).clone() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/ResultsetMappingSecondPass.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/ResultsetMappingSecondPass.java index 170272113a..04fa0f09fc 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/ResultsetMappingSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/ResultsetMappingSecondPass.java @@ -216,59 +216,59 @@ public class ResultsetMappingSecondPass implements QuerySecondPass { } return followers; } - - private Iterator getSubPropertyIterator(PersistentClass pc, String reducedName) { - Value value = pc.getRecursiveProperty( reducedName ).getValue(); - Iterator parentPropIter; - if ( value instanceof Component ) { - Component comp = (Component) value; - parentPropIter = comp.getPropertyIterator(); - } - else if ( value instanceof ToOne ) { - ToOne toOne = (ToOne) value; - PersistentClass referencedPc = context.getMetadataCollector().getEntityBinding( toOne.getReferencedEntityName() ); - if ( toOne.getReferencedPropertyName() != null ) { - try { - parentPropIter = ( (Component) referencedPc.getRecursiveProperty( - toOne.getReferencedPropertyName() - ).getValue() ).getPropertyIterator(); - } - catch (ClassCastException e) { - throw new MappingException( - "dotted notation references neither a component nor a many/one to one", e - ); - } - } - else { - try { - if ( referencedPc.getIdentifierMapper() == null ) { - parentPropIter = ( (Component) referencedPc.getIdentifierProperty() - .getValue() ).getPropertyIterator(); - } - else { - parentPropIter = referencedPc.getIdentifierMapper().getPropertyIterator(); - } - } - catch (ClassCastException e) { - throw new MappingException( - "dotted notation references neither a component nor a many/one to one", e - ); - } - } - } - else { - throw new MappingException( "dotted notation references neither a component nor a many/one to one" ); - } - return parentPropIter; - } - - private static int getIndexOfFirstMatchingProperty(List propertyNames, String follower) { - int propertySize = propertyNames.size(); - for (int propIndex = 0; propIndex < propertySize; propIndex++) { - if ( ( (String) propertyNames.get( propIndex ) ).startsWith( follower ) ) { - return propIndex; - } - } - return -1; - } +// +// private Iterator getSubPropertyIterator(PersistentClass pc, String reducedName) { +// Value value = pc.getRecursiveProperty( reducedName ).getValue(); +// Iterator parentPropIter; +// if ( value instanceof Component ) { +// Component comp = (Component) value; +// parentPropIter = comp.getPropertyIterator(); +// } +// else if ( value instanceof ToOne ) { +// ToOne toOne = (ToOne) value; +// PersistentClass referencedPc = context.getMetadataCollector().getEntityBinding( toOne.getReferencedEntityName() ); +// if ( toOne.getReferencedPropertyName() != null ) { +// try { +// parentPropIter = ( (Component) referencedPc.getRecursiveProperty( +// toOne.getReferencedPropertyName() +// ).getValue() ).getPropertyIterator(); +// } +// catch (ClassCastException e) { +// throw new MappingException( +// "dotted notation references neither a component nor a many/one to one", e +// ); +// } +// } +// else { +// try { +// if ( referencedPc.getIdentifierMapper() == null ) { +// parentPropIter = ( (Component) referencedPc.getIdentifierProperty() +// .getValue() ).getPropertyIterator(); +// } +// else { +// parentPropIter = referencedPc.getIdentifierMapper().getPropertyIterator(); +// } +// } +// catch (ClassCastException e) { +// throw new MappingException( +// "dotted notation references neither a component nor a many/one to one", e +// ); +// } +// } +// } +// else { +// throw new MappingException( "dotted notation references neither a component nor a many/one to one" ); +// } +// return parentPropIter; +// } +// +// private static int getIndexOfFirstMatchingProperty(List propertyNames, String follower) { +// int propertySize = propertyNames.size(); +// for (int propIndex = 0; propIndex < propertySize; propIndex++) { +// if ( ( (String) propertyNames.get( propIndex ) ).startsWith( follower ) ) { +// return propIndex; +// } +// } +// return -1; +// } } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/TableBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/TableBinder.java index 002bcb29ad..3ccfc2b365 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/TableBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/TableBinder.java @@ -29,6 +29,7 @@ import org.hibernate.cfg.IndexOrUniqueKeySecondPass; import org.hibernate.cfg.JPAIndexHolder; import org.hibernate.cfg.ObjectNameSource; import org.hibernate.cfg.UniqueConstraintHolder; +import org.hibernate.dialect.Dialect; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.collections.CollectionHelper; @@ -39,6 +40,7 @@ import org.hibernate.mapping.DependantValue; import org.hibernate.mapping.JoinedSubclass; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; +import org.hibernate.mapping.Selectable; import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.SortableValue; import org.hibernate.mapping.Table; @@ -52,7 +54,6 @@ import org.jboss.logging.Logger; * * @author Emmanuel Bernard */ -@SuppressWarnings("unchecked") public class TableBinder { //TODO move it to a getter/setter strategy private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, TableBinder.class.getName() ); @@ -525,13 +526,6 @@ public class TableBinder { return table; } - private static String extract(Identifier identifier) { - if ( identifier == null ) { - return null; - } - return identifier.render(); - } - public static void bindFk( PersistentClass referencedEntity, PersistentClass destinationEntity, @@ -551,14 +545,14 @@ public class TableBinder { } final String mappedByProperty = columns[0].getMappedBy(); if ( StringHelper.isNotEmpty( mappedByProperty ) ) { - /** + /* * Get the columns of the mapped-by property * copy them and link the copy to the actual value */ LOG.debugf( "Retrieving property %s.%s", associatedClass.getEntityName(), mappedByProperty ); final Property property = associatedClass.getRecursiveProperty( columns[0].getMappedBy() ); - Iterator mappedByColumns; + List mappedByColumns; if ( property.getValue() instanceof Collection ) { Collection collection = ( (Collection) property.getValue() ); Value element = collection.getElement(); @@ -568,31 +562,25 @@ public class TableBinder { + associatedClass.getEntityName() + "." + mappedByProperty ); } - mappedByColumns = element.getColumnIterator(); + mappedByColumns = element.getColumns(); } else { - mappedByColumns = property.getValue().getColumnIterator(); + mappedByColumns = property.getValue().getColumns(); } - while ( mappedByColumns.hasNext() ) { - Column column = (Column) mappedByColumns.next(); + for ( Column column: mappedByColumns ) { columns[0].overrideFromReferencedColumnIfNecessary( column ); columns[0].linkValueUsingAColumnCopy( column, value ); } } else if ( columns[0].isImplicit() ) { - /** + /* * if columns are implicit, then create the columns based on the * referenced entity id columns */ - Iterator idColumns; - if ( referencedEntity instanceof JoinedSubclass ) { - idColumns = referencedEntity.getKey().getColumnIterator(); - } - else { - idColumns = referencedEntity.getIdentifier().getColumnIterator(); - } - while ( idColumns.hasNext() ) { - Column column = (Column) idColumns.next(); + List idColumns = referencedEntity instanceof JoinedSubclass + ? referencedEntity.getKey().getColumns() + : referencedEntity.getIdentifier().getColumns(); + for ( Column column: idColumns ) { columns[0].linkValueUsingDefaultColumnNaming( column, referencedEntity, value ); columns[0].overrideFromReferencedColumnIfNecessary( column ); } @@ -635,7 +623,7 @@ public class TableBinder { ); } linkJoinColumnWithValueOverridingNameIfImplicit( - referencedEntity, synthProp.getColumnIterator(), columns, value + referencedEntity, synthProp.getValue(), columns, value ); if ( value instanceof SortableValue ) { ( (SortableValue) value ).sortProperties(); @@ -654,7 +642,7 @@ public class TableBinder { } linkJoinColumnWithValueOverridingNameIfImplicit( referencedEntity, - referencedEntity.getIdentifier().getColumnIterator(), + referencedEntity.getIdentifier(), columns, value ); @@ -668,25 +656,25 @@ public class TableBinder { ( (Component) referencedEntity.getKey() ).sortProperties(); } //explicit referencedColumnName - Iterator idColItr = referencedEntity.getKey().getColumnIterator(); - Column col; + List idColumns = referencedEntity.getKey().getColumns(); //works cause the pk has to be on the primary table Table table = referencedEntity.getTable(); - if ( !idColItr.hasNext() ) { + if ( idColumns.isEmpty() ) { LOG.debug( "No column in the identifier!" ); } - while ( idColItr.hasNext() ) { + for ( Column col: idColumns ) { boolean match = false; //for each PK column, find the associated FK column. - col = (Column) idColItr.next(); - final String colName = col.getQuotedName( buildingContext.getMetadataCollector().getDatabase().getJdbcEnvironment().getDialect() ); + Dialect dialect = buildingContext.getMetadataCollector().getDatabase() + .getJdbcEnvironment().getDialect(); + final String colName = col.getQuotedName(dialect); for (AnnotatedJoinColumn joinCol : columns) { String referencedColumn = joinCol.getReferencedColumn(); referencedColumn = buildingContext.getMetadataCollector().getPhysicalColumnName( table, referencedColumn ); - //In JPA 2 referencedColumnName is case insensitive + //In JPA 2 referencedColumnName is case-insensitive if ( referencedColumn.equalsIgnoreCase( colName ) ) { //proper join column if ( joinCol.isNameDeferred() ) { @@ -718,15 +706,16 @@ public class TableBinder { } value.createForeignKey(); if ( unique ) { - createUniqueConstraint( value ); + value.createUniqueKey(); } } public static void linkJoinColumnWithValueOverridingNameIfImplicit( PersistentClass referencedEntity, - Iterator columnIterator, + Value v, AnnotatedJoinColumn[] columns, SimpleValue value) { + Iterator columnIterator = v.getColumnIterator(); for (AnnotatedJoinColumn joinCol : columns) { Column synthCol = (Column) columnIterator.next(); if ( joinCol.isNameDeferred() ) { @@ -740,15 +729,6 @@ public class TableBinder { } } - public static void createUniqueConstraint(Value value) { - Iterator iter = value.getColumnIterator(); - ArrayList cols = new ArrayList(); - while ( iter.hasNext() ) { - cols.add( iter.next() ); - } - value.getTable().createUniqueKey( cols ); - } - public static void addIndexes(Table hibTable, Index[] indexes, MetadataBuildingContext buildingContext) { for (Index index : indexes) { //no need to handle inSecondPass here since it is only called from EntityBinder diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/beanvalidation/TypeSafeActivator.java b/hibernate-core/src/main/java/org/hibernate/cfg/beanvalidation/TypeSafeActivator.java index 9ff0c6f0be..6f4fc4e4c0 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/beanvalidation/TypeSafeActivator.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/beanvalidation/TypeSafeActivator.java @@ -10,7 +10,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; -import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.Set; @@ -280,9 +279,7 @@ class TypeSafeActivator { ConstraintDescriptor minConstraint = (ConstraintDescriptor) descriptor; long min = minConstraint.getAnnotation().value(); - final Iterator itor = property.getColumnIterator(); - if ( itor.hasNext() ) { - final Selectable selectable = itor.next(); + for ( Selectable selectable : property.getSelectables() ) { if ( selectable instanceof Column ) { Column col = (Column) selectable; String checkConstraint = col.getQuotedName(dialect) + ">=" + min; @@ -298,9 +295,7 @@ class TypeSafeActivator { ConstraintDescriptor maxConstraint = (ConstraintDescriptor) descriptor; long max = maxConstraint.getAnnotation().value(); - final Iterator itor = property.getColumnIterator(); - if ( itor.hasNext() ) { - final Selectable selectable = itor.next(); + for ( Selectable selectable : property.getSelectables() ) { if ( selectable instanceof Column ) { Column col = (Column) selectable; String checkConstraint = col.getQuotedName( dialect ) + "<=" + max; @@ -327,9 +322,7 @@ class TypeSafeActivator { if ( !( property.getPersistentClass() instanceof SingleTableSubclass ) ) { //composite should not add not-null on all columns if ( !property.isComposite() ) { - final Iterator itr = property.getColumnIterator(); - while ( itr.hasNext() ) { - final Selectable selectable = itr.next(); + for ( Selectable selectable : property.getSelectables() ) { if ( selectable instanceof Column ) { ((Column) selectable).setNullable( false ); } @@ -356,9 +349,7 @@ class TypeSafeActivator { int integerDigits = digitsConstraint.getAnnotation().integer(); int fractionalDigits = digitsConstraint.getAnnotation().fraction(); - final Iterator itor = property.getColumnIterator(); - if ( itor.hasNext() ) { - final Selectable selectable = itor.next(); + for ( Selectable selectable : property.getSelectables() ) { if ( selectable instanceof Column ) { Column col = (Column) selectable; col.setPrecision( integerDigits + fractionalDigits ); @@ -376,10 +367,7 @@ class TypeSafeActivator { ConstraintDescriptor sizeConstraint = (ConstraintDescriptor) descriptor; int max = sizeConstraint.getAnnotation().max(); - final Iterator itor = property.getColumnIterator(); - if ( itor.hasNext() ) { - final Selectable selectable = itor.next(); - Column col = (Column) selectable; + for ( Column col : property.getColumns() ) { if ( max < Integer.MAX_VALUE ) { col.setLength( max ); } @@ -394,9 +382,7 @@ class TypeSafeActivator { && String.class.equals( propertyDescriptor.getElementClass() ) ) { int max = (Integer) descriptor.getAttributes().get( "max" ); - final Iterator itor = property.getColumnIterator(); - if ( itor.hasNext() ) { - final Selectable selectable = itor.next(); + for ( Selectable selectable : property.getSelectables() ) { if ( selectable instanceof Column ) { Column col = (Column) selectable; if ( max < Integer.MAX_VALUE ) { diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/internal/NullableDiscriminatorColumnSecondPass.java b/hibernate-core/src/main/java/org/hibernate/cfg/internal/NullableDiscriminatorColumnSecondPass.java index afd3d57c68..54e45ba4bd 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/internal/NullableDiscriminatorColumnSecondPass.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/internal/NullableDiscriminatorColumnSecondPass.java @@ -28,9 +28,7 @@ public class NullableDiscriminatorColumnSecondPass implements SecondPass { public void doSecondPass(Map persistentClasses) throws MappingException { PersistentClass rootPersistenceClass = (PersistentClass) persistentClasses.get( rootEntityName ); if ( hasNullDiscriminatorValue( rootPersistenceClass ) ) { - for ( Iterator iterator = rootPersistenceClass.getDiscriminator().getColumnIterator(); - iterator.hasNext(); ) { - Selectable selectable = iterator.next(); + for ( Selectable selectable: rootPersistenceClass.getDiscriminator().getSelectables() ) { if ( selectable instanceof Column ) { ( (Column) selectable ).setNullable( true ); } @@ -38,7 +36,6 @@ public class NullableDiscriminatorColumnSecondPass implements SecondPass { } } - @SuppressWarnings({ "unchecked" }) private boolean hasNullDiscriminatorValue(PersistentClass rootPersistenceClass) { if ( rootPersistenceClass.isDiscriminatorValueNull() ) { return true; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/temptable/TemporaryTable.java b/hibernate-core/src/main/java/org/hibernate/dialect/temptable/TemporaryTable.java index dd3bdbb6a1..d05ee2561d 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/temptable/TemporaryTable.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/temptable/TemporaryTable.java @@ -125,12 +125,10 @@ public class TemporaryTable implements Exportable, Contributable { final PersistentClass entityBinding = runtimeModelCreationContext.getBootModel() .getEntityBinding( entityDescriptor.getEntityName() ); - final Iterator itr = entityBinding.getKey().getColumnIterator(); final Iterator jdbcMappings = entityDescriptor.getIdentifierMapping() .getJdbcMappings() .iterator(); - while ( itr.hasNext() ) { - final Column column = (Column) itr.next(); + for ( Column column : entityBinding.getKey().getColumns() ) { final JdbcMapping jdbcMapping = jdbcMappings.next(); columns.add( new TemporaryTableColumn( @@ -155,8 +153,8 @@ public class TemporaryTable implements Exportable, Contributable { if ( !( fkTarget instanceof EntityIdentifierMapping ) ) { final Value value = entityBinding.getSubclassProperty( pluralAttribute.getAttributeName() ) .getValue(); - final Iterator columnIterator = ( (Collection) value ).getKey() - .getColumnIterator(); + final Iterator columnIterator = + ( (Collection) value ).getKey().getColumnIterator(); fkTarget.forEachSelectable( (columnIndex, selection) -> { final Selectable selectable = columnIterator.next(); @@ -207,12 +205,10 @@ public class TemporaryTable implements Exportable, Contributable { final boolean hasOptimizer; if ( identityColumn ) { hasOptimizer = false; - final Iterator itr = entityBinding.getKey().getColumnIterator(); final Iterator jdbcMappings = entityDescriptor.getIdentifierMapping() .getJdbcMappings() .iterator(); - while ( itr.hasNext() ) { - final Column column = (Column) itr.next(); + for ( Column column : entityBinding.getKey().getColumns() ) { final JdbcMapping jdbcMapping = jdbcMappings.next(); columns.add( new TemporaryTableColumn( @@ -237,12 +233,10 @@ public class TemporaryTable implements Exportable, Contributable { hasOptimizer = false; } } - final Iterator itr = entityBinding.getKey().getColumnIterator(); final Iterator jdbcMappings = entityDescriptor.getIdentifierMapping() .getJdbcMappings() .iterator(); - while ( itr.hasNext() ) { - final Column column = (Column) itr.next(); + for ( Column column : entityBinding.getKey().getColumns() ) { final JdbcMapping jdbcMapping = jdbcMappings.next(); columns.add( new TemporaryTableColumn( @@ -259,7 +253,7 @@ public class TemporaryTable implements Exportable, Contributable { final EntityDiscriminatorMapping discriminatorMapping = entityDescriptor.getDiscriminatorMapping(); if ( entityBinding.getDiscriminator() != null && !discriminatorMapping.isFormula() ) { - final Column discriminator = (Column) entityBinding.getDiscriminator().getColumnIterator().next(); + final Column discriminator = entityBinding.getDiscriminator().getColumns().get(0); columns.add( new TemporaryTableColumn( temporaryTable, diff --git a/hibernate-core/src/main/java/org/hibernate/id/ExportableColumn.java b/hibernate-core/src/main/java/org/hibernate/id/ExportableColumn.java index 21e81a1e04..f4a82593b7 100644 --- a/hibernate-core/src/main/java/org/hibernate/id/ExportableColumn.java +++ b/hibernate-core/src/main/java/org/hibernate/id/ExportableColumn.java @@ -6,7 +6,6 @@ */ package org.hibernate.id; -import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; @@ -69,14 +68,19 @@ public class ExportableColumn extends Column { return 1; } - @Override + @Override @Deprecated public Iterator getColumnIterator() { return new ColumnIterator( column ); } @Override public List getSelectables() { - return Arrays.asList( column ); + return List.of( column ); + } + + @Override + public List getColumns() { + return List.of( column ); } @Override @@ -130,7 +134,11 @@ public class ExportableColumn extends Column { } @Override - public void createForeignKey() throws MappingException { + public void createForeignKey() { + } + + @Override + public void createUniqueKey() { } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/collections/JoinedIterator.java b/hibernate-core/src/main/java/org/hibernate/internal/util/collections/JoinedIterator.java index dc9e6fdabf..bd151d7dd5 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/util/collections/JoinedIterator.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/collections/JoinedIterator.java @@ -30,6 +30,7 @@ public class JoinedIterator implements Iterator { this( wrappedIterators.toArray(new Iterator[0]) ); } + @SafeVarargs public JoinedIterator(Iterator... iteratorsToWrap) { if( iteratorsToWrap == null ) { throw new NullPointerException( "Iterators to join were null" ); diff --git a/hibernate-core/src/main/java/org/hibernate/internal/util/collections/JoinedList.java b/hibernate-core/src/main/java/org/hibernate/internal/util/collections/JoinedList.java new file mode 100644 index 0000000000..389a55d7c1 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/internal/util/collections/JoinedList.java @@ -0,0 +1,51 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * License: GNU Lesser General Public License (LGPL), version 2.1 or later. + * See the lgpl.txt file in the root directory or . + */ +package org.hibernate.internal.util.collections; + +import java.util.AbstractList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +/** + * @author Gavin King + */ +public class JoinedList extends AbstractList { + private final List> lists; + private final int size; + + public JoinedList(List> lists) { + this.lists = lists; + size = lists.stream().map(List::size).reduce(0, Integer::sum); + } + + @SafeVarargs + public JoinedList(List... lists) { + this( Arrays.asList(lists) ); + } + + @Override + public E get(int index) { + for (List list: lists) { + if ( list.size() > index ) { + return list.get(index); + } + index -= list.size(); + } + return null; + } + + @Override + public int size() { + return size; + } + + @Override + public Iterator iterator() { + return lists.stream().flatMap(List::stream).iterator(); + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Collection.java b/hibernate-core/src/main/java/org/hibernate/mapping/Collection.java index ff9557f1b4..5ab0417996 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Collection.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Collection.java @@ -47,7 +47,7 @@ public abstract class Collection implements Fetchable, Value, Filterable { public static final String DEFAULT_KEY_COLUMN_NAME = "id"; private final MetadataBuildingContext buildingContext; - private PersistentClass owner; + private final PersistentClass owner; private KeyValue key; private Value element; @@ -346,14 +346,12 @@ public abstract class Collection implements Fetchable, Value, Filterable { throws MappingException { final boolean[] insertability = value.getColumnInsertability(); final boolean[] updatability = value.getColumnUpdateability(); - final Iterator iterator = value.getColumnIterator(); int i = 0; - while ( iterator.hasNext() ) { - Selectable s = iterator.next(); + for ( Selectable selectable : value.getSelectables() ) { // exclude formulas and columns that are not insertable or updatable // since these values can be repeated (HHH-5393) - if ( !s.isFormula() && ( insertability[i] || updatability[i] ) ) { - Column col = (Column) s; + if ( !selectable.isFormula() && ( insertability[i] || updatability[i] ) ) { + Column col = (Column) selectable; if ( !distinctColumns.add( col.getName() ) ) { throw new MappingException( "Repeated column in mapping for collection: " @@ -387,6 +385,7 @@ public abstract class Collection implements Fetchable, Value, Filterable { } } + @Deprecated public Iterator getColumnIterator() { return Collections.emptyIterator(); } @@ -396,6 +395,11 @@ public abstract class Collection implements Fetchable, Value, Filterable { return Collections.emptyList(); } + @Override + public List getColumns() { + return Collections.emptyList(); + } + public int getColumnSpan() { return 0; } @@ -404,8 +408,7 @@ public abstract class Collection implements Fetchable, Value, Filterable { return getCollectionType(); } - @SuppressWarnings("rawtypes") - public CollectionSemantics getCollectionSemantics() { + public CollectionSemantics getCollectionSemantics() { if ( cachedCollectionSemantics == null ) { cachedCollectionSemantics = resolveCollectionSemantics(); } @@ -475,6 +478,10 @@ public abstract class Collection implements Fetchable, Value, Filterable { public void createForeignKey() { } + @Override + public void createUniqueKey() { + } + public boolean isSimpleValue() { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Component.java b/hibernate-core/src/main/java/org/hibernate/mapping/Component.java index fb536142df..c5e04044f9 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Component.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Component.java @@ -12,6 +12,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.stream.Collectors; import org.hibernate.MappingException; import org.hibernate.boot.model.relational.Database; @@ -41,7 +42,7 @@ import org.hibernate.type.Type; * @author Steve Ebersole */ public class Component extends SimpleValue implements MetaAttributable, SortableValue { - private ArrayList properties = new ArrayList<>(); + private final ArrayList properties = new ArrayList<>(); private int[] originalPropertyOrder = ArrayHelper.EMPTY_INT_ARRAY; private String componentClassName; private boolean embedded; @@ -88,6 +89,10 @@ public class Component extends SimpleValue implements MetaAttributable, Sortable return properties.iterator(); } + public List getProperties() { + return properties; + } + public void addProperty(Property p) { properties.add( p ); } @@ -100,37 +105,35 @@ public class Component extends SimpleValue implements MetaAttributable, Sortable @Override public int getColumnSpan() { int n=0; - Iterator iter = getPropertyIterator(); - while ( iter.hasNext() ) { - Property p = (Property) iter.next(); - n+= p.getColumnSpan(); + for ( Property property : getProperties() ) { + n += property.getColumnSpan(); } return n; } - @Override - @SuppressWarnings("unchecked") + @Override @Deprecated public Iterator getColumnIterator() { + @SuppressWarnings("unchecked") Iterator[] iters = new Iterator[ getPropertySpan() ]; - Iterator iter = getPropertyIterator(); int i = 0; - while ( iter.hasNext() ) { - iters[i++] = iter.next().getColumnIterator(); + for ( Property property : getProperties() ) { + iters[i++] = property.getColumnIterator(); } return new JoinedIterator<>( iters ); } @Override public List getSelectables() { - final List columns = new ArrayList<>(); - final Iterator propertyIterator = getPropertyIterator(); - while ( propertyIterator.hasNext() ) { - final Iterator columnIterator = propertyIterator.next().getColumnIterator(); - while ( columnIterator.hasNext() ) { - columns.add( columnIterator.next() ); - } - } - return columns; + return properties.stream() + .flatMap( p -> p.getSelectables().stream() ) + .collect(Collectors.toList()); + } + + @Override + public List getColumns() { + return properties.stream() + .flatMap( p -> p.getValue().getColumns().stream() ) + .collect(Collectors.toList()); } public boolean isEmbedded() { @@ -141,7 +144,7 @@ public class Component extends SimpleValue implements MetaAttributable, Sortable return componentClassName; } - public Class getComponentClass() throws MappingException { + public Class getComponentClass() throws MappingException { final ClassLoaderService classLoaderService = getMetadata() .getMetadataBuildingOptions() .getServiceRegistry() @@ -256,10 +259,8 @@ public class Component extends SimpleValue implements MetaAttributable, Sortable @Override public boolean[] getColumnInsertability() { boolean[] result = new boolean[ getColumnSpan() ]; - Iterator iter = getPropertyIterator(); int i=0; - while ( iter.hasNext() ) { - Property prop = (Property) iter.next(); + for ( Property prop : getProperties() ) { boolean[] chunk = prop.getValue().getColumnInsertability(); if ( prop.isInsertable() ) { System.arraycopy(chunk, 0, result, i, chunk.length); @@ -284,10 +285,8 @@ public class Component extends SimpleValue implements MetaAttributable, Sortable @Override public boolean[] getColumnUpdateability() { boolean[] result = new boolean[ getColumnSpan() ]; - Iterator iter = getPropertyIterator(); int i=0; - while ( iter.hasNext() ) { - Property prop = (Property) iter.next(); + for ( Property prop : getProperties() ) { boolean[] chunk = prop.getValue().getColumnUpdateability(); if ( prop.isUpdateable() ) { System.arraycopy(chunk, 0, result, i, chunk.length); @@ -334,9 +333,7 @@ public class Component extends SimpleValue implements MetaAttributable, Sortable } public Property getProperty(String propertyName) throws MappingException { - Iterator iter = getPropertyIterator(); - while ( iter.hasNext() ) { - Property prop = (Property) iter.next(); + for ( Property prop : getProperties() ) { if ( prop.getName().equals(propertyName) ) { return prop; } @@ -391,8 +388,8 @@ public class Component extends SimpleValue implements MetaAttributable, Sortable ); } - final Class entityClass = rootClass.getMappedClass(); - final Class attributeDeclarer; // what class is the declarer of the composite pk attributes + final Class entityClass = rootClass.getMappedClass(); + final Class attributeDeclarer; // what class is the declarer of the composite pk attributes CompositeNestedGeneratedValueGenerator.GenerationContextLocator locator; // IMPL NOTE : See the javadoc discussion on CompositeNestedGeneratedValueGenerator wrt the @@ -413,9 +410,7 @@ public class Component extends SimpleValue implements MetaAttributable, Sortable locator = new StandardGenerationContextLocator( rootClass.getEntityName() ); final CompositeNestedGeneratedValueGenerator generator = new CompositeNestedGeneratedValueGenerator( locator ); - Iterator itr = getPropertyIterator(); - while ( itr.hasNext() ) { - final Property property = (Property) itr.next(); + for ( Property property : getProperties() ) { if ( property.getValue().isSimpleValue() ) { final SimpleValue value = (SimpleValue) property.getValue(); @@ -443,13 +438,13 @@ public class Component extends SimpleValue implements MetaAttributable, Sortable return generator; } - private Setter injector(Property property, Class attributeDeclarer) { + private Setter injector(Property property, Class attributeDeclarer) { return property.getPropertyAccessStrategy( attributeDeclarer ) .buildPropertyAccess( attributeDeclarer, property.getName(), true ) .getSetter(); } - private Class resolveComponentClass() { + private Class resolveComponentClass() { try { return getComponentClass(); } @@ -543,9 +538,7 @@ public class Component extends SimpleValue implements MetaAttributable, Sortable final List columns = primaryKey.getColumns(); columns.clear(); for ( int i = 0; i < properties.size(); i++ ) { - final Iterator columnIterator = properties.get( i ).getColumnIterator(); - while ( columnIterator.hasNext() ) { - final Selectable selectable = columnIterator.next(); + for ( Selectable selectable : properties.get(i).getSelectables() ) { if ( selectable instanceof Column ) { columns.add( (Column) selectable ); } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Constraint.java b/hibernate-core/src/main/java/org/hibernate/mapping/Constraint.java index 16c9f01499..e5b374dcf9 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Constraint.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Constraint.java @@ -17,6 +17,7 @@ import java.util.List; import java.util.Locale; import org.hibernate.HibernateException; +import org.hibernate.MappingException; import org.hibernate.boot.model.relational.Exportable; import org.hibernate.boot.model.relational.SqlStringGenerationContext; import org.hibernate.dialect.Dialect; @@ -129,11 +130,13 @@ public abstract class Constraint implements RelationalModel, Exportable, Seriali } } - public void addColumns(Iterator columnIterator) { - while ( columnIterator.hasNext() ) { - Selectable col = (Selectable) columnIterator.next(); - if ( !col.isFormula() ) { - addColumn( (Column) col ); + public void addColumns(Value value) { + for ( Selectable selectable : value.getSelectables() ) { + if ( selectable.isFormula() ) { + throw new MappingException( "constraint involves a formula: " + this.name ); + } + else { + addColumn( (Column) selectable ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Contributable.java b/hibernate-core/src/main/java/org/hibernate/mapping/Contributable.java index cd24be5fa8..48f5ff0ded 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Contributable.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Contributable.java @@ -7,7 +7,9 @@ package org.hibernate.mapping; /** - * Part of the mapping model that is associated with a contributor. ORM, Envers, Search, etc + * Part of the mapping model that is associated with a contributor. + * ORM, Envers, Search, etc + * * @author Steve Ebersole */ public interface Contributable { diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/DenormalizedTable.java b/hibernate-core/src/main/java/org/hibernate/mapping/DenormalizedTable.java index 30b0df48dd..0068916fc6 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/DenormalizedTable.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/DenormalizedTable.java @@ -7,17 +7,18 @@ package org.hibernate.mapping; import java.util.ArrayList; +import java.util.Collection; import java.util.Iterator; import java.util.List; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.relational.Namespace; import org.hibernate.internal.util.collections.JoinedIterator; +import org.hibernate.internal.util.collections.JoinedList; /** * @author Gavin King */ -@SuppressWarnings("unchecked") public class DenormalizedTable extends Table { private final Table includedTable; @@ -59,9 +60,9 @@ public class DenormalizedTable extends Table { @Override public void createForeignKeys() { includedTable.createForeignKeys(); - Iterator iter = includedTable.getForeignKeyIterator(); + Iterator iter = includedTable.getForeignKeyIterator(); while ( iter.hasNext() ) { - ForeignKey fk = (ForeignKey) iter.next(); + ForeignKey fk = iter.next(); createForeignKey( Constraint.generateName( fk.generatedConstraintNamePrefix(), @@ -79,29 +80,27 @@ public class DenormalizedTable extends Table { @Override public Column getColumn(Column column) { Column superColumn = super.getColumn( column ); - if ( superColumn != null ) { - return superColumn; - } - else { - return includedTable.getColumn( column ); - } + return superColumn != null ? superColumn : includedTable.getColumn(column); } public Column getColumn(Identifier name) { Column superColumn = super.getColumn( name ); - if ( superColumn != null ) { - return superColumn; - } - else { - return includedTable.getColumn( name ); - } + return superColumn != null ? superColumn : includedTable.getColumn(name); + } + + @Override @Deprecated + public Iterator getColumnIterator() { + return new JoinedIterator<>( + includedTable.getColumnIterator(), + super.getColumnIterator() + ); } @Override - public Iterator getColumnIterator() { - return new JoinedIterator( - includedTable.getColumnIterator(), - super.getColumnIterator() + public Collection getColumns() { + return new JoinedList<>( + new ArrayList<>( includedTable.getColumns() ), + new ArrayList<>( super.getColumns() ) ); } @@ -116,11 +115,11 @@ public class DenormalizedTable extends Table { } @Override - public Iterator getUniqueKeyIterator() { + public Iterator getUniqueKeyIterator() { if ( !includedTable.isPhysicalTable() ) { - Iterator iter = includedTable.getUniqueKeyIterator(); + Iterator iter = includedTable.getUniqueKeyIterator(); while ( iter.hasNext() ) { - UniqueKey uk = (UniqueKey) iter.next(); + UniqueKey uk = iter.next(); createUniqueKey( uk.getColumns() ); } } @@ -128,18 +127,18 @@ public class DenormalizedTable extends Table { } @Override - public Iterator getIndexIterator() { - List indexes = new ArrayList(); - Iterator iter = includedTable.getIndexIterator(); + public Iterator getIndexIterator() { + List indexes = new ArrayList<>(); + Iterator iter = includedTable.getIndexIterator(); while ( iter.hasNext() ) { - Index parentIndex = (Index) iter.next(); + Index parentIndex = iter.next(); Index index = new Index(); index.setName( getName() + parentIndex.getName() ); index.setTable( this ); index.addColumns( parentIndex.getColumnIterator() ); indexes.add( index ); } - return new JoinedIterator( + return new JoinedIterator<>( indexes.iterator(), super.getIndexIterator() ); diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/DependantBasicValue.java b/hibernate-core/src/main/java/org/hibernate/mapping/DependantBasicValue.java index 2fd35e2a44..f0aa441514 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/DependantBasicValue.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/DependantBasicValue.java @@ -14,8 +14,8 @@ import org.hibernate.boot.spi.MetadataBuildingContext; public class DependantBasicValue extends BasicValue { private final BasicValue referencedValue; - private boolean nullable; - private boolean updateable; + private final boolean nullable; + private final boolean updateable; public DependantBasicValue( MetadataBuildingContext buildingContext, diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/FetchProfile.java b/hibernate-core/src/main/java/org/hibernate/mapping/FetchProfile.java index 8b6db485ad..aecdab6d54 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/FetchProfile.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/FetchProfile.java @@ -20,7 +20,7 @@ import java.util.LinkedHashSet; public class FetchProfile { private final String name; private final MetadataSource source; - private LinkedHashSet fetches = new LinkedHashSet<>(); + private final LinkedHashSet fetches = new LinkedHashSet<>(); /** * Create a fetch profile representation. diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Fetchable.java b/hibernate-core/src/main/java/org/hibernate/mapping/Fetchable.java index b5e076af8a..6552c2a864 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Fetchable.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Fetchable.java @@ -9,6 +9,7 @@ import org.hibernate.FetchMode; /** * Any mapping with an outer-join attribute + * * @author Gavin King */ public interface Fetchable { diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/ForeignKey.java b/hibernate-core/src/main/java/org/hibernate/mapping/ForeignKey.java index 2af48bef49..b55fe223e6 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/ForeignKey.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/ForeignKey.java @@ -25,7 +25,7 @@ public class ForeignKey extends Constraint { private String referencedEntityName; private String keyDefinition; private boolean cascadeDeleteEnabled; - private List referencedColumns = new ArrayList<>(); + private final List referencedColumns = new ArrayList<>(); private boolean creationEnabled = true; public ForeignKey() { @@ -73,10 +73,10 @@ public class ForeignKey extends Constraint { referencedColumnItr = referencedColumns.iterator(); } - Iterator columnItr = getColumnIterator(); + Iterator columnItr = getColumnIterator(); int i = 0; while ( columnItr.hasNext() ) { - columnNames[i] = ( (Column) columnItr.next() ).getQuotedName( dialect ); + columnNames[i] = columnItr.next().getQuotedName( dialect ); referencedColumnNames[i] = referencedColumnItr.next().getQuotedName( dialect ); i++; } @@ -105,9 +105,9 @@ public class ForeignKey extends Constraint { return referencedTable; } - private void appendColumns(StringBuilder buf, Iterator columns) { + private void appendColumns(StringBuilder buf, Iterator columns) { while ( columns.hasNext() ) { - Column column = (Column) columns.next(); + Column column = columns.next(); buf.append( column.getName() ); if ( columns.hasNext() ) { buf.append( "," ); @@ -149,10 +149,10 @@ public class ForeignKey extends Constraint { throw new MappingException( sb.toString() ); } - Iterator fkCols = getColumnIterator(); - Iterator pkCols = referencedTable.getPrimaryKey().getColumnIterator(); + Iterator fkCols = getColumnIterator(); + Iterator pkCols = referencedTable.getPrimaryKey().getColumnIterator(); while ( pkCols.hasNext() ) { - ( (Column) fkCols.next() ).setLength( ( (Column) pkCols.next() ).getLength() ); + fkCols.next().setLength( pkCols.next().getLength() ); } } @@ -207,7 +207,7 @@ public class ForeignKey extends Constraint { /** * Returns the referenced columns if the foreignkey does not refer to the primary key */ - public List getReferencedColumns() { + public List getReferencedColumns() { return referencedColumns; } @@ -218,9 +218,9 @@ public class ForeignKey extends Constraint { return referencedColumns.isEmpty(); } - public void addReferencedColumns(Iterator referencedColumnsIterator) { + public void addReferencedColumns(Iterator referencedColumnsIterator) { while ( referencedColumnsIterator.hasNext() ) { - Selectable col = (Selectable) referencedColumnsIterator.next(); + Selectable col = referencedColumnsIterator.next(); if ( !col.isFormula() ) { addReferencedColumn( (Column) col ); } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/IdentifierCollection.java b/hibernate-core/src/main/java/org/hibernate/mapping/IdentifierCollection.java index 5d9c36d072..9343a95956 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/IdentifierCollection.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/IdentifierCollection.java @@ -55,7 +55,7 @@ public abstract class IdentifierCollection extends Collection { void createPrimaryKey() { if ( !isOneToMany() ) { PrimaryKey pk = new PrimaryKey( getCollectionTable() ); - pk.addColumns( getIdentifier().getColumnIterator() ); + pk.addColumns( getIdentifier() ); getCollectionTable().setPrimaryKey(pk); } // create an index on the key columns?? diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/IndexedCollection.java b/hibernate-core/src/main/java/org/hibernate/mapping/IndexedCollection.java index 7627f0e5b2..4cad3c1dad 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/IndexedCollection.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/IndexedCollection.java @@ -58,23 +58,21 @@ public abstract class IndexedCollection extends Collection { void createPrimaryKey() { if ( !isOneToMany() ) { PrimaryKey pk = new PrimaryKey( getCollectionTable() ); - pk.addColumns( getKey().getColumnIterator() ); + pk.addColumns( getKey() ); // index should be last column listed boolean indexIsPartOfElement = false; - final Iterator iter = getIndex().getColumnIterator(); - while ( iter.hasNext() ) { - final Selectable selectable = iter.next(); + for ( Selectable selectable: getIndex().getSelectables() ) { if ( selectable.isFormula() || !getCollectionTable().containsColumn( (Column) selectable ) ) { indexIsPartOfElement = true; } } if ( indexIsPartOfElement ) { //if it is part of the element, use the element columns in the PK - pk.addColumns( getElement().getColumnIterator() ); + pk.addColumns( getElement() ); } else { - pk.addColumns( getIndex().getColumnIterator() ); + pk.addColumns( getIndex() ); } getCollectionTable().setPrimaryKey(pk); } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Join.java b/hibernate-core/src/main/java/org/hibernate/mapping/Join.java index 1335004719..8cbd04dc90 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Join.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Join.java @@ -9,6 +9,7 @@ package org.hibernate.mapping; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; +import java.util.List; import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle; import org.hibernate.sql.Alias; @@ -52,6 +53,15 @@ public class Join implements AttributeContainer, Serializable { prop.setPersistentClass( getPersistentClass() ); } + public List getDeclaredProperties() { + return declaredProperties; + } + + public List getProperties() { + return properties; + } + + @Deprecated(since = "6.0") public Iterator getDeclaredPropertyIterator() { return declaredProperties.iterator(); } @@ -59,6 +69,8 @@ public class Join implements AttributeContainer, Serializable { public boolean containsProperty(Property prop) { return properties.contains(prop); } + + @Deprecated(since = "6.0") public Iterator getPropertyIterator() { return properties.iterator(); } @@ -95,7 +107,7 @@ public class Join implements AttributeContainer, Serializable { pk.setName( PK_ALIAS.toAliasString( table.getName() ) ); table.setPrimaryKey(pk); - pk.addColumns( getKey().getColumnIterator() ); + pk.addColumns( getKey() ); } public int getPropertySpan() { diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/JoinedSubclass.java b/hibernate-core/src/main/java/org/hibernate/mapping/JoinedSubclass.java index 44c20a3ace..1e81c7ef18 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/JoinedSubclass.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/JoinedSubclass.java @@ -6,6 +6,7 @@ */ package org.hibernate.mapping; import java.util.Iterator; +import java.util.List; import org.hibernate.MappingException; import org.hibernate.boot.spi.MetadataBuildingContext; @@ -52,10 +53,15 @@ public class JoinedSubclass extends Subclass implements TableOwner { } } + @Deprecated public Iterator getReferenceablePropertyIterator() { return getPropertyIterator(); } + public List getReferenceableProperties() { + return getProperties(); + } + public Object accept(PersistentClassVisitor mv) { return mv.accept(this); } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/ManyToOne.java b/hibernate-core/src/main/java/org/hibernate/mapping/ManyToOne.java index 581c3c95ca..d3fbed32ea 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/ManyToOne.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/ManyToOne.java @@ -48,16 +48,21 @@ public class ManyToOne extends ToOne { return resolvedType; } - public void createForeignKey() throws MappingException { + public void createForeignKey() { // Ensure properties are sorted before we create a foreign key sortProperties(); // the case of a foreign key to something other than the pk is handled in createPropertyRefConstraints - if (referencedPropertyName==null && !hasFormula() ) { + if ( referencedPropertyName==null && !hasFormula() ) { createForeignKeyOfEntity( ( (EntityType) getType() ).getAssociatedEntityName() ); } } - + @Override + public void createUniqueKey() { + if ( !hasFormula() ) { + getTable().createUniqueKey( getConstraintColumns() ); + } + } public void createPropertyRefConstraints(Map persistentClasses) { if (referencedPropertyName!=null) { @@ -82,19 +87,12 @@ public class ManyToOne extends ToOne { } // todo : if "none" another option is to create the ForeignKey object still but to set its #disableCreation flag if ( !hasFormula() && !"none".equals( getForeignKeyName() ) ) { - java.util.List refColumns = new ArrayList(); - Iterator iter = property.getColumnIterator(); - while ( iter.hasNext() ) { - Column col = (Column) iter.next(); - refColumns.add( col ); - } - ForeignKey fk = getTable().createForeignKey( getForeignKeyName(), getConstraintColumns(), ( (EntityType) getType() ).getAssociatedEntityName(), - getForeignKeyDefinition(), - refColumns + getForeignKeyDefinition(), + new ArrayList<>( property.getColumns() ) ); fk.setCascadeDeleteEnabled(isCascadeDeleteEnabled() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/OneToMany.java b/hibernate-core/src/main/java/org/hibernate/mapping/OneToMany.java index f76e580fe3..8ae712ad24 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/OneToMany.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/OneToMany.java @@ -33,7 +33,7 @@ public class OneToMany implements Value { public OneToMany(MetadataBuildingContext buildingContext, PersistentClass owner) throws MappingException { this.buildingContext = buildingContext; - this.referencingTable = ( owner == null ) ? null : owner.getTable(); + this.referencingTable = owner == null ? null : owner.getTable(); } public MetadataBuildingContext getBuildingContext() { @@ -74,6 +74,11 @@ public class OneToMany implements Value { // no foreign key element for a one-to-many } + @Override + public void createUniqueKey() { + } + + @Deprecated public Iterator getColumnIterator() { return associatedClass.getKey().getColumnIterator(); } @@ -83,6 +88,11 @@ public class OneToMany implements Value { return associatedClass.getKey().getSelectables(); } + @Override + public List getColumns() { + return associatedClass.getKey().getColumns(); + } + public int getColumnSpan() { return associatedClass.getKey().getColumnSpan(); } @@ -150,8 +160,8 @@ public class OneToMany implements Value { public boolean isSame(OneToMany other) { return Objects.equals( referencingTable, other.referencingTable ) - && Objects.equals( referencedEntityName, other.referencedEntityName ) - && Objects.equals( associatedClass, other.associatedClass ); + && Objects.equals( referencedEntityName, other.referencedEntityName ) + && Objects.equals( associatedClass, other.associatedClass ); } public boolean[] getColumnInsertability() { diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/OneToOne.java b/hibernate-core/src/main/java/org/hibernate/mapping/OneToOne.java index 8c3fb99333..72618f1280 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/OneToOne.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/OneToOne.java @@ -6,14 +6,12 @@ */ package org.hibernate.mapping; -import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Objects; import org.hibernate.MappingException; import org.hibernate.boot.spi.MetadataBuildingContext; -import org.hibernate.boot.spi.MetadataImplementor; import org.hibernate.type.EntityType; import org.hibernate.type.ForeignKeyDirection; import org.hibernate.type.Type; @@ -28,7 +26,7 @@ public class OneToOne extends ToOne { private ForeignKeyDirection foreignKeyType; private KeyValue identifier; private String propertyName; - private String entityName; + private final String entityName; private String mappedByProperty; public OneToOne(MetadataBuildingContext buildingContext, Table table, PersistentClass owner) throws MappingException { @@ -48,13 +46,9 @@ public class OneToOne extends ToOne { public String getEntityName() { return entityName; } - - public void setEntityName(String propertyName) { - this.entityName = entityName==null ? null : entityName.intern(); - } public Type getType() throws MappingException { - if ( getColumnIterator().hasNext() ) { + if ( getColumnSpan()>0 ) { return MappingHelper.specialOneToOne( getReferencedEntityName(), getForeignKeyType(), @@ -95,20 +89,27 @@ public class OneToOne extends ToOne { } @Override - public List getSelectables() { - if ( super.getSelectables().size() > 0 ) { - return super.getSelectables(); + public void createUniqueKey() { + if ( !hasFormula() && getColumnSpan()>0 ) { + getTable().createUniqueKey( getConstraintColumns() ); } - return getConstraintColumns(); } - public List getConstraintColumns() { - ArrayList list = new ArrayList(); - Iterator iter = identifier.getColumnIterator(); - while ( iter.hasNext() ) { - list.add( iter.next() ); + @Override + public List getVirtualSelectables() { + List selectables = super.getVirtualSelectables(); + if ( selectables.isEmpty() ) { + selectables = identifier.getSelectables(); } - return list; + return selectables; + } + + public List getConstraintColumns() { + List columns = super.getColumns(); + if ( columns.isEmpty() ) { + columns = identifier.getColumns(); + } + return columns; } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java b/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java index 9d6816e6b1..da9923701a 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java @@ -12,6 +12,7 @@ import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Set; import java.util.StringTokenizer; @@ -25,6 +26,7 @@ import org.hibernate.engine.spi.Mapping; import org.hibernate.internal.FilterConfiguration; import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.collections.JoinedIterator; +import org.hibernate.internal.util.collections.JoinedList; import org.hibernate.internal.util.collections.SingletonIterator; import org.hibernate.metamodel.RepresentationMode; import org.hibernate.persister.entity.EntityPersister; @@ -58,8 +60,8 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl private String discriminatorValue; private boolean lazy; - private java.util.List properties = new ArrayList<>(); - private java.util.List declaredProperties = new ArrayList<>(); + private final java.util.List properties = new ArrayList<>(); + private final java.util.List declaredProperties = new ArrayList<>(); private final java.util.List subclasses = new ArrayList<>(); private final java.util.List subclassProperties = new ArrayList<>(); private final java.util.List subclassTables = new ArrayList<>(); @@ -68,7 +70,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl private int batchSize = -1; private boolean selectBeforeUpdate; private java.util.Map metaAttributes; - private java.util.List joins = new ArrayList<>(); + private final java.util.List joins = new ArrayList<>(); private final java.util.List subclassJoins = new ArrayList<>(); private final java.util.List filters = new ArrayList<>(); protected final Set synchronizedTables = new HashSet<>(); @@ -89,8 +91,6 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl private boolean customDeleteCallable; private ExecuteUpdateResultCheckStyle deleteCheckStyle; - private java.util.Map tuplizerImpls; - private MappedSuperclass superMappedSuperclass; private Component declaredIdentifierMapper; private OptimisticLockStyle optimisticLockStyle; @@ -218,6 +218,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl * first. */ public Iterator getSubclassIterator() { + @SuppressWarnings("unchecked") Iterator[] iters = new Iterator[subclasses.size() + 1]; Iterator iter = subclasses.iterator(); int i = 0; @@ -317,6 +318,9 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl public abstract boolean isDiscriminatorInsertable(); + public abstract List getPropertyClosure(); + + @Deprecated(since = "6.0") public abstract Iterator getPropertyClosureIterator(); public abstract Iterator
getTableClosureIterator(); @@ -335,17 +339,27 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl subclassTables.add( subclassTable ); } + @Deprecated(since = "6.0") public Iterator getSubclassPropertyClosureIterator() { ArrayList> iters = new ArrayList<>(); iters.add( getPropertyClosureIterator() ); iters.add( subclassProperties.iterator() ); - for ( int i = 0; i < subclassJoins.size(); i++ ) { - Join join = subclassJoins.get( i ); + for (Join join : subclassJoins) { iters.add( join.getPropertyIterator() ); } return new JoinedIterator<>( iters ); } + public List getSubclassPropertyClosure() { + ArrayList> lists = new ArrayList<>(); + lists.add( getPropertyClosure() ); + lists.add( subclassProperties ); + for (Join join : subclassJoins) { + lists.add( join.getProperties() ); + } + return new JoinedList<>( lists ); + } + public Iterator getSubclassJoinClosureIterator() { return new JoinedIterator<>( getJoinClosureIterator(), subclassJoins.iterator() ); } @@ -397,7 +411,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl pk.setName( PK_ALIAS.toAliasString( table.getName() ) ); table.setPrimaryKey( pk ); - pk.addColumns( getKey().getColumnIterator() ); + pk.addColumns( getKey() ); } public abstract String getWhere(); @@ -425,12 +439,29 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl * Includes all properties defined as part of a join. * * @see #getReferencedProperty for a discussion of "referenceable" + * * @return The referenceable property iterator. + * + * @deprecated use {@link #getReferenceableProperties()} */ + @Deprecated(since = "6.0") public Iterator getReferenceablePropertyIterator() { return getPropertyClosureIterator(); } + /** + * Build a list of properties which may be referenced in association mappings. + *

+ * Includes properties defined in superclasses of the mapping inheritance. + * Includes all properties defined as part of a join. + * + * @see #getReferencedProperty for a discussion of "referenceable" + * @return The referenceable property iterator. + */ + public List getReferenceableProperties() { + return getPropertyClosure(); + } + /** * Given a property path, locate the appropriate referenceable property reference. *

@@ -445,7 +476,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl */ public Property getReferencedProperty(String propertyPath) throws MappingException { try { - return getRecursiveProperty( propertyPath, getReferenceablePropertyIterator() ); + return getRecursiveProperty( propertyPath, getReferenceableProperties() ); } catch (MappingException e) { throw new MappingException( @@ -456,7 +487,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl public Property getRecursiveProperty(String propertyPath) throws MappingException { try { - return getRecursiveProperty( propertyPath, getPropertyClosureIterator() ); + return getRecursiveProperty( propertyPath, getPropertyClosure() ); } catch (MappingException e) { throw new MappingException( @@ -465,7 +496,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl } } - private Property getRecursiveProperty(String propertyPath, Iterator iter) throws MappingException { + private Property getRecursiveProperty(String propertyPath, List iter) throws MappingException { Property property = null; StringTokenizer st = new StringTokenizer( propertyPath, ".", false ); try { @@ -482,12 +513,10 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl else if ( identifierProperty == null && getIdentifierMapper() != null ) { // we have an embedded composite identifier try { - identifierProperty = getProperty( element, getIdentifierMapper().getPropertyIterator() ); - if ( identifierProperty != null ) { - // the root of the incoming property path matched one - // of the embedded composite identifier properties - property = identifierProperty; - } + identifierProperty = getProperty( element, getIdentifierMapper().getProperties() ); + // the root of the incoming property path matched one + // of the embedded composite identifier properties + property = identifierProperty; } catch (MappingException ignore) { // ignore it... @@ -511,16 +540,13 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl return property; } - private Property getProperty(String propertyName, Iterator iterator) throws MappingException { - if ( iterator.hasNext() ) { - String root = StringHelper.root( propertyName ); - while ( iterator.hasNext() ) { - Property prop = iterator.next(); - if ( prop.getName().equals( root ) - || (prop instanceof Backref || prop instanceof IndexBackref) - && prop.getName().equals( propertyName ) ) { - return prop; - } + private Property getProperty(String propertyName, List properties) throws MappingException { + String root = StringHelper.root( propertyName ); + for ( Property prop : properties ) { + if ( prop.getName().equals( root ) + || ( prop instanceof Backref || prop instanceof IndexBackref ) + && prop.getName().equals( propertyName ) ) { + return prop; } } throw new MappingException( "property [" + propertyName + "] not found on entity [" + getEntityName() + "]" ); @@ -533,12 +559,12 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl return identifierProperty; } else { - Iterator iter = getPropertyClosureIterator(); + List closure = getPropertyClosure(); Component identifierMapper = getIdentifierMapper(); if ( identifierMapper != null ) { - iter = new JoinedIterator<>( identifierMapper.getPropertyIterator(), iter ); + closure = new JoinedList<>( identifierMapper.getProperties(), closure ); } - return getProperty( propertyName, iter ); + return getProperty( propertyName, closure ); } } @@ -549,12 +575,12 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl return identifierProperty; } else { - Iterator iter = getSubclassPropertyClosureIterator(); + List closure = getSubclassPropertyClosure(); Component identifierMapper = getIdentifierMapper(); if ( identifierMapper != null ) { - iter = new JoinedIterator<>( identifierMapper.getPropertyIterator(), iter ); + closure = new JoinedList<>( identifierMapper.getProperties(), closure ); } - return getProperty( propertyName, iter ); + return getProperty( propertyName, closure ); } } @@ -606,21 +632,9 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl * @return {@code true} if a property with that name exists; {@code false} if not */ public boolean isPropertyDefinedInHierarchy(String name) { - if ( hasProperty( name ) ) { - return true; - } - - if ( getSuperMappedSuperclass() != null - && getSuperMappedSuperclass().isPropertyDefinedInHierarchy( name ) ) { - return true; - } - - if ( getSuperclass() != null - && getSuperclass().isPropertyDefinedInHierarchy( name ) ) { - return true; - } - - return false; + return hasProperty( name ) + || getSuperMappedSuperclass() != null && getSuperMappedSuperclass().isPropertyDefinedInHierarchy( name ) + ||getSuperclass() != null && getSuperclass().isPropertyDefinedInHierarchy(name); } /** @@ -648,9 +662,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl } public void validate(Mapping mapping) throws MappingException { - Iterator iter = getPropertyIterator(); - while ( iter.hasNext() ) { - Property prop = iter.next(); + for ( Property prop : getProperties() ) { if ( !prop.isValid( mapping ) ) { throw new MappingException( "property mapping has wrong number of columns: " + @@ -666,9 +678,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl private void checkPropertyDuplication() throws MappingException { HashSet names = new HashSet<>(); - Iterator iter = getPropertyIterator(); - while ( iter.hasNext() ) { - Property prop = iter.next(); + for ( Property prop : getProperties() ) { if ( !names.add( prop.getName() ) ) { throw new MappingException( "Duplicate property mapping of " + prop.getName() + " found in " + getEntityName() ); } @@ -756,24 +766,46 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl public Iterator getPropertyIterator() { ArrayList> iterators = new ArrayList<>(); iterators.add( properties.iterator() ); - for ( int i = 0; i < joins.size(); i++ ) { - Join join = joins.get( i ); + for (Join join : joins) { iterators.add( join.getPropertyIterator() ); } return new JoinedIterator<>( iterators ); } + public List getProperties() { + ArrayList> list = new ArrayList<>(); + list.add( properties ); + for (Join join : joins) { + list.add( join.getProperties() ); + } + return new JoinedList<>( list ); + } + /** * Build an iterator over the properties defined on this class which * are not defined as part of a join. As with {@link #getPropertyIterator}, * the returned iterator only accounts for non-identifier properties. * * @return An iterator over the non-joined "normal" properties. + * + * @deprecated use {@link #getUnjoinedProperties()} */ + @Deprecated(since = "6.0") public Iterator getUnjoinedPropertyIterator() { return properties.iterator(); } + /** + * Get a list of the properties defined on this class which + * are not defined as part of a join. As with {@link #getProperties}, + * the returned iterator only accounts for non-identifier properties. + * + * @return An iterator over the non-joined "normal" properties. + */ + public List getUnjoinedProperties() { + return properties; + } + public void setCustomSqlInsert(CustomSql customSql) { if ( customSql != null ) { setCustomSQLInsert( @@ -908,10 +940,12 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl this.isAbstract = isAbstract; } - protected void checkColumnDuplication(Set distinctColumns, Iterator columns) + protected void checkColumnDuplication(Set distinctColumns, Value value) throws MappingException { - while ( columns.hasNext() ) { - Selectable columnOrFormula = columns.next(); + if (value == null) { + return; + } + for ( Selectable columnOrFormula : value.getSelectables() ) { if ( !columnOrFormula.isFormula() ) { Column col = (Column) columnOrFormula; if ( !distinctColumns.add( col.getName() ) ) { @@ -927,26 +961,30 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl } } - protected void checkPropertyColumnDuplication(Set distinctColumns, Iterator properties) + protected void checkPropertyColumnDuplication(Set distinctColumns, List properties) throws MappingException { - while ( properties.hasNext() ) { - Property prop = (Property) properties.next(); + for (Property prop : properties) { if ( prop.getValue() instanceof Component ) { //TODO: remove use of instanceof! Component component = (Component) prop.getValue(); - checkPropertyColumnDuplication( distinctColumns, component.getPropertyIterator() ); + checkPropertyColumnDuplication( distinctColumns, component.getProperties() ); } else { if ( prop.isUpdateable() || prop.isInsertable() ) { - checkColumnDuplication( distinctColumns, prop.getColumnIterator() ); + checkColumnDuplication( distinctColumns, prop.getValue() ); } } } } + @Deprecated(since = "6.0") protected Iterator getNonDuplicatedPropertyIterator() { return getUnjoinedPropertyIterator(); } + protected List getNonDuplicatedProperties() { + return getUnjoinedProperties(); + } + protected Iterator getDiscriminatorColumnIterator() { return Collections.emptyIterator(); } @@ -956,16 +994,16 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl if ( getIdentifierMapper() == null ) { //an identifier mapper => getKey will be included in the getNonDuplicatedPropertyIterator() //and checked later, so it needs to be excluded - checkColumnDuplication( cols, getKey().getColumnIterator() ); + checkColumnDuplication( cols, getKey() ); } - checkColumnDuplication( cols, getDiscriminatorColumnIterator() ); - checkPropertyColumnDuplication( cols, getNonDuplicatedPropertyIterator() ); + checkColumnDuplication( cols, getDiscriminator() ); + checkPropertyColumnDuplication( cols, getNonDuplicatedProperties() ); Iterator iter = getJoinIterator(); while ( iter.hasNext() ) { cols.clear(); Join join = iter.next(); - checkColumnDuplication( cols, join.getKey().getColumnIterator() ); - checkPropertyColumnDuplication( cols, join.getPropertyIterator() ); + checkColumnDuplication( cols, join.getKey() ); + checkPropertyColumnDuplication( cols, join.getProperties() ); } } @@ -1029,17 +1067,11 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl } public String getTuplizerImplClassName(RepresentationMode mode) { - if ( tuplizerImpls == null ) { - return null; - } - return (String) tuplizerImpls.get( mode ); + return null; } public java.util.Map getTuplizerMap() { - if ( tuplizerImpls == null ) { - return null; - } - return Collections.unmodifiableMap( tuplizerImpls ); + return null; } private Boolean hasNaturalId; diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Property.java b/hibernate-core/src/main/java/org/hibernate/mapping/Property.java index c63bb7b26e..380a053e84 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Property.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Property.java @@ -77,10 +77,30 @@ public class Property implements Serializable, MetaAttributable { public int getColumnSpan() { return value.getColumnSpan(); } - + + /** + * @deprecated moving away from the use of {@link Iterator} as a return type + */ + @Deprecated(since = "6.0") public Iterator getColumnIterator() { return value.getColumnIterator(); } + + /** + * Delegates to {@link Value#getSelectables()}. + */ + public java.util.List getSelectables() { + return value.getSelectables(); + } + + /** + * Delegates to {@link Value#getColumns()}. + * + * @throws org.hibernate.AssertionFailure if the mapping involves formulas + */ + public java.util.List getColumns() { + return value.getColumns(); + } public String getName() { return name; @@ -104,9 +124,7 @@ public class Property implements Serializable, MetaAttributable { public void resetOptional(boolean optional) { setOptional(optional); - Iterator columnIterator = getValue().getColumnIterator(); - while ( columnIterator.hasNext() ) { - Selectable column = columnIterator.next(); + for ( Selectable column: getValue().getSelectables() ) { if (column instanceof Column) { ( (Column) column ).setNullable(optional); } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java b/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java index eeff6dda6f..f69f2c4f7d 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java @@ -8,6 +8,7 @@ package org.hibernate.mapping; import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Set; import org.hibernate.MappingException; @@ -125,11 +126,16 @@ public class RootClass extends PersistentClass implements TableOwner { return this; } - @Override + @Override @Deprecated public Iterator getPropertyClosureIterator() { return getPropertyIterator(); } + @Override + public List getPropertyClosure() { + return getProperties(); + } + @Override public Iterator

getTableClosureIterator() { return new SingletonIterator<>( getTable() ); diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Set.java b/hibernate-core/src/main/java/org/hibernate/mapping/Set.java index bf12ef7ba6..6219cab641 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Set.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Set.java @@ -6,7 +6,6 @@ */ package org.hibernate.mapping; -import java.util.Iterator; import java.util.function.Supplier; import org.hibernate.MappingException; @@ -71,10 +70,8 @@ public class Set extends Collection { void createPrimaryKey() { if ( !isOneToMany() ) { PrimaryKey pk = new PrimaryKey( getCollectionTable() ); - pk.addColumns( getKey().getColumnIterator() ); - Iterator iter = getElement().getColumnIterator(); - while ( iter.hasNext() ) { - Object selectable = iter.next(); + pk.addColumns( getKey() ); + for ( Selectable selectable : getElement().getSelectables() ) { if ( selectable instanceof Column ) { Column col = (Column) selectable; if ( !col.isNullable() ) { @@ -85,18 +82,18 @@ public class Set extends Collection { } } } - if ( pk.getColumnSpan() == getKey().getColumnSpan() ) { + if ( pk.getColumnSpan() != getKey().getColumnSpan() ) { + getCollectionTable().setPrimaryKey( pk ); + } +// else { //for backward compatibility, allow a set with no not-null //element columns, using all columns in the row locator SQL //TODO: create an implicit not null constraint on all cols? - } - else { - getCollectionTable().setPrimaryKey( pk ); - } +// } } - else { +// else { //create an index on the key columns?? - } +// } } public Object accept(ValueVisitor visitor) { diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/SimpleValue.java b/hibernate-core/src/main/java/org/hibernate/mapping/SimpleValue.java index 62c5b702f3..5d6d732072 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/SimpleValue.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/SimpleValue.java @@ -17,6 +17,7 @@ import java.util.Map; import java.util.Objects; import java.util.Properties; +import org.hibernate.AssertionFailure; import org.hibernate.FetchMode; import org.hibernate.MappingException; import org.hibernate.TimeZoneStorageStrategy; @@ -70,7 +71,7 @@ public abstract class SimpleValue implements KeyValue { public static final String DEFAULT_ID_GEN_STRATEGY = "assigned"; - private MetadataBuildingContext buildingContext; + private final MetadataBuildingContext buildingContext; private final MetadataImplementor metadata; private final List columns = new ArrayList<>(); @@ -187,10 +188,8 @@ public abstract class SimpleValue implements KeyValue { @Override public boolean hasFormula() { - Iterator iter = getColumnIterator(); - while ( iter.hasNext() ) { - Object o = iter.next(); - if (o instanceof Formula) { + for ( Selectable selectable : getSelectables() ) { + if ( selectable instanceof Formula ) { return true; } } @@ -206,7 +205,7 @@ public abstract class SimpleValue implements KeyValue { return columns.get( position ); } - @Override + @Override @Deprecated public Iterator getColumnIterator() { return columns.iterator(); } @@ -216,8 +215,15 @@ public abstract class SimpleValue implements KeyValue { return columns; } - public List getConstraintColumns() { - return columns; + @Override + public List getColumns() { + if ( hasFormula() ) { + // in principle this method should never get called + // if we have formulas in the mapping + throw new AssertionFailure("value involves formulas"); + } + //noinspection unchecked, rawtypes + return (List) columns; } public Iterator getConstraintColumnIterator() { @@ -236,7 +242,7 @@ public abstract class SimpleValue implements KeyValue { .getServiceRegistry() .getService( ClassLoaderService.class ); try { - final Class converterClass = cls.classForName( converterClassName ); + final Class> converterClass = cls.classForName( converterClassName ); this.attributeConverterDescriptor = new ClassBasedConverterDescriptor( converterClass, false, @@ -285,12 +291,20 @@ public abstract class SimpleValue implements KeyValue { @Override public void createForeignKeyOfEntity(String entityName) { - if ( !hasFormula() && !"none".equals(getForeignKeyName())) { - ForeignKey fk = table.createForeignKey( getForeignKeyName(), getConstraintColumns(), entityName, getForeignKeyDefinition() ); - fk.setCascadeDeleteEnabled(cascadeDeleteEnabled); + if ( !hasFormula() && !"none".equals( getForeignKeyName() ) ) { + table.createForeignKey( getForeignKeyName(), getConstraintColumns(), entityName, getForeignKeyDefinition() ) + .setCascadeDeleteEnabled(cascadeDeleteEnabled); } } + @Override + public void createUniqueKey() { + if ( hasFormula() ) { + throw new MappingException( "unique key constraint involves formulas" ); + } + getTable().createUniqueKey( getConstraintColumns() ); + } + private IdentifierGeneratorCreator customIdGeneratorCreator; private IdentifierGenerator identifierGenerator; @@ -395,7 +409,7 @@ public abstract class SimpleValue implements KeyValue { params.setProperty( PersistentIdentifierGenerator.TABLE, tableName ); //pass the column name (a generated id almost always has a single column) - final String columnName = ( (Column) getColumnIterator().next() ).getQuotedName( dialect ); + final String columnName = ( (Column) getSelectables().get(0) ).getQuotedName( dialect ); params.setProperty( PersistentIdentifierGenerator.PK, columnName ); //pass the entity-name, if not a collection-id @@ -485,7 +499,9 @@ public abstract class SimpleValue implements KeyValue { } public boolean isIdentityColumn(IdentifierGeneratorFactory identifierGeneratorFactory, Dialect dialect) { - return IdentityGenerator.class.isAssignableFrom(identifierGeneratorFactory.getIdentifierGeneratorClass( identifierGeneratorStrategy )); + return IdentityGenerator.class.isAssignableFrom( + identifierGeneratorFactory.getIdentifierGeneratorClass( identifierGeneratorStrategy ) + ); } public Properties getIdentifierGeneratorProperties() { @@ -553,9 +569,7 @@ public abstract class SimpleValue implements KeyValue { } public boolean isNullable() { - Iterator itr = getColumnIterator(); - while ( itr.hasNext() ) { - final Object selectable = itr.next(); + for (Selectable selectable : getSelectables()) { if ( selectable instanceof Formula ) { // if there are *any* formulas, then the Value overall is // considered nullable @@ -698,7 +712,6 @@ public abstract class SimpleValue implements KeyValue { * * @todo : see if we already have previously built a custom on-the-fly BasicType for this AttributeConverter; see note below about caching */ - @SuppressWarnings("unchecked") private Type buildAttributeConverterTypeAdapter() { // todo : validate the number of columns present here? @@ -721,7 +734,6 @@ public abstract class SimpleValue implements KeyValue { final BasicJavaType domainJtd = (BasicJavaType) jpaAttributeConverter.getDomainJavaType(); - // build the SqlTypeDescriptor adapter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Going back to the illustration, this should be a SqlTypeDescriptor that handles the Integer <-> String // conversions. This is the more complicated piece. First we need to determine the JDBC type code @@ -846,7 +858,7 @@ public abstract class SimpleValue implements KeyValue { @Override public String toString() { - return getClass().getName() + '(' + columns.toString() + ')'; + return getClass().getName() + '(' + columns + ')'; } public Object accept(ValueVisitor visitor) { @@ -937,7 +949,7 @@ public abstract class SimpleValue implements KeyValue { table.getCatalog(), table.getSchema(), table.getName(), - Boolean.valueOf( typeParameters.getProperty( DynamicParameterizedType.IS_PRIMARY_KEY ) ), + Boolean.parseBoolean( typeParameters.getProperty( DynamicParameterizedType.IS_PRIMARY_KEY ) ), columnNames, columnLengths ) @@ -990,7 +1002,7 @@ public abstract class SimpleValue implements KeyValue { private static final class ParameterTypeImpl implements DynamicParameterizedType.ParameterType { - private final Class returnedClass; + private final Class returnedClass; private final Annotation[] annotationsMethod; private final String catalog; private final String schema; @@ -1000,7 +1012,7 @@ public abstract class SimpleValue implements KeyValue { private final Long[] columnLengths; private ParameterTypeImpl( - Class returnedClass, + Class returnedClass, Annotation[] annotationsMethod, String catalog, String schema, @@ -1019,7 +1031,7 @@ public abstract class SimpleValue implements KeyValue { } @Override - public Class getReturnedClass() { + public Class getReturnedClass() { return returnedClass; } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/SingleTableSubclass.java b/hibernate-core/src/main/java/org/hibernate/mapping/SingleTableSubclass.java index e035071ece..c487727686 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/SingleTableSubclass.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/SingleTableSubclass.java @@ -7,11 +7,13 @@ package org.hibernate.mapping; import java.util.Iterator; +import java.util.List; import org.hibernate.MappingException; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.engine.spi.Mapping; import org.hibernate.internal.util.collections.JoinedIterator; +import org.hibernate.internal.util.collections.JoinedList; /** * @author Gavin King @@ -22,7 +24,7 @@ public class SingleTableSubclass extends Subclass { super( superclass, metadataBuildingContext ); } - @SuppressWarnings("unchecked") + @Deprecated protected Iterator getNonDuplicatedPropertyIterator() { return new JoinedIterator<>( getSuperclass().getUnjoinedPropertyIterator(), @@ -30,13 +32,14 @@ public class SingleTableSubclass extends Subclass { ); } + protected List getNonDuplicatedProperties() { + return new JoinedList<>( getSuperclass().getUnjoinedProperties(), getUnjoinedProperties() ); + } + protected Iterator getDiscriminatorColumnIterator() { - if ( isDiscriminatorInsertable() && !getDiscriminator().hasFormula() ) { - return getDiscriminator().getColumnIterator(); - } - else { - return super.getDiscriminatorColumnIterator(); - } + return isDiscriminatorInsertable() && !getDiscriminator().hasFormula() + ? getDiscriminator().getColumnIterator() + : super.getDiscriminatorColumnIterator(); } public Object accept(PersistentClassVisitor mv) { diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/SortableValue.java b/hibernate-core/src/main/java/org/hibernate/mapping/SortableValue.java index efe178b04e..95511db02c 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/SortableValue.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/SortableValue.java @@ -6,9 +6,6 @@ */ package org.hibernate.mapping; -/** - * - */ public interface SortableValue { boolean isSorted(); diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java b/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java index 9b526c1e54..d8fa32a30b 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java @@ -5,10 +5,12 @@ * See the lgpl.txt file in the root directory or . */ package org.hibernate.mapping; + import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; +import java.util.List; import java.util.Map; import org.hibernate.AssertionFailure; @@ -16,6 +18,7 @@ import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.engine.OptimisticLockStyle; import org.hibernate.internal.FilterConfiguration; import org.hibernate.internal.util.collections.JoinedIterator; +import org.hibernate.internal.util.collections.JoinedList; import org.hibernate.internal.util.collections.SingletonIterator; import org.hibernate.metamodel.RepresentationMode; import org.hibernate.persister.entity.EntityPersister; @@ -102,12 +105,19 @@ public class Subclass extends PersistentClass { getSuperclass().addSubclassJoin(j); } + @Override + public List getPropertyClosure() { + return new JoinedList<>( getSuperclass().getPropertyClosure(), getProperties() ); + } + + @Deprecated public Iterator getPropertyClosureIterator() { return new JoinedIterator<>( getSuperclass().getPropertyClosureIterator(), getPropertyIterator() ); } + public Iterator
getTableClosureIterator() { return new JoinedIterator<>( getSuperclass().getTableClosureIterator(), @@ -149,12 +159,9 @@ public class Subclass extends PersistentClass { return getSuperclass().hasEmbeddedIdentifier(); } public Class getEntityPersisterClass() { - if (classPersisterClass==null) { - return getSuperclass().getEntityPersisterClass(); - } - else { - return classPersisterClass; - } + return classPersisterClass == null + ? getSuperclass().getEntityPersisterClass() + : classPersisterClass; } public Table getRootTable() { diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Table.java b/hibernate-core/src/main/java/org/hibernate/mapping/Table.java index 81d1b993f0..0411f08347 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Table.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Table.java @@ -9,6 +9,7 @@ package org.hibernate.mapping; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; @@ -38,7 +39,6 @@ import org.jboss.logging.Logger; * * @author Gavin King */ -@SuppressWarnings("deprecation") public class Table implements RelationalModel, Serializable, ContributableDatabaseObject { private static final Logger log = Logger.getLogger( Table.class ); private static final Column[] EMPTY_COLUMN_ARRAY = new Column[0]; @@ -52,14 +52,14 @@ public class Table implements RelationalModel, Serializable, ContributableDataba /** * contains all columns, including the primary key */ - private Map columns = new LinkedHashMap<>(); + private final Map columns = new LinkedHashMap<>(); private KeyValue idValue; private PrimaryKey primaryKey; - private Map foreignKeys = new LinkedHashMap<>(); - private Map indexes = new LinkedHashMap<>(); - private Map uniqueKeys = new LinkedHashMap<>(); + private final Map foreignKeys = new LinkedHashMap<>(); + private final Map indexes = new LinkedHashMap<>(); + private final Map uniqueKeys = new LinkedHashMap<>(); private int uniqueInteger; - private List checkConstraints = new ArrayList<>(); + private final List checkConstraints = new ArrayList<>(); private String rowId; private String subselect; private boolean isAbstract; @@ -229,7 +229,7 @@ public class Table implements RelationalModel, Serializable, ContributableDataba return null; } - Column myColumn = (Column) columns.get( column.getCanonicalName() ); + Column myColumn = columns.get( column.getCanonicalName() ); return column.equals( myColumn ) ? myColumn : @@ -241,7 +241,7 @@ public class Table implements RelationalModel, Serializable, ContributableDataba return null; } - return (Column) columns.get( name.getCanonicalName() ); + return columns.get( name.getCanonicalName() ); } public Column getColumn(int n) { @@ -249,7 +249,7 @@ public class Table implements RelationalModel, Serializable, ContributableDataba for ( int i = 0; i < n - 1; i++ ) { iter.next(); } - return (Column) iter.next(); + return iter.next(); } public void addColumn(Column column) { @@ -285,6 +285,10 @@ public class Table implements RelationalModel, Serializable, ContributableDataba return columns.values().iterator(); } + public Collection getColumns() { + return columns.values(); + } + public Iterator getIndexIterator() { return indexes.values().iterator(); } @@ -425,7 +429,7 @@ public class Table implements RelationalModel, Serializable, ContributableDataba List results = new ArrayList<>(); while ( iter.hasNext() ) { - final Column column = (Column) iter.next(); + final Column column = iter.next(); final ColumnInformation columnInfo = tableInfo.getColumn( Identifier.toIdentifier( column.getName(), column.isQuoted() ) ); if ( columnInfo == null ) { @@ -651,7 +655,9 @@ public class Table implements RelationalModel, Serializable, ContributableDataba public UniqueKey createUniqueKey(List keyColumns) { String keyName = Constraint.generateName( "UK_", this, keyColumns ); UniqueKey uk = getOrCreateUniqueKey( keyName ); - uk.addColumns( keyColumns.iterator() ); + for (Column keyColumn : keyColumns) { + uk.addColumn( keyColumn ); + } return uk; } @@ -691,8 +697,10 @@ public class Table implements RelationalModel, Serializable, ContributableDataba fk = new ForeignKey(); fk.setTable( this ); fk.setReferencedEntityName( referencedEntityName ); - fk.setKeyDefinition(keyDefinition); - fk.addColumns( keyColumns.iterator() ); + fk.setKeyDefinition( keyDefinition ); + for (Column keyColumn : keyColumns) { + fk.addColumn( keyColumn ); + } if ( referencedColumns != null ) { fk.addReferencedColumns( referencedColumns.iterator() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/ToOne.java b/hibernate-core/src/main/java/org/hibernate/mapping/ToOne.java index 21e50c21c3..17def9aa81 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/ToOne.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/ToOne.java @@ -12,8 +12,6 @@ import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.engine.spi.Mapping; import org.hibernate.internal.util.ReflectHelper; -import org.hibernate.type.ComponentType; -import org.hibernate.type.Type; import java.util.Objects; @@ -44,9 +42,6 @@ public abstract class ToOne extends SimpleValue implements Fetchable, SortableVa this.fetchMode=fetchMode; } - public abstract void createForeignKey() throws MappingException; - public abstract Type getType() throws MappingException; - public String getReferencedPropertyName() { return referencedPropertyName; } @@ -98,8 +93,8 @@ public abstract class ToOne extends SimpleValue implements Fetchable, SortableVa public boolean isSame(ToOne other) { return super.isSame( other ) - && Objects.equals( referencedPropertyName, other.referencedPropertyName ) - && Objects.equals( referencedEntityName, other.referencedEntityName ); + && Objects.equals( referencedPropertyName, other.referencedPropertyName ) + && Objects.equals( referencedEntityName, other.referencedEntityName ); } public boolean isValid(Mapping mapping) throws MappingException { diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/UnionSubclass.java b/hibernate-core/src/main/java/org/hibernate/mapping/UnionSubclass.java index 2963d7a3c5..fbe44ce8db 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/UnionSubclass.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/UnionSubclass.java @@ -6,6 +6,7 @@ */ package org.hibernate.mapping; import java.util.Iterator; +import java.util.List; import org.hibernate.MappingException; import org.hibernate.boot.spi.MetadataBuildingContext; @@ -35,11 +36,17 @@ public class UnionSubclass extends Subclass implements TableOwner { public java.util.Set getSynchronizedTables() { return synchronizedTables; } - + + @Deprecated protected Iterator getNonDuplicatedPropertyIterator() { return getPropertyClosureIterator(); } + @Override + protected List getNonDuplicatedProperties() { + return getPropertyClosure(); + } + public void validate(Mapping mapping) throws MappingException { super.validate(mapping); if ( key!=null && !key.isValid(mapping) ) { diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Value.java b/hibernate-core/src/main/java/org/hibernate/mapping/Value.java index 5318c797c2..310a6d333d 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Value.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Value.java @@ -17,8 +17,8 @@ import org.hibernate.service.ServiceRegistry; import org.hibernate.type.Type; /** - * A value is anything that is persisted by value, instead of - * by reference. It is essentially a Hibernate Type, together + * A value is anything that is persisted by value, instead of by + * reference. It is essentially a Hibernate {@link Type}, together * with zero or more columns. Values are wrapped by things with * higher level semantics, for example properties, collections, * classes. @@ -26,20 +26,71 @@ import org.hibernate.type.Type; * @author Gavin King */ public interface Value extends Serializable { + + /** + * The number of columns and formulas in the mapping. + */ int getColumnSpan(); + + /** + * @deprecated moving away from the use of {@link Iterator} as a return type + */ + @Deprecated(since = "6.0") Iterator getColumnIterator(); + + /** + * The mapping to columns and formulas. + */ List getSelectables(); + + /** + * If the mapping involves only columns, return them. + * + * @throws org.hibernate.AssertionFailure if the mapping involves formulas + */ + List getColumns(); + + /** + * Same as {@link #getSelectables()} except it returns the PK for the + * non-owning side of a one-to-one association. + */ + default List getVirtualSelectables() { + return getSelectables(); + } + + /** + * Same as {@link #getColumns()} except it returns the PK for the + * non-owning side of a one-to-one association. + * + * @throws org.hibernate.AssertionFailure if the mapping involves formulas + */ + default List getConstraintColumns() { + return getColumns(); + } + Type getType() throws MappingException; + FetchMode getFetchMode(); + Table getTable(); + boolean hasFormula(); + boolean isAlternateUniqueKey(); + boolean isNullable(); - void createForeignKey() throws MappingException; + + void createForeignKey(); + void createUniqueKey(); + boolean isSimpleValue(); + boolean isValid(Mapping mapping) throws MappingException; + void setTypeUsingReflection(String className, String propertyName) throws MappingException; + Object accept(ValueVisitor visitor); + boolean isSame(Value other); boolean[] getColumnInsertability(); diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/internal/AbstractEmbeddableRepresentationStrategy.java b/hibernate-core/src/main/java/org/hibernate/metamodel/internal/AbstractEmbeddableRepresentationStrategy.java index 92dddeceb4..66970b9f14 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/internal/AbstractEmbeddableRepresentationStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/internal/AbstractEmbeddableRepresentationStrategy.java @@ -6,7 +6,6 @@ */ package org.hibernate.metamodel.internal; -import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -40,14 +39,12 @@ public abstract class AbstractEmbeddableRepresentationStrategy implements Embedd this.attributeNameToPositionMap = new ConcurrentHashMap<>( propertySpan ); boolean foundCustomAccessor = false; - Iterator itr = bootDescriptor.getPropertyIterator(); int i = 0; - while ( itr.hasNext() ) { - final Property prop = ( Property ) itr.next(); - propertyAccesses[i] = buildPropertyAccess( prop ); - attributeNameToPositionMap.put( prop.getName(), i ); + for ( Property property : bootDescriptor.getProperties() ) { + propertyAccesses[i] = buildPropertyAccess( property ); + attributeNameToPositionMap.put( property.getName(), i ); - if ( !prop.isBasicPropertyAccessor() ) { + if ( !property.isBasicPropertyAccessor() ) { foundCustomAccessor = true; } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/internal/AttributeFactory.java b/hibernate-core/src/main/java/org/hibernate/metamodel/internal/AttributeFactory.java index 0e07191a35..3158521cb5 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/internal/AttributeFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/internal/AttributeFactory.java @@ -251,7 +251,8 @@ public class AttributeFactory { else { // we should have a non-dynamic embeddable assert component.getComponentClassName() != null; - final Class embeddableClass = component.getComponentClass(); + @SuppressWarnings("unchecked") + final Class embeddableClass = (Class) component.getComponentClass(); final EmbeddableDomainType cached = context.locateEmbeddable( embeddableClass, component ); if ( cached != null ) { @@ -274,9 +275,7 @@ public class AttributeFactory { } final EmbeddableTypeImpl.InFlightAccess inFlightAccess = embeddableType.getInFlightAccess(); - final Iterator subProperties = component.getPropertyIterator(); - while ( subProperties.hasNext() ) { - final Property property = subProperties.next(); + for ( Property property : component.getProperties() ) { final PersistentAttribute attribute = buildAttribute( embeddableType, property, context ); if ( attribute != null ) { inFlightAccess.addAttribute( attribute ); diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/internal/EntityRepresentationStrategyPojoStandard.java b/hibernate-core/src/main/java/org/hibernate/metamodel/internal/EntityRepresentationStrategyPojoStandard.java index 1e9314acf8..34d4444360 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/internal/EntityRepresentationStrategyPojoStandard.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/internal/EntityRepresentationStrategyPojoStandard.java @@ -113,7 +113,8 @@ public class EntityRepresentationStrategyPojoStandard implements EntityRepresent if ( bootDescriptor.getIdentifierMapper() != null ) { mapsIdRepresentationStrategy = new EmbeddableRepresentationStrategyPojo( bootDescriptor.getIdentifierMapper(), - () -> ( ( CompositeTypeImplementor) bootDescriptor.getIdentifierMapper().getType() ).getMappingModelPart().getEmbeddableTypeDescriptor(), + () -> ( ( CompositeTypeImplementor) bootDescriptor.getIdentifierMapper().getType() ) + .getMappingModelPart().getEmbeddableTypeDescriptor(), // we currently do not support custom instantiators for identifiers null, creationContext @@ -122,7 +123,8 @@ public class EntityRepresentationStrategyPojoStandard implements EntityRepresent else if ( bootDescriptorIdentifier != null ) { mapsIdRepresentationStrategy = new EmbeddableRepresentationStrategyPojo( (Component) bootDescriptorIdentifier, - () -> ( ( CompositeTypeImplementor) bootDescriptor.getIdentifierMapper().getType() ).getMappingModelPart().getEmbeddableTypeDescriptor(), + () -> ( ( CompositeTypeImplementor) bootDescriptor.getIdentifierMapper().getType() ) + .getMappingModelPart().getEmbeddableTypeDescriptor(), // we currently do not support custom instantiators for identifiers null, creationContext @@ -223,14 +225,11 @@ public class EntityRepresentationStrategyPojoStandard implements EntityRepresent proxyInterfaces.add( HibernateProxy.class ); - Iterator properties = bootDescriptor.getPropertyIterator(); Class clazz = bootDescriptor.getMappedClass(); final Method idGetterMethod; final Method idSetterMethod; - try { - while ( properties.hasNext() ) { - Property property = (Property) properties.next(); + for ( Property property : bootDescriptor.getProperties() ) { ProxyFactoryHelper.validateGetterSetterMethodProxyability( "Getter", property.getGetter( clazz ).getMethod() diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/internal/MetadataContext.java b/hibernate-core/src/main/java/org/hibernate/metamodel/internal/MetadataContext.java index 1f3b1fd9f4..17fa5e2966 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/internal/MetadataContext.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/internal/MetadataContext.java @@ -256,7 +256,8 @@ public class MetadataContext { LOG.trace( "Wrapping up metadata context..." ); } - boolean staticMetamodelScanEnabled = this.jpaStaticMetaModelPopulationSetting != JpaStaticMetaModelPopulationSetting.DISABLED; + boolean staticMetamodelScanEnabled = + this.jpaStaticMetaModelPopulationSetting != JpaStaticMetaModelPopulationSetting.DISABLED; //we need to process types from superclasses to subclasses for ( Object mapping : orderedMappings ) { @@ -266,7 +267,8 @@ public class MetadataContext { LOG.trace( "Starting entity [" + safeMapping.getEntityName() + ']' ); } try { - final EntityDomainType jpaMapping = (EntityDomainType) entityTypesByPersistentClass.get( safeMapping ); + final EntityDomainType jpaMapping = (EntityDomainType) + entityTypesByPersistentClass.get( safeMapping ); applyIdMetadata( safeMapping, jpaMapping ); applyVersionAttribute( safeMapping, jpaMapping ); @@ -315,7 +317,8 @@ public class MetadataContext { LOG.trace( "Starting mapped superclass [" + safeMapping.getMappedClass().getName() + ']' ); } try { - final MappedSuperclassDomainType jpaType = (MappedSuperclassDomainType) mappedSuperclassByMappedSuperclassMapping.get( safeMapping ); + final MappedSuperclassDomainType jpaType = (MappedSuperclassDomainType) + mappedSuperclassByMappedSuperclassMapping.get( safeMapping ); applyIdMetadata( safeMapping, jpaType ); applyVersionAttribute( safeMapping, jpaType ); @@ -366,10 +369,9 @@ public class MetadataContext { for ( EmbeddableDomainType embeddable : processingEmbeddables ) { final Component component = componentByEmbeddable.get( embeddable ); - final Iterator propertyItr = component.getPropertyIterator(); - while ( propertyItr.hasNext() ) { - final Property property = propertyItr.next(); - final PersistentAttribute attribute = attributeFactory.buildAttribute( (ManagedDomainType) embeddable, property ); + for ( Property property : component.getProperties() ) { + final PersistentAttribute attribute = + attributeFactory.buildAttribute( (ManagedDomainType) embeddable, property ); if ( attribute != null ) { addAttribute( embeddable, attribute ); } @@ -386,16 +388,19 @@ public class MetadataContext { } private void addAttribute(ManagedDomainType type, PersistentAttribute attribute) { - final AttributeContainer.InFlightAccess inFlightAccess = ( (AttributeContainer) type ).getInFlightAccess(); + //noinspection unchecked + AttributeContainer container = (AttributeContainer) type; + final AttributeContainer.InFlightAccess inFlightAccess = container.getInFlightAccess(); final boolean virtual = attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED && attribute.getAttributeJavaType() instanceof EntityJavaType; if ( virtual ) { final EmbeddableDomainType embeddableDomainType = (EmbeddableDomainType) attribute.getValueGraphType(); final Component component = componentByEmbeddable.get( embeddableDomainType ); - final Iterator propertyItr = component.getPropertyIterator(); - while ( propertyItr.hasNext() ) { - final Property property = propertyItr.next(); - final PersistentAttribute subAttribute = attributeFactory.buildAttribute( (ManagedDomainType) embeddableDomainType, property ); + for ( Property property : component.getProperties() ) { + //noinspection unchecked + ManagedDomainType managedDomainType = (ManagedDomainType) embeddableDomainType; + final PersistentAttribute subAttribute = + attributeFactory.buildAttribute( managedDomainType, property ); if ( subAttribute != null ) { inFlightAccess.addAttribute( subAttribute ); } @@ -411,7 +416,6 @@ public class MetadataContext { // 2) register the part (mapping role) // 3) somehow get the mapping role "into" the part (setter, ?) - @SuppressWarnings({"unchecked", "rawtypes"}) private void applyIdMetadata(PersistentClass persistentClass, IdentifiableDomainType identifiableType) { if ( persistentClass.hasIdentifierProperty() ) { final Property declaredIdentifierProperty = persistentClass.getDeclaredIdentifierProperty(); @@ -421,53 +425,54 @@ public class MetadataContext { declaredIdentifierProperty ); + //noinspection unchecked rawtypes ( ( AttributeContainer) identifiableType ).getInFlightAccess().applyIdAttribute( idAttribute ); } } else { // we have a non-aggregated composite-id - //noinspection RedundantClassCall - if ( ! Component.class.isInstance( persistentClass.getIdentifier() ) ) { + if ( !(persistentClass.getIdentifier() instanceof Component) ) { throw new MappingException( "Expecting Component for id mapping with no id-attribute" ); } // Handle the actual id-attributes final Component cidValue = (Component) persistentClass.getIdentifier(); - final Iterator cidPropertyItr; + final List cidProperties; final int propertySpan; final EmbeddableTypeImpl idClassType; final Component identifierMapper = persistentClass.getIdentifierMapper(); if ( identifierMapper != null ) { - cidPropertyItr = identifierMapper.getPropertyIterator(); + cidProperties = identifierMapper.getProperties(); propertySpan = identifierMapper.getPropertySpan(); idClassType = applyIdClassMetadata( (Component) persistentClass.getIdentifier() ); } else { - cidPropertyItr = cidValue.getPropertyIterator(); + cidProperties = cidValue.getProperties(); propertySpan = cidValue.getPropertySpan(); idClassType = null; } assert cidValue.isEmbedded(); - AbstractIdentifiableType idType = (AbstractIdentifiableType) entityTypesByEntityName.get( cidValue.getOwner().getEntityName() ); + AbstractIdentifiableType idType = (AbstractIdentifiableType) + entityTypesByEntityName.get( cidValue.getOwner().getEntityName() ); + //noinspection rawtypes Set idAttributes = idType.getIdClassAttributesSafely(); if ( idAttributes == null ) { idAttributes = new HashSet<>( propertySpan ); - while ( cidPropertyItr.hasNext() ) { - final Property cidSubProperty = cidPropertyItr.next(); - final SingularPersistentAttribute cidSubAttr = attributeFactory.buildIdAttribute( - idType, - cidSubProperty - ); - + for ( Property cidSubproperty : cidProperties ) { + final SingularPersistentAttribute cidSubAttr = + attributeFactory.buildIdAttribute( idType, cidSubproperty ); + //noinspection unchecked idAttributes.add( cidSubAttr ); } } - ( ( AttributeContainer) identifiableType ).getInFlightAccess().applyNonAggregatedIdAttributes( idAttributes, idClassType ); + AttributeContainer container = (AttributeContainer) identifiableType; + //noinspection unchecked + container.getInFlightAccess().applyNonAggregatedIdAttributes( idAttributes, idClassType ); } } @@ -486,12 +491,12 @@ public class MetadataContext { return embeddableType; } - @SuppressWarnings({"unchecked", "rawtypes"}) private void applyIdMetadata(MappedSuperclass mappingType, MappedSuperclassDomainType jpaMappingType) { if ( mappingType.hasIdentifierProperty() ) { final Property declaredIdentifierProperty = mappingType.getDeclaredIdentifierProperty(); if ( declaredIdentifierProperty != null ) { - final SingularPersistentAttribute attribute = attributeFactory.buildIdAttribute( jpaMappingType, declaredIdentifierProperty ); + final SingularPersistentAttribute attribute = + attributeFactory.buildIdAttribute( jpaMappingType, declaredIdentifierProperty ); //noinspection unchecked ( ( AttributeContainer) jpaMappingType ).getInFlightAccess().applyIdAttribute( attribute ); } @@ -500,7 +505,7 @@ public class MetadataContext { else if ( mappingType.getIdentifierMapper() != null ) { Set> attributes = buildIdClassAttributes( jpaMappingType, - mappingType.getIdentifierMapper().getPropertyIterator() + mappingType.getIdentifierMapper().getProperties() ); //noinspection unchecked ( ( AttributeContainer) jpaMappingType ).getInFlightAccess().applyIdClassAttributes( attributes ); @@ -529,13 +534,13 @@ public class MetadataContext { private Set> buildIdClassAttributes( IdentifiableDomainType ownerType, - Iterator propertyIterator) { + List properties) { if ( LOG.isTraceEnabled() ) { LOG.trace( "Building old-school composite identifier [" + ownerType.getJavaType().getName() + ']' ); } Set> attributes = new HashSet<>(); - while ( propertyIterator.hasNext() ) { - attributes.add( attributeFactory.buildIdAttribute( ownerType, propertyIterator.next() ) ); + for ( Property property : properties ) { + attributes.add( attributeFactory.buildIdAttribute( ownerType, property ) ); } return attributes; } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractEmbeddableMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractEmbeddableMapping.java index 7369de3171..8eb2205206 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractEmbeddableMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractEmbeddableMapping.java @@ -7,7 +7,6 @@ package org.hibernate.metamodel.mapping.internal; import java.io.Serializable; -import java.util.Iterator; import java.util.Locale; import java.util.function.Consumer; @@ -152,9 +151,7 @@ public abstract class AbstractEmbeddableMapping implements EmbeddableMappingType int attributeIndex = 0; int columnPosition = 0; - final Iterator propertyIterator = bootDescriptor.getPropertyIterator(); - while ( propertyIterator.hasNext() ) { - final Property bootPropertyDescriptor = propertyIterator.next(); + for ( Property bootPropertyDescriptor : bootDescriptor.getProperties() ) { final Type subtype = subtypes[ attributeIndex ]; attributeTypeValidator.check( bootPropertyDescriptor.getName(), subtype ); diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddableMappingTypeImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddableMappingTypeImpl.java index f2861b26da..cce553e203 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddableMappingTypeImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddableMappingTypeImpl.java @@ -292,9 +292,7 @@ public class EmbeddableMappingTypeImpl extends AbstractEmbeddableMapping impleme // Reset the attribute mappings that were added in previous attempts this.attributeMappings.clear(); - final Iterator propertyIterator = bootDescriptor.getPropertyIterator(); - while ( propertyIterator.hasNext() ) { - final Property bootPropertyDescriptor = propertyIterator.next(); + for ( Property bootPropertyDescriptor : bootDescriptor.getProperties() ) { final AttributeMapping attributeMapping; final Type subtype = subtypes[attributeIndex]; diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EntityCollectionPart.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EntityCollectionPart.java index 43af120deb..082af96a7a 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EntityCollectionPart.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EntityCollectionPart.java @@ -286,7 +286,7 @@ public class EntityCollectionPart final BasicValuedModelPart basicFkTargetPart = (BasicValuedModelPart) fkTargetPart; final SelectableMapping keySelectableMapping = SelectableMappingImpl.from( fkKeyTableName, - fkBootDescriptorSource.getColumnIterator().next(), + fkBootDescriptorSource.getSelectables().get(0), basicFkTargetPart.getJdbcMapping(), dialect, creationProcess.getSqmFunctionRegistry() diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java index 0b2b3c7b0c..9f405aecd1 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java @@ -580,7 +580,7 @@ public class MappingModelCreationHelper { final BasicValue index = (BasicValue) ( (IndexedCollection) bootValueMapping ).getIndex(); final SelectableMapping selectableMapping = SelectableMappingImpl.from( tableExpression, - index.getColumnIterator().next(), + index.getSelectables().get(0), creationContext.getTypeConfiguration().getBasicTypeForJavaType( Integer.class ), dialect, creationProcess.getSqmFunctionRegistry() @@ -631,7 +631,7 @@ public class MappingModelCreationHelper { final BasicValue index = (BasicValue) ( (IndexedCollection) bootValueMapping ).getIndex(); final SelectableMapping selectableMapping = SelectableMappingImpl.from( tableExpression, - index.getColumnIterator().next(), + index.getSelectables().get(0), creationContext.getTypeConfiguration().getBasicTypeForJavaType( Integer.class ), dialect, creationProcess.getSqmFunctionRegistry() @@ -858,7 +858,7 @@ public class MappingModelCreationHelper { final String tableExpression = getTableIdentifierExpression( bootValueMappingKey.getTable(), creationProcess ); final SelectableMapping keySelectableMapping = SelectableMappingImpl.from( tableExpression, - bootValueMappingKey.getColumnIterator().next(), + bootValueMappingKey.getSelectables().get(0), (JdbcMapping) keyType, dialect, creationProcess.getSqmFunctionRegistry() @@ -1320,7 +1320,7 @@ public class MappingModelCreationHelper { final BasicValue basicValue = (BasicValue) bootMapKeyDescriptor; final SelectableMapping selectableMapping = SelectableMappingImpl.from( tableExpression, - basicValue.getColumnIterator().next(), + basicValue.getSelectables().get(0), basicValue.resolve().getJdbcMapping(), dialect, creationProcess.getSqmFunctionRegistry() @@ -1403,7 +1403,7 @@ public class MappingModelCreationHelper { final BasicValue basicElement = (BasicValue) element; final SelectableMapping selectableMapping = SelectableMappingImpl.from( tableExpression, - basicElement.getColumnIterator().next(), + basicElement.getSelectables().get(0), basicElement.resolve().getJdbcMapping(), dialect, creationProcess.getSqmFunctionRegistry() diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SelectableMappingsImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SelectableMappingsImpl.java index 0a642a7f2f..989a00b340 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SelectableMappingsImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SelectableMappingsImpl.java @@ -64,13 +64,13 @@ public class SelectableMappingsImpl implements SelectableMappings { final List jdbcMappings = new ArrayList<>(); resolveJdbcMappings( jdbcMappings, mapping, value.getType() ); - final List constraintColumns = value.getSelectables(); + final List selectables = value.getVirtualSelectables(); final SelectableMapping[] selectableMappings = new SelectableMapping[jdbcMappings.size()]; - for ( int i = 0; i < constraintColumns.size(); i++ ) { + for ( int i = 0; i < selectables.size(); i++ ) { selectableMappings[propertyOrder[i]] = SelectableMappingImpl.from( containingTableExpression, - constraintColumns.get( i ), + selectables.get( i ), jdbcMappings.get( propertyOrder[i] ), dialect, sqmFunctionRegistry @@ -85,13 +85,9 @@ public class SelectableMappingsImpl implements SelectableMappings { final List selectableMappings = CollectionHelper.arrayList( propertySpan ); embeddableMappingType.forEachAttributeMapping( - (index, attributeMapping) -> { - attributeMapping.forEachSelectable( - (columnIndex, selection) -> { - selectableMappings.add( selection ); - } - ); - } + (index, attributeMapping) -> attributeMapping.forEachSelectable( + (columnIndex, selection) -> selectableMappings.add( selection ) + ) ); return new SelectableMappingsImpl( selectableMappings.toArray( new SelectableMapping[0] ) ); diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java index b3466ad09a..ed892e0374 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java @@ -229,7 +229,7 @@ public class ToOneAttributeMapping if ( join.getPersistentClass().getEntityName().equals( entityBinding.getEntityName() ) && join.getPropertySpan() == 1 && join.getTable() == manyToOne.getTable() - && equal( join.getKey().getColumnIterator(), manyToOne.getColumnIterator() ) ) { + && equal( join.getKey(), manyToOne ) ) { bidirectionalAttributeName = join.getPropertyIterator().next().getName(); break; } @@ -503,7 +503,9 @@ public class ToOneAttributeMapping this.isConstrained = original.isConstrained; } - private static boolean equal(Iterator lhsColumns, Iterator rhsColumns) { + private static boolean equal(Value lhsValue, Value rhsValue) { + Iterator lhsColumns = lhsValue.getColumnIterator(); + Iterator rhsColumns = rhsValue.getColumnIterator(); boolean hasNext; do { final Selectable lhs = lhsColumns.next(); diff --git a/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java index 372a9cbbe8..86103961d4 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/collection/AbstractCollectionPersister.java @@ -358,14 +358,12 @@ public abstract class AbstractCollectionPersister // KEY keyType = collectionBootDescriptor.getKey().getType(); - Iterator columnIter = collectionBootDescriptor.getKey().getColumnIterator(); int keySpan = collectionBootDescriptor.getKey().getColumnSpan(); keyColumnNames = new String[keySpan]; keyColumnAliases = new String[keySpan]; int k = 0; - while ( columnIter.hasNext() ) { + for ( Column column: collectionBootDescriptor.getKey().getColumns() ) { // NativeSQL: collect key column and auto-aliases - Column column = (Column) columnIter.next(); keyColumnNames[k] = column.getQuotedName( dialect ); keyColumnAliases[k] = column.getAlias( dialect, table ); k++; @@ -404,9 +402,7 @@ public abstract class AbstractCollectionPersister columnInsertability = elementBootDescriptor.getColumnInsertability(); } int j = 0; - columnIter = elementBootDescriptor.getColumnIterator(); - while ( columnIter.hasNext() ) { - Selectable selectable = columnIter.next(); + for ( Selectable selectable: elementBootDescriptor.getSelectables() ) { elementColumnAliases[j] = selectable.getAlias( dialect, table ); if ( selectable.isFormula() ) { Formula form = (Formula) selectable; @@ -455,7 +451,6 @@ public abstract class AbstractCollectionPersister int indexSpan = indexedCollection.getIndex().getColumnSpan(); boolean[] indexColumnInsertability = indexedCollection.getIndex().getColumnInsertability(); boolean[] indexColumnUpdatability = indexedCollection.getIndex().getColumnUpdateability(); - columnIter = indexedCollection.getIndex().getColumnIterator(); indexColumnNames = new String[indexSpan]; indexFormulaTemplates = new String[indexSpan]; indexFormulas = new String[indexSpan]; @@ -464,8 +459,7 @@ public abstract class AbstractCollectionPersister indexColumnAliases = new String[indexSpan]; int i = 0; boolean hasFormula = false; - while ( columnIter.hasNext() ) { - Selectable s = columnIter.next(); + for ( Selectable s: indexedCollection.getIndex().getSelectables() ) { indexColumnAliases[i] = s.getAlias( dialect ); if ( s.isFormula() ) { Formula indexForm = (Formula) s; @@ -516,8 +510,7 @@ public abstract class AbstractCollectionPersister } IdentifierCollection idColl = (IdentifierCollection) collectionBootDescriptor; identifierType = idColl.getIdentifier().getType(); - columnIter = idColl.getIdentifier().getColumnIterator(); - Column col = (Column) columnIter.next(); + Column col = idColl.getIdentifier().getColumns().get(0); identifierColumnName = col.getQuotedName( dialect ); identifierColumnAlias = col.getAlias( dialect ); identifierGenerator = idColl.getIdentifier().createIdentifierGenerator( diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java index d4ca8e6481..8bc62fcc3d 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/AbstractEntityPersister.java @@ -284,7 +284,6 @@ public abstract class AbstractEntityPersister public static final String VERSION_COLUMN_ALIAS = "version_"; private final String sqlAliasStem; - private EntityMappingType rootEntityDescriptor; private final SingleIdEntityLoader singleIdEntityLoader; private final MultiIdEntityLoader multiIdEntityLoader; @@ -774,24 +773,22 @@ public abstract class AbstractEntityPersister multiIdEntityLoader = new MultiIdLoaderStandard<>( this, bootDescriptor, factory ); - Iterator idColumns = bootDescriptor.getIdentifier().getColumnIterator(); int i = 0; - while ( idColumns.hasNext() ) { - Column col = (Column) idColumns.next(); - rootTableKeyColumnNames[i] = col.getQuotedName( dialect ); - rootTableKeyColumnReaders[i] = col.getReadExpr( dialect ); - rootTableKeyColumnReaderTemplates[i] = col.getTemplate( + for ( Column column: bootDescriptor.getIdentifier().getColumns() ) { + rootTableKeyColumnNames[i] = column.getQuotedName( dialect ); + rootTableKeyColumnReaders[i] = column.getReadExpr( dialect ); + rootTableKeyColumnReaderTemplates[i] = column.getTemplate( dialect, factory.getQueryEngine().getSqmFunctionRegistry() ); - identifierAliases[i] = col.getAlias( dialect, bootDescriptor.getRootTable() ); + identifierAliases[i] = column.getAlias( dialect, bootDescriptor.getRootTable() ); i++; } // VERSION if ( bootDescriptor.isVersioned() ) { - versionColumnName = ( (Column) bootDescriptor.getVersion().getColumnIterator().next() ).getQuotedName( dialect ); + versionColumnName = bootDescriptor.getVersion().getColumns().get(0).getQuotedName( dialect ); } else { versionColumnName = null; @@ -841,11 +838,9 @@ public abstract class AbstractEntityPersister ArrayList lazyColAliases = new ArrayList<>(); final ArrayList lobPropertiesLocalCollector = new ArrayList<>(); - Iterator properties = bootDescriptor.getPropertyClosureIterator(); i = 0; boolean foundFormula = false; - while ( properties.hasNext() ) { - Property prop = properties.next(); + for ( Property prop : bootDescriptor.getPropertyClosure() ) { thisClassProperties.add( prop ); int span = prop.getColumnSpan(); @@ -856,18 +851,16 @@ public abstract class AbstractEntityPersister String[] colReaderTemplates = new String[span]; String[] colWriters = new String[span]; String[] formulaTemplates = new String[span]; - Iterator colIter = prop.getColumnIterator(); int k = 0; - while ( colIter.hasNext() ) { - Selectable thing = colIter.next(); - colAliases[k] = thing.getAlias( dialect, prop.getValue().getTable() ); - if ( thing.isFormula() ) { + for ( Selectable selectable: prop.getSelectables() ) { + colAliases[k] = selectable.getAlias( dialect, prop.getValue().getTable() ); + if ( selectable.isFormula() ) { foundFormula = true; - ( (Formula) thing ).setFormula( substituteBrackets( ( (Formula) thing ).getFormula() ) ); - formulaTemplates[k] = thing.getTemplate( dialect, factory.getQueryEngine().getSqmFunctionRegistry() ); + ( (Formula) selectable ).setFormula( substituteBrackets( ( (Formula) selectable ).getFormula() ) ); + formulaTemplates[k] = selectable.getTemplate( dialect, factory.getQueryEngine().getSqmFunctionRegistry() ); } else { - Column col = (Column) thing; + Column col = (Column) selectable; colNames[k] = col.getQuotedName( dialect ); colReaderTemplates[k] = col.getTemplate( dialect, factory.getQueryEngine().getSqmFunctionRegistry() ); colWriters[k] = col.getWriteExpr(); @@ -945,9 +938,7 @@ public abstract class AbstractEntityPersister ArrayList columnSelectables = new ArrayList<>(); ArrayList propNullables = new ArrayList<>(); - Iterator iter = bootDescriptor.getSubclassPropertyClosureIterator(); - while ( iter.hasNext() ) { - final Property prop = iter.next(); + for ( Property prop : bootDescriptor.getSubclassPropertyClosure() ) { names.add( prop.getName() ); classes.add( prop.getPersistentClass().getEntityName() ); types.add( prop.getType() ); @@ -956,7 +947,6 @@ public abstract class AbstractEntityPersister definedBySubclass.add( Boolean.valueOf( isDefinedBySubclass ) ); propNullables.add( Boolean.valueOf( prop.isOptional() || isDefinedBySubclass ) ); //TODO: is this completely correct? - final Iterator colIter = prop.getColumnIterator(); String[] cols = new String[ prop.getColumnSpan() ]; String[] readers = new String[ prop.getColumnSpan() ]; String[] readerTemplates = new String[ prop.getColumnSpan() ]; @@ -968,7 +958,7 @@ public abstract class AbstractEntityPersister final boolean lazy = ! EnhancementHelper.includeInBaseFetchGroup( prop, entityMetamodel.isInstrumented(), - (entityName) -> { + entityName -> { final MetadataImplementor metadata = creationContext.getMetadata(); final PersistentClass entityBinding = metadata.getEntityBinding( entityName ); assert entityBinding != null; @@ -976,26 +966,25 @@ public abstract class AbstractEntityPersister }, sessionFactoryOptions.isCollectionsInDefaultFetchGroupEnabled() ); - while ( colIter.hasNext() ) { - final Selectable thing = colIter.next(); - if ( thing.isFormula() ) { - String template = thing.getTemplate( dialect, factory.getQueryEngine().getSqmFunctionRegistry() ); + for ( Selectable selectable : prop.getSelectables() ) { + if ( selectable.isFormula() ) { + String template = selectable.getTemplate( dialect, factory.getQueryEngine().getSqmFunctionRegistry() ); formnos[l] = formulaTemplates.size(); colnos[l] = -1; formulaTemplates.add( template ); forms[l] = template; - formulas.add( thing.getText( dialect ) ); - formulaAliases.add( thing.getAlias( dialect ) ); + formulas.add( selectable.getText( dialect ) ); + formulaAliases.add( selectable.getAlias( dialect ) ); formulasLazy.add( lazy ); } else { - Column col = (Column) thing; + Column col = (Column) selectable; String colName = col.getQuotedName( dialect ); colnos[l] = columns.size(); //before add :-) formnos[l] = -1; columns.add( colName ); cols[l] = colName; - aliases.add( thing.getAlias( dialect, prop.getValue().getTable() ) ); + aliases.add( selectable.getAlias( dialect, prop.getValue().getTable() ) ); columnsLazy.add( lazy ); columnSelectables.add( Boolean.valueOf( prop.isSelectable() ) ); @@ -1059,29 +1048,9 @@ public abstract class AbstractEntityPersister filterHelper = null; } - // Check if we can use Reference Cached entities in 2lc - // todo : should really validate that the cache access type is read-only - boolean refCacheEntries = true; - if ( !factory.getSessionFactoryOptions().isDirectReferenceCacheEntriesEnabled() ) { - refCacheEntries = false; - } + useReferenceCacheEntries = useReferenceCacheEntries(); - // for now, limit this to just entities that: - // 1) are immutable - if ( entityMetamodel.isMutable() ) { - refCacheEntries = false; - } - - // 2) have no associations. Eventually we want to be a little more lenient with associations. - for ( Type type : getSubclassPropertyTypeClosure() ) { - if ( type.isAssociationType() ) { - refCacheEntries = false; - } - } - - useReferenceCacheEntries = refCacheEntries; - - this.cacheEntryHelper = buildCacheEntryHelper(); + cacheEntryHelper = buildCacheEntryHelper(); if ( sessionFactoryOptions.isSecondLevelCacheEnabled() ) { this.invalidateCache = canWriteToCache && shouldInvalidateCache( bootDescriptor, creationContext ); @@ -1092,6 +1061,30 @@ public abstract class AbstractEntityPersister } + private boolean useReferenceCacheEntries() { + // Check if we can use Reference Cached entities in 2lc + // todo : should really validate that the cache access type is read-only + if ( !factory.getSessionFactoryOptions().isDirectReferenceCacheEntriesEnabled() ) { + return false; + } + + // for now, limit this to just entities that: + else if ( entityMetamodel.isMutable() ) { + // 1) are immutable + return false; + } + else { + // 2) have no associations. + // Eventually we want to be a little more lenient with associations. + for ( Type type : getSubclassPropertyTypeClosure() ) { + if ( type.isAssociationType() ) { + return false; + } + } + return true; + } + } + private static SingleIdEntityLoader createBatchingIdEntityLoader( EntityMappingType entityDescriptor, int batchSize, @@ -2355,13 +2348,7 @@ public abstract class AbstractEntityPersister } private DiscriminatorMetadata buildTypeDiscriminatorMetadata() { - return new DiscriminatorMetadata() { - - @Override - public Type getResolutionType() { - return new DiscriminatorType( (BasicType) getDiscriminatorType(), AbstractEntityPersister.this ); - } - }; + return () -> new DiscriminatorType( (BasicType) getDiscriminatorType(), AbstractEntityPersister.this ); } public static String generateTableAlias(String rootAlias, int tableNumber) { @@ -2530,13 +2517,11 @@ public abstract class AbstractEntityPersister } ); } - if ( attributeNames != null ) { - final boolean[] propertyUpdateability = entityMetamodel.getPropertyUpdateability(); - for ( String attributeName : attributeNames ) { - final Integer index = entityMetamodel.getPropertyIndexOrNull( attributeName ); - if ( index != null && propertyUpdateability[index] && !fields.contains( index ) ) { - fields.add( index ); - } + final boolean[] propertyUpdateability = entityMetamodel.getPropertyUpdateability(); + for ( String attributeName : attributeNames ) { + final Integer index = entityMetamodel.getPropertyIndexOrNull( attributeName ); + if ( index != null && propertyUpdateability[index] && !fields.contains( index ) ) { + fields.add( index ); } } @@ -2599,7 +2584,7 @@ public abstract class AbstractEntityPersister protected void initSubclassPropertyAliasesMap(PersistentClass model) throws MappingException { // ALIASES - internalInitSubclassPropertyAliasesMap( null, model.getSubclassPropertyClosureIterator() ); + internalInitSubclassPropertyAliasesMap( null, model.getSubclassPropertyClosure() ); // aliases for identifier ( alias.id ); skip if the entity defines a non-id property named 'id' if ( !entityMetamodel.hasNonIdentifierPropertyNamedId() ) { @@ -2658,31 +2643,26 @@ public abstract class AbstractEntityPersister } - private void internalInitSubclassPropertyAliasesMap(String path, Iterator propertyIterator) { - while ( propertyIterator.hasNext() ) { - - Property prop = propertyIterator.next(); - String propname = path == null ? prop.getName() : path + "." + prop.getName(); - if ( prop.isComposite() ) { - Component component = (Component) prop.getValue(); - Iterator compProps = component.getPropertyIterator(); - internalInitSubclassPropertyAliasesMap( propname, compProps ); + private void internalInitSubclassPropertyAliasesMap(String path, List properties) { + for (Property property : properties) { + String name = path == null ? property.getName() : path + "." + property.getName(); + if ( property.isComposite() ) { + Component component = (Component) property.getValue(); + internalInitSubclassPropertyAliasesMap( name, component.getProperties() ); } else { - String[] aliases = new String[prop.getColumnSpan()]; - String[] cols = new String[prop.getColumnSpan()]; - Iterator colIter = prop.getColumnIterator(); + String[] aliases = new String[property.getColumnSpan()]; + String[] cols = new String[property.getColumnSpan()]; int l = 0; - while ( colIter.hasNext() ) { - Selectable thing = colIter.next(); + for ( Selectable selectable: property.getSelectables() ) { Dialect dialect = getFactory().getJdbcServices().getDialect(); - aliases[l] = thing.getAlias( dialect, prop.getValue().getTable() ); - cols[l] = thing.getText(dialect); // TODO: skip formulas? + aliases[l] = selectable.getAlias( dialect, property.getValue().getTable() ); + cols[l] = selectable.getText(dialect); // TODO: skip formulas? l++; } - subclassPropertyAliases.put( propname, aliases ); - subclassPropertyColumnNames.put( propname, cols ); + subclassPropertyAliases.put( name, aliases ); + subclassPropertyColumnNames.put( name, cols ); } } @@ -4389,9 +4369,8 @@ public abstract class AbstractEntityPersister public final boolean[] getPropertiesToUpdate(final int[] dirtyProperties, final boolean hasDirtyCollection) { final boolean[] propsToUpdate = new boolean[entityMetamodel.getPropertySpan()]; final boolean[] updateability = getPropertyUpdateability(); //no need to check laziness, dirty checking handles that - for ( int j = 0; j < dirtyProperties.length; j++ ) { - int property = dirtyProperties[j]; - if ( updateability[property] ) { + for ( int property: dirtyProperties ) { + if (updateability[property]) { propsToUpdate[property] = true; } } @@ -4490,9 +4469,9 @@ public abstract class AbstractEntityPersister private void logDirtyProperties(int[] props) { if ( LOG.isTraceEnabled() ) { - for ( int i = 0; i < props.length; i++ ) { - String propertyName = entityMetamodel.getProperties()[props[i]].getName(); - LOG.trace( StringHelper.qualify( getEntityName(), propertyName ) + " is dirty" ); + for ( int prop : props ) { + String propertyName = entityMetamodel.getProperties()[prop].getName(); + LOG.trace(StringHelper.qualify(getEntityName(), propertyName) + " is dirty"); } } } @@ -5501,6 +5480,7 @@ public abstract class AbstractEntityPersister .getBootModel() .getEntityBinding( getEntityName() ); + EntityMappingType rootEntityDescriptor; if ( superMappingType != null ) { ( (InFlightEntityMappingType) superMappingType ).prepareMappingModel( creationProcess ); if ( shouldProcessSuperMapping() ) { @@ -5528,10 +5508,8 @@ public abstract class AbstractEntityPersister final NonIdentifierAttribute runtimeAttrDefinition = properties[i]; final Property bootProperty = bootEntityDescriptor.getProperty( runtimeAttrDefinition.getName() ); - if ( superMappingType != null && superMappingType.findAttributeMapping( bootProperty.getName() ) != null ) { - // its defined on the super-type, skip it here - } - else { + if ( superMappingType == null + || superMappingType.findAttributeMapping( bootProperty.getName() ) == null ) { declaredAttributeMappings.put( runtimeAttrDefinition.getName(), generateNonIdAttributeMapping( @@ -5542,6 +5520,9 @@ public abstract class AbstractEntityPersister ) ); } +// else { + // its defined on the supertype, skip it here +// } } getAttributeMappings(); @@ -5577,8 +5558,8 @@ public abstract class AbstractEntityPersister } ); - boolean needsMultiTableInsert; - if ( needsMultiTableInsert = isMultiTable() ) { + boolean needsMultiTableInsert = isMultiTable(); + if ( needsMultiTableInsert ) { creationProcess.registerInitializationCallback( "Entity(" + getEntityName() + ") `sqmMultiTableMutationStrategy` interpretation", () -> { @@ -6074,9 +6055,9 @@ public abstract class AbstractEntityPersister attrColumnExpression = attrColumnNames[ 0 ]; isAttrColumnExpressionFormula = false; - final Iterator selectableIterator = basicBootValue.getColumnIterator(); - assert selectableIterator.hasNext(); - final Selectable selectable = selectableIterator.next(); + final List selectables = basicBootValue.getSelectables(); + assert !selectables.isEmpty(); + final Selectable selectable = selectables.get(0); assert attrColumnExpression.equals( selectable.getText(sessionFactory.getJdbcServices().getDialect()) ); diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/JoinedSubclassEntityPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/JoinedSubclassEntityPersister.java index 24dee10463..2e2b858e6d 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/JoinedSubclassEntityPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/JoinedSubclassEntityPersister.java @@ -173,7 +173,7 @@ public class JoinedSubclassEntityPersister extends AbstractEntityPersister { if ( discriminatorMapping != null ) { log.debug( "Encountered explicit discriminator mapping for joined inheritance" ); - final Selectable selectable = discriminatorMapping.getColumnIterator().next(); + final Selectable selectable = discriminatorMapping.getSelectables().get(0); if ( selectable instanceof Formula ) { throw new MappingException( "Discriminator formulas on joined inheritance hierarchies not supported at this time" ); } @@ -259,12 +259,15 @@ public class JoinedSubclassEntityPersister extends AbstractEntityPersister { String[] keyCols = new String[idColumnSpan]; String[] keyColReaders = new String[idColumnSpan]; String[] keyColReaderTemplates = new String[idColumnSpan]; - Iterator cItr = key.getColumnIterator(); + List columns = key.getColumns(); for ( int k = 0; k < idColumnSpan; k++ ) { - Column column = (Column) cItr.next(); + Column column = columns.get(k); keyCols[k] = column.getQuotedName( factory.getJdbcServices().getDialect() ); keyColReaders[k] = column.getReadExpr( factory.getJdbcServices().getDialect() ); - keyColReaderTemplates[k] = column.getTemplate( factory.getJdbcServices().getDialect(), factory.getQueryEngine().getSqmFunctionRegistry() ); + keyColReaderTemplates[k] = column.getTemplate( + factory.getJdbcServices().getDialect(), + factory.getQueryEngine().getSqmFunctionRegistry() + ); } keyColumns.add( keyCols ); keyColumnReaders.add( keyColReaders ); @@ -297,9 +300,9 @@ public class JoinedSubclassEntityPersister extends AbstractEntityPersister { String[] keyColReaders = new String[joinIdColumnSpan]; String[] keyColReaderTemplates = new String[joinIdColumnSpan]; - Iterator cItr = key.getColumnIterator(); + List columns = key.getColumns(); for ( int k = 0; k < joinIdColumnSpan; k++ ) { - Column column = (Column) cItr.next(); + Column column = columns.get(k); keyCols[k] = column.getQuotedName( factory.getJdbcServices().getDialect() ); keyColReaders[k] = column.getReadExpr( factory.getJdbcServices().getDialect() ); keyColReaderTemplates[k] = column.getTemplate( factory.getJdbcServices().getDialect(), factory.getQueryEngine().getSqmFunctionRegistry() ); @@ -335,9 +338,9 @@ public class JoinedSubclassEntityPersister extends AbstractEntityPersister { final String tableName = determineTableName( tab ); subclassTableNames.add( tableName ); String[] key = new String[idColumnSpan]; - Iterator cItr = tab.getPrimaryKey().getColumnIterator(); + List columns = tab.getPrimaryKey().getColumns(); for ( int k = 0; k < idColumnSpan; k++ ) { - key[k] = cItr.next().getQuotedName( factory.getJdbcServices().getDialect() ); + key[k] = columns.get(k).getQuotedName( factory.getJdbcServices().getDialect() ); } keyColumns.add( key ); } @@ -357,9 +360,9 @@ public class JoinedSubclassEntityPersister extends AbstractEntityPersister { String joinTableName = determineTableName( joinTable ); subclassTableNames.add( joinTableName ); String[] key = new String[idColumnSpan]; - Iterator citer = joinTable.getPrimaryKey().getColumnIterator(); + List columns = joinTable.getPrimaryKey().getColumns(); for ( int k = 0; k < idColumnSpan; k++ ) { - key[k] = citer.next().getQuotedName( factory.getJdbcServices().getDialect() ); + key[k] = columns.get(k).getQuotedName( factory.getJdbcServices().getDialect() ); } keyColumns.add( key ); } @@ -473,11 +476,9 @@ public class JoinedSubclassEntityPersister extends AbstractEntityPersister { int hydrateSpan = getPropertySpan(); naturalOrderPropertyTableNumbers = new int[hydrateSpan]; propertyTableNumbers = new int[hydrateSpan]; - Iterator iter = persistentClass.getPropertyClosureIterator(); int i = 0; - while ( iter.hasNext() ) { - Property prop = iter.next(); - String tabname = prop.getValue().getTable().getQualifiedName( + for ( Property property : persistentClass.getPropertyClosure() ) { + String tabname = property.getValue().getTable().getQualifiedName( factory.getSqlStringGenerationContext() ); propertyTableNumbers[i] = getTableId( tabname, this.tableNames ); @@ -493,20 +494,16 @@ public class JoinedSubclassEntityPersister extends AbstractEntityPersister { ArrayList formulaTableNumbers = new ArrayList<>(); ArrayList propTableNumbers = new ArrayList<>(); - iter = persistentClass.getSubclassPropertyClosureIterator(); - while ( iter.hasNext() ) { - Property prop = iter.next(); - Table tab = prop.getValue().getTable(); + for ( Property property : persistentClass.getSubclassPropertyClosure() ) { + Table tab = property.getValue().getTable(); String tabname = tab.getQualifiedName( factory.getSqlStringGenerationContext() ); Integer tabnum = getTableId( tabname, subclassTableNameClosure ); propTableNumbers.add( tabnum ); - Iterator citer = prop.getColumnIterator(); - while ( citer.hasNext() ) { - Selectable thing = citer.next(); - if ( thing.isFormula() ) { + for ( Selectable selectable : property.getSelectables() ) { + if ( selectable.isFormula() ) { formulaTableNumbers.add( tabnum ); } else { diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/SingleTableEntityPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/SingleTableEntityPersister.java index 1ebe0b8164..a0e27d1b22 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/SingleTableEntityPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/SingleTableEntityPersister.java @@ -214,11 +214,9 @@ public class SingleTableEntityPersister extends AbstractEntityPersister { ? ExecuteUpdateResultCheckStyle.determineDefault( customSQLDelete[j], deleteCallable[j] ) : join.getCustomSQLDeleteCheckStyle(); - Iterator iter = join.getKey().getColumnIterator(); keyColumnNames[j] = new String[join.getKey().getColumnSpan()]; int i = 0; - while ( iter.hasNext() ) { - Column col = (Column) iter.next(); + for ( Column col : join.getKey().getColumns() ) { keyColumnNames[j][i++] = col.getQuotedName( dialect ); } @@ -270,11 +268,9 @@ public class SingleTableEntityPersister extends AbstractEntityPersister { String joinTableName = determineTableName( join.getTable() ); subclassTables.add( joinTableName ); - Iterator iter = join.getKey().getColumnIterator(); String[] keyCols = new String[join.getKey().getColumnSpan()]; int i = 0; - while ( iter.hasNext() ) { - Column col = (Column) iter.next(); + for ( Column col : join.getKey().getColumns() ) { keyCols[i++] = col.getQuotedName( dialect ); } joinKeyColumns.add( keyCols ); @@ -297,7 +293,7 @@ public class SingleTableEntityPersister extends AbstractEntityPersister { throw new MappingException( "discriminator mapping required for single table polymorphic persistence" ); } forceDiscriminator = persistentClass.isForceDiscriminator(); - Selectable selectable = discrimValue.getColumnIterator().next(); + Selectable selectable = discrimValue.getSelectables().get(0); if ( discrimValue.hasFormula() ) { Formula formula = (Formula) selectable; discriminatorFormula = formula.getFormula(); @@ -371,12 +367,9 @@ public class SingleTableEntityPersister extends AbstractEntityPersister { // PROPERTIES propertyTableNumbers = new int[getPropertySpan()]; - Iterator props = persistentClass.getPropertyClosureIterator(); int i = 0; - while ( props.hasNext() ) { - Property prop = props.next(); - propertyTableNumbers[i++] = persistentClass.getJoinNumber( prop ); - + for ( Property property : persistentClass.getPropertyClosure() ) { + propertyTableNumbers[i++] = persistentClass.getJoinNumber( property ); } //TODO: code duplication with JoinedSubclassEntityPersister @@ -388,22 +381,18 @@ public class SingleTableEntityPersister extends AbstractEntityPersister { final HashMap propertyTableNumbersByNameAndSubclassLocal = new HashMap<>(); final Map subclassesByDiscriminatorValueLocal = new HashMap<>(); - Iterator iter = persistentClass.getSubclassPropertyClosureIterator(); - while ( iter.hasNext() ) { - Property prop = iter.next(); - Integer join = persistentClass.getJoinNumber( prop ); + for ( Property property : persistentClass.getSubclassPropertyClosure() ) { + Integer join = persistentClass.getJoinNumber( property ); propertyJoinNumbers.add( join ); //propertyTableNumbersByName.put( prop.getName(), join ); propertyTableNumbersByNameAndSubclassLocal.put( - prop.getPersistentClass().getEntityName() + '.' + prop.getName(), + property.getPersistentClass().getEntityName() + '.' + property.getName(), join ); - Iterator citer = prop.getColumnIterator(); - while ( citer.hasNext() ) { - Selectable thing = citer.next(); - if ( thing.isFormula() ) { + for ( Selectable selectable : property.getSelectables() ) { + if ( selectable.isFormula() ) { formulaJoinedNumbers.add( join ); } else { diff --git a/hibernate-core/src/main/java/org/hibernate/persister/entity/UnionSubclassEntityPersister.java b/hibernate-core/src/main/java/org/hibernate/persister/entity/UnionSubclassEntityPersister.java index 46544ed690..a1cd73fcf1 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/entity/UnionSubclassEntityPersister.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/entity/UnionSubclassEntityPersister.java @@ -217,9 +217,9 @@ public class UnionSubclassEntityPersister extends AbstractEntityPersister { final String tableName = determineTableName( tab ); tableNames.add( tableName ); String[] key = new String[idColumnSpan]; - Iterator citer = tab.getPrimaryKey().getColumnIterator(); + List columns = tab.getPrimaryKey().getColumns(); for ( int k = 0; k < idColumnSpan; k++ ) { - key[k] = citer.next().getQuotedName( factory.getJdbcServices().getDialect() ); + key[k] = columns.get(k).getQuotedName( factory.getJdbcServices().getDialect() ); } keyColumns.add( key ); } @@ -473,9 +473,8 @@ public class UnionSubclassEntityPersister extends AbstractEntityPersister { while ( titer.hasNext() ) { Table table = titer.next(); if ( !table.isAbstractUnionTable() ) { - Iterator citer = table.getColumnIterator(); - while ( citer.hasNext() ) { - columns.add( citer.next() ); + for ( Column column : table.getColumns() ) { + columns.add( column ); } } } @@ -483,7 +482,6 @@ public class UnionSubclassEntityPersister extends AbstractEntityPersister { StringBuilder buf = new StringBuilder() .append( "( " ); - @SuppressWarnings("unchecked") Iterator siter = new JoinedIterator<>( new SingletonIterator<>( model ), model.getSubclassIterator() diff --git a/hibernate-core/src/main/java/org/hibernate/proxy/pojo/ProxyFactoryHelper.java b/hibernate-core/src/main/java/org/hibernate/proxy/pojo/ProxyFactoryHelper.java index 146f26d289..af2e6e8a40 100644 --- a/hibernate-core/src/main/java/org/hibernate/proxy/pojo/ProxyFactoryHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/proxy/pojo/ProxyFactoryHelper.java @@ -70,10 +70,8 @@ public final class ProxyFactoryHelper { } public static void validateProxyability(final PersistentClass persistentClass) { - Iterator properties = persistentClass.getPropertyIterator(); Class clazz = persistentClass.getMappedClass(); - while ( properties.hasNext() ) { - Property property = (Property) properties.next(); + for ( Property property : persistentClass.getProperties() ) { validateGetterSetterMethodProxyability( "Getter", property.getGetter( clazz ).getMethod() ); validateGetterSetterMethodProxyability( "Setter", property.getSetter( clazz ).getMethod() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/TenantIdBinder.java b/hibernate-core/src/main/java/org/hibernate/tuple/TenantIdBinder.java index 207c94637e..9993751e48 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/TenantIdBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/TenantIdBinder.java @@ -90,10 +90,10 @@ public class TenantIdBinder implements AttributeBinder { if ( property.getColumnSpan()!=1 ) { throw new MappingException("@TenantId attribute must be mapped to a single column or formula"); } - Selectable column = property.getColumnIterator().next(); - return column.isFormula() - ? ((Formula) column).getFormula() - : ((Column) column).getName(); + Selectable selectable = property.getSelectables().get(0); + return selectable.isFormula() + ? ((Formula) selectable).getFormula() + : ((Column) selectable).getName(); } } diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java b/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java index d9aaba1eb5..410a89d992 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java @@ -154,9 +154,8 @@ public class EntityMetamodel implements Serializable { if ( identifierMapperComponent != null ) { nonAggregatedCidMapper = (CompositeType) identifierMapperComponent.getType(); idAttributeNames = new HashSet<>( ); - final Iterator propertyItr = identifierMapperComponent.getPropertyIterator(); - while ( propertyItr.hasNext() ) { - idAttributeNames.add( propertyItr.next().getName() ); + for ( Property property : identifierMapperComponent.getProperties() ) { + idAttributeNames.add( property.getName() ); } } else { @@ -463,10 +462,8 @@ public class EntityMetamodel implements Serializable { SessionFactoryImplementor sessionFactory, Component composite, CompositeGenerationStrategyPairBuilder builder) { - Iterator subProperties = composite.getPropertyIterator(); - while ( subProperties.hasNext() ) { - final Property subProperty = (Property) subProperties.next(); - builder.addPair( buildGenerationStrategyPair( sessionFactory, subProperty ) ); + for ( Property property : composite.getProperties() ) { + builder.addPair( buildGenerationStrategyPair( sessionFactory, property ) ); } } @@ -616,10 +613,8 @@ public class EntityMetamodel implements Serializable { // start building the aggregate values int propertyIndex = -1; int columnIndex = 0; - Iterator subProperties = composite.getPropertyIterator(); - while ( subProperties.hasNext() ) { + for ( Property property : composite.getProperties() ) { propertyIndex++; - final Property subProperty = (Property) subProperties.next(); final InDatabaseValueGenerationStrategy subStrategy = inDatabaseStrategies.get( propertyIndex ); if ( subStrategy.getGenerationTiming() == GenerationTiming.ALWAYS ) { @@ -632,11 +627,11 @@ public class EntityMetamodel implements Serializable { referenceColumns = true; } if ( subStrategy.getReferencedColumnValues() != null ) { - if ( subStrategy.getReferencedColumnValues().length != subProperty.getColumnSpan() ) { + if ( subStrategy.getReferencedColumnValues().length != property.getColumnSpan() ) { throw new ValueGenerationStrategyException( "Internal error : mismatch between number of collected 'referenced column values'" + " and number of columns for composite attribute : " + mappingProperty.getName() + - '.' + subProperty.getName() + '.' + property.getName() ); } System.arraycopy( @@ -644,7 +639,7 @@ public class EntityMetamodel implements Serializable { 0, columnValues, columnIndex, - subProperty.getColumnSpan() + property.getColumnSpan() ); } } @@ -760,9 +755,8 @@ public class EntityMetamodel implements Serializable { private void mapPropertyToIndex(Property prop, int i) { propertyIndexes.put( prop.getName(), i ); if ( prop.getValue() instanceof Component ) { - Iterator iter = ( (Component) prop.getValue() ).getPropertyIterator(); - while ( iter.hasNext() ) { - Property subprop = (Property) iter.next(); + Component composite = (Component) prop.getValue(); + for ( Property subprop : composite.getProperties() ) { propertyIndexes.put( prop.getName() + '.' + subprop.getName(), i diff --git a/hibernate-core/src/main/java/org/hibernate/type/ComponentType.java b/hibernate-core/src/main/java/org/hibernate/type/ComponentType.java index d23683a5df..d42e18f210 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/ComponentType.java +++ b/hibernate-core/src/main/java/org/hibernate/type/ComponentType.java @@ -82,10 +82,8 @@ public class ComponentType extends AbstractType implements CompositeTypeImplemen this.cascade = new CascadeStyle[propertySpan]; this.joinedFetch = new FetchMode[propertySpan]; - final Iterator itr = component.getPropertyIterator(); int i = 0; - while ( itr.hasNext() ) { - final Property property = itr.next(); + for ( Property property : component.getProperties() ) { // todo (6.0) : see if we really need to create these final StandardProperty prop = PropertyFactory.buildStandardProperty( property, false ); this.propertyNames[i] = prop.getName(); diff --git a/hibernate-core/src/main/java/org/hibernate/type/EnumType.java b/hibernate-core/src/main/java/org/hibernate/type/EnumType.java index 630a46be42..8df48b7829 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/EnumType.java +++ b/hibernate-core/src/main/java/org/hibernate/type/EnumType.java @@ -118,7 +118,7 @@ public class EnumType> // the `reader != null` block handles annotations, while the `else` block // handles hbm.xml if ( reader != null ) { - enumClass = reader.getReturnedClass().asSubclass( Enum.class ); + enumClass = (Class) reader.getReturnedClass().asSubclass( Enum.class ); final Long columnLength = reader.getColumnLengths()[0]; diff --git a/hibernate-core/src/main/java/org/hibernate/type/SerializableToBlobType.java b/hibernate-core/src/main/java/org/hibernate/type/SerializableToBlobType.java index 00b2e75b83..dfcef74b9c 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/SerializableToBlobType.java +++ b/hibernate-core/src/main/java/org/hibernate/type/SerializableToBlobType.java @@ -73,7 +73,7 @@ public class SerializableToBlobType implements BasicType ParameterType reader = (ParameterType) parameters.get( PARAMETER_TYPE ); if ( reader != null ) { @SuppressWarnings("unchecked") - Class returnedClass = reader.getReturnedClass(); + Class returnedClass = (Class) reader.getReturnedClass(); setJavaTypeDescriptor( new SerializableJavaType<>(returnedClass) ); } else { diff --git a/hibernate-core/src/main/java/org/hibernate/usertype/DynamicParameterizedType.java b/hibernate-core/src/main/java/org/hibernate/usertype/DynamicParameterizedType.java index 2f03b3a170..58fa9cac28 100644 --- a/hibernate-core/src/main/java/org/hibernate/usertype/DynamicParameterizedType.java +++ b/hibernate-core/src/main/java/org/hibernate/usertype/DynamicParameterizedType.java @@ -32,7 +32,7 @@ public interface DynamicParameterizedType extends ParameterizedType { interface ParameterType { - Class getReturnedClass(); + Class getReturnedClass(); Annotation[] getAnnotationsMethod(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableTest.java index d75af8f9d5..d252e2af8d 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/annotations/immutable/ImmutableTest.java @@ -32,11 +32,10 @@ import static org.junit.Assert.fail; * * @author Hardy Ferentschik */ -@SuppressWarnings("unchecked") public class ImmutableTest extends BaseCoreFunctionalTestCase { @Test - public void testImmutableEntity() throws Exception { + public void testImmutableEntity() { Session s = openSession(); Transaction tx = s.beginTransaction(); Country country = new Country(); @@ -48,7 +47,7 @@ public class ImmutableTest extends BaseCoreFunctionalTestCase { // try changing the entity s = openSession(); tx = s.beginTransaction(); - Country germany = (Country) s.get(Country.class, country.getId()); + Country germany = s.get(Country.class, country.getId()); assertNotNull(germany); germany.setName("France"); assertEquals("Local name can be changed", "France", germany.getName()); @@ -59,7 +58,7 @@ public class ImmutableTest extends BaseCoreFunctionalTestCase { // retrieving the country again - it should be unmodified s = openSession(); tx = s.beginTransaction(); - germany = (Country) s.get(Country.class, country.getId()); + germany = s.get(Country.class, country.getId()); assertNotNull(germany); assertEquals("Name should not have changed", "Germany", germany.getName()); tx.commit(); @@ -70,7 +69,7 @@ public class ImmutableTest extends BaseCoreFunctionalTestCase { public void testImmutableCollection() { Country country = new Country(); country.setName("Germany"); - List states = new ArrayList(); + List states = new ArrayList<>(); State bayern = new State(); bayern.setName("Bayern"); State hessen = new State(); @@ -90,7 +89,7 @@ public class ImmutableTest extends BaseCoreFunctionalTestCase { s = openSession(); tx = s.beginTransaction(); - Country germany = (Country) s.get(Country.class, country.getId()); + Country germany = s.get(Country.class, country.getId()); assertNotNull(germany); assertEquals("Wrong number of states", 3, germany.getStates().size()); @@ -112,7 +111,7 @@ public class ImmutableTest extends BaseCoreFunctionalTestCase { s = openSession(); tx = s.beginTransaction(); - germany = (Country) s.get(Country.class, country.getId()); + germany = s.get(Country.class, country.getId()); assertNotNull(germany); assertEquals("Wrong number of states", 3, germany.getStates().size()); @@ -129,7 +128,7 @@ public class ImmutableTest extends BaseCoreFunctionalTestCase { s = openSession(); tx = s.beginTransaction(); - germany = (Country) s.get(Country.class, country.getId()); + germany = s.get(Country.class, country.getId()); assertNotNull(germany); assertEquals("Wrong number of states", 3, germany.getStates().size()); tx.commit(); diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/ProxyDeletionTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/ProxyDeletionTest.java index e1acd8322c..9508e8cd7e 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/ProxyDeletionTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/ProxyDeletionTest.java @@ -22,7 +22,6 @@ import jakarta.persistence.OneToMany; import jakarta.persistence.OneToOne; import jakarta.persistence.Table; -import org.hibernate.Hibernate; import org.hibernate.annotations.LazyGroup; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.SessionFactoryBuilder; diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/ASTParserLoadingTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/ASTParserLoadingTest.java index 2241e5b6bc..d607ee7751 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/hql/ASTParserLoadingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/hql/ASTParserLoadingTest.java @@ -108,7 +108,7 @@ import static org.junit.Assert.fail; @RequiresDialectFeature(DialectChecks.SupportsTemporaryTable.class) public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase { - private List createdAnimalIds = new ArrayList<>(); + private final List createdAnimalIds = new ArrayList<>(); @After public void cleanUpTestData() { diff --git a/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/SellCarTest.java b/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/SellCarTest.java index 4273a916cc..a99f64a3ae 100644 --- a/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/SellCarTest.java +++ b/hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/alias/SellCarTest.java @@ -34,7 +34,7 @@ public class SellCarTest extends BaseCoreFunctionalTestCase { } @Test - public void testSellCar() throws Exception { + public void testSellCar() { prepareData(); Session session = openSession(); Transaction tx = session.beginTransaction(); @@ -54,7 +54,6 @@ public class SellCarTest extends BaseCoreFunctionalTestCase { session.close(); } - @SuppressWarnings( {"unchecked"}) private Object createData() { Seller stliu = new Seller(); stliu.setId( createID( "stliu" ) ); @@ -69,7 +68,7 @@ public class SellCarTest extends BaseCoreFunctionalTestCase { private PersonID createID( String name ) { PersonID id = new PersonID(); id.setName( name ); - id.setNum( Long.valueOf( 100 ) ); + id.setNum(100L); return id; } }