get rid of the iterators in the mapping package

and clean up a lot of warnings
This commit is contained in:
Gavin King 2022-01-26 14:04:09 +01:00
parent 766d519ddd
commit 54b9677d99
74 changed files with 1036 additions and 1029 deletions

View File

@ -33,7 +33,6 @@
import org.hibernate.boot.model.naming.ImplicitEntityNameSource; import org.hibernate.boot.model.naming.ImplicitEntityNameSource;
import org.hibernate.boot.model.naming.ImplicitIdentifierColumnNameSource; import org.hibernate.boot.model.naming.ImplicitIdentifierColumnNameSource;
import org.hibernate.boot.model.naming.ImplicitIndexColumnNameSource; 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.ImplicitMapKeyColumnNameSource;
import org.hibernate.boot.model.naming.ImplicitNamingStrategy; import org.hibernate.boot.model.naming.ImplicitNamingStrategy;
import org.hibernate.boot.model.naming.ImplicitUniqueKeyNameSource; import org.hibernate.boot.model.naming.ImplicitUniqueKeyNameSource;
@ -733,29 +732,26 @@ private void bindSimpleEntityIdentifier(
( (RelationalValueSourceContainer) idSource.getIdentifierAttributeSource() ).getRelationalValueSources(), ( (RelationalValueSourceContainer) idSource.getIdentifierAttributeSource() ).getRelationalValueSources(),
idValue, idValue,
false, false,
new RelationalObjectBinder.ColumnNamingDelegate() { context -> {
@Override context.getBuildingOptions().getImplicitNamingStrategy().determineIdentifierColumnName(
public Identifier determineImplicitName(final LocalMetadataBuildingContext context) { new ImplicitIdentifierColumnNameSource() {
context.getBuildingOptions().getImplicitNamingStrategy().determineIdentifierColumnName( @Override
new ImplicitIdentifierColumnNameSource() { public EntityNaming getEntityNaming() {
@Override return hierarchySource.getRoot().getEntityNamingSource();
public EntityNaming getEntityNaming() {
return hierarchySource.getRoot().getEntityNamingSource();
}
@Override
public AttributePath getIdentifierAttributePath() {
return idSource.getIdentifierAttributeSource().getAttributePath();
}
@Override
public MetadataBuildingContext getBuildingContext() {
return context;
}
} }
);
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 @@ private void bindEntityVersion(
versionAttributeSource.getRelationalValueSources(), versionAttributeSource.getRelationalValueSources(),
versionValue, versionValue,
false, false,
new RelationalObjectBinder.ColumnNamingDelegate() { context -> implicitNamingStrategy.determineBasicColumnName( versionAttributeSource )
@Override
public Identifier determineImplicitName(LocalMetadataBuildingContext context) {
return implicitNamingStrategy.determineBasicColumnName( versionAttributeSource );
}
}
); );
Property prop = new Property(); Property prop = new Property();
@ -1072,14 +1063,9 @@ private void bindEntityDiscriminator(
hierarchySource.getDiscriminatorSource().getDiscriminatorRelationalValueSource(), hierarchySource.getDiscriminatorSource().getDiscriminatorRelationalValueSource(),
discriminatorValue, discriminatorValue,
false, false,
new RelationalObjectBinder.ColumnNamingDelegate() { context -> implicitNamingStrategy.determineDiscriminatorColumnName(
@Override hierarchySource.getDiscriminatorSource()
public Identifier determineImplicitName(final LocalMetadataBuildingContext context) { )
return implicitNamingStrategy.determineDiscriminatorColumnName(
hierarchySource.getDiscriminatorSource()
);
}
}
); );
rootEntityDescriptor.setPolymorphic( true ); rootEntityDescriptor.setPolymorphic( true );
@ -1124,7 +1110,7 @@ private void bindAllEntityAttributes(
} }
for ( AttributeSource attributeSource : entitySource.attributeSources() ) { for ( AttributeSource attributeSource : entitySource.attributeSources() ) {
if ( PluralAttributeSource.class.isInstance( attributeSource ) ) { if ( attributeSource instanceof PluralAttributeSource ) {
// plural attribute // plural attribute
final Property attribute = createPluralAttribute( final Property attribute = createPluralAttribute(
mappingDocument, mappingDocument,
@ -1135,7 +1121,7 @@ private void bindAllEntityAttributes(
} }
else { else {
// singular attribute // singular attribute
if ( SingularAttributeSourceBasic.class.isInstance( attributeSource ) ) { if ( attributeSource instanceof SingularAttributeSourceBasic ) {
final SingularAttributeSourceBasic basicAttributeSource = (SingularAttributeSourceBasic) attributeSource; final SingularAttributeSourceBasic basicAttributeSource = (SingularAttributeSourceBasic) attributeSource;
final Identifier tableName = determineTable( mappingDocument, basicAttributeSource.getName(), basicAttributeSource ); final Identifier tableName = determineTable( mappingDocument, basicAttributeSource.getName(), basicAttributeSource );
final AttributeContainer attributeContainer; final AttributeContainer attributeContainer;
@ -1170,7 +1156,7 @@ private void bindAllEntityAttributes(
basicAttributeSource.getNaturalIdMutability() basicAttributeSource.getNaturalIdMutability()
); );
} }
else if ( SingularAttributeSourceEmbedded.class.isInstance( attributeSource ) ) { else if ( attributeSource instanceof SingularAttributeSourceEmbedded ) {
final SingularAttributeSourceEmbedded embeddedAttributeSource = (SingularAttributeSourceEmbedded) attributeSource; final SingularAttributeSourceEmbedded embeddedAttributeSource = (SingularAttributeSourceEmbedded) attributeSource;
final Identifier tableName = determineTable( mappingDocument, embeddedAttributeSource ); final Identifier tableName = determineTable( mappingDocument, embeddedAttributeSource );
final AttributeContainer attributeContainer; final AttributeContainer attributeContainer;
@ -1205,7 +1191,7 @@ else if ( SingularAttributeSourceEmbedded.class.isInstance( attributeSource ) )
embeddedAttributeSource.getNaturalIdMutability() embeddedAttributeSource.getNaturalIdMutability()
); );
} }
else if ( SingularAttributeSourceManyToOne.class.isInstance( attributeSource ) ) { else if ( attributeSource instanceof SingularAttributeSourceManyToOne ) {
final SingularAttributeSourceManyToOne manyToOneAttributeSource = (SingularAttributeSourceManyToOne) attributeSource; final SingularAttributeSourceManyToOne manyToOneAttributeSource = (SingularAttributeSourceManyToOne) attributeSource;
final Identifier tableName = determineTable( mappingDocument, manyToOneAttributeSource.getName(), manyToOneAttributeSource ); final Identifier tableName = determineTable( mappingDocument, manyToOneAttributeSource.getName(), manyToOneAttributeSource );
final AttributeContainer attributeContainer; final AttributeContainer attributeContainer;
@ -1240,7 +1226,7 @@ else if ( SingularAttributeSourceManyToOne.class.isInstance( attributeSource ) )
manyToOneAttributeSource.getNaturalIdMutability() manyToOneAttributeSource.getNaturalIdMutability()
); );
} }
else if ( SingularAttributeSourceOneToOne.class.isInstance( attributeSource ) ) { else if ( attributeSource instanceof SingularAttributeSourceOneToOne ) {
final SingularAttributeSourceOneToOne oneToOneAttributeSource = (SingularAttributeSourceOneToOne) attributeSource; final SingularAttributeSourceOneToOne oneToOneAttributeSource = (SingularAttributeSourceOneToOne) attributeSource;
final Table table = entityDescriptor.getTable(); final Table table = entityDescriptor.getTable();
final Property attribute = createOneToOneAttribute( final Property attribute = createOneToOneAttribute(
@ -1258,7 +1244,7 @@ else if ( SingularAttributeSourceOneToOne.class.isInstance( attributeSource ) )
oneToOneAttributeSource.getNaturalIdMutability() oneToOneAttributeSource.getNaturalIdMutability()
); );
} }
else if ( SingularAttributeSourceAny.class.isInstance( attributeSource ) ) { else if ( attributeSource instanceof SingularAttributeSourceAny ) {
final SingularAttributeSourceAny anyAttributeSource = (SingularAttributeSourceAny) attributeSource; final SingularAttributeSourceAny anyAttributeSource = (SingularAttributeSourceAny) attributeSource;
final Identifier tableName = determineTable( final Identifier tableName = determineTable(
mappingDocument, mappingDocument,
@ -1458,7 +1444,7 @@ private void bindCollectionMetadata(MappingDocument mappingDocument, PluralAttri
// bind the collection type info // bind the collection type info
String typeName = source.getTypeInformation().getName(); String typeName = source.getTypeInformation().getName();
Map typeParameters = new HashMap(); Map<Object,Object> typeParameters = new HashMap<>();
if ( typeName != null ) { if ( typeName != null ) {
// see if there is a corresponding type-def // see if there is a corresponding type-def
final TypeDefinition typeDef = mappingDocument.getMetadataCollector().getTypeDefinition( typeName ); final TypeDefinition typeDef = mappingDocument.getMetadataCollector().getTypeDefinition( typeName );
@ -1652,7 +1638,7 @@ private Identifier determineTable(
Identifier tableName = null; Identifier tableName = null;
for ( AttributeSource attributeSource : embeddedAttributeSource.getEmbeddableSource().attributeSources() ) { for ( AttributeSource attributeSource : embeddedAttributeSource.getEmbeddableSource().attributeSources() ) {
final Identifier determinedName; final Identifier determinedName;
if ( RelationalValueSourceContainer.class.isInstance( attributeSource ) ) { if ( attributeSource instanceof RelationalValueSourceContainer ) {
determinedName = determineTable( determinedName = determineTable(
mappingDocument, mappingDocument,
embeddedAttributeSource.getAttributeRole().getFullPath(), embeddedAttributeSource.getAttributeRole().getFullPath(),
@ -1660,10 +1646,10 @@ private Identifier determineTable(
); );
} }
else if ( SingularAttributeSourceEmbedded.class.isInstance( attributeSource ) ) { else if ( attributeSource instanceof SingularAttributeSourceEmbedded ) {
determinedName = determineTable( mappingDocument, (SingularAttributeSourceEmbedded) attributeSource ); determinedName = determineTable( mappingDocument, (SingularAttributeSourceEmbedded) attributeSource );
} }
else if ( SingularAttributeSourceAny.class.isInstance( attributeSource ) ) { else if ( attributeSource instanceof SingularAttributeSourceAny ) {
determinedName = determineTable( determinedName = determineTable(
mappingDocument, mappingDocument,
attributeSource.getAttributeRole().getFullPath(), attributeSource.getAttributeRole().getFullPath(),
@ -1901,12 +1887,7 @@ private Property createBasicAttribute(
attributeSource.getRelationalValueSources(), attributeSource.getRelationalValueSources(),
value, value,
attributeSource.areValuesNullableByDefault(), attributeSource.areValuesNullableByDefault(),
new RelationalObjectBinder.ColumnNamingDelegate() { context -> implicitNamingStrategy.determineBasicColumnName( attributeSource )
@Override
public Identifier determineImplicitName(LocalMetadataBuildingContext context) {
return implicitNamingStrategy.determineBasicColumnName( attributeSource );
}
}
); );
@ -2181,7 +2162,7 @@ private Property createManyToOneAttribute(
referencedEntityName = manyToOneSource.getReferencedEntityName(); referencedEntityName = manyToOneSource.getReferencedEntityName();
} }
else { else {
Class reflectedPropertyClass = Helper.reflectedPropertyClass( sourceDocument, containingClassName, attributeName ); Class<?> reflectedPropertyClass = Helper.reflectedPropertyClass( sourceDocument, containingClassName, attributeName );
if ( reflectedPropertyClass != null ) { if ( reflectedPropertyClass != null ) {
referencedEntityName = reflectedPropertyClass.getName(); referencedEntityName = reflectedPropertyClass.getName();
} }
@ -2615,9 +2596,9 @@ private void bindProperty(
.append( "Mapped property: " ) .append( "Mapped property: " )
.append( propertySource.getName() ) .append( propertySource.getName() )
.append( " -> [" ); .append( " -> [" );
final Iterator itr = property.getValue().getColumnIterator(); final Iterator<Selectable> itr = property.getValue().getColumnIterator();
while ( itr.hasNext() ) { while ( itr.hasNext() ) {
message.append( ( (Selectable) itr.next() ).getText() ); message.append( itr.next().getText() );
if ( itr.hasNext() ) { if ( itr.hasNext() ) {
message.append( ", " ); message.append( ", " );
} }
@ -2706,7 +2687,7 @@ else if ( isVirtual ) {
} }
else if ( componentBinding.getOwner().hasPojoRepresentation() ) { else if ( componentBinding.getOwner().hasPojoRepresentation() ) {
log.tracef( "Attempting to determine component class by reflection %s", role ); log.tracef( "Attempting to determine component class by reflection %s", role );
final Class reflectedComponentClass; final Class<?> reflectedComponentClass;
if ( StringHelper.isNotEmpty( containingClassName ) && StringHelper.isNotEmpty( propertyName ) ) { if ( StringHelper.isNotEmpty( containingClassName ) && StringHelper.isNotEmpty( propertyName ) ) {
reflectedComponentClass = Helper.reflectedPropertyClass( reflectedComponentClass = Helper.reflectedPropertyClass(
sourceDocument, sourceDocument,
@ -2747,40 +2728,25 @@ else if ( componentBinding.getOwner().hasPojoRepresentation() ) {
if ( embeddableSource.isUnique() ) { if ( embeddableSource.isUnique() ) {
final ArrayList<Column> cols = new ArrayList<>(); final ArrayList<Column> cols = new ArrayList<>();
final Iterator itr = componentBinding.getColumnIterator(); for ( Selectable selectable: componentBinding.getSelectables() ) {
while ( itr.hasNext() ) { if ( selectable instanceof Column) {
final Object selectable = itr.next(); cols.add( (Column) selectable );
// skip formulas. ugh, yes terrible naming of these methods :(
if ( !Column.class.isInstance( selectable ) ) {
continue;
} }
cols.add( (Column) selectable );
} }
// todo : we may need to delay this // todo : we may need to delay this
componentBinding.getOwner().getTable().createUniqueKey( cols ); 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( private void bindAllCompositeAttributes(
MappingDocument sourceDocument, MappingDocument sourceDocument,
EmbeddableSource embeddableSource, EmbeddableSource embeddableSource,
Component component) { Component component) {
for ( AttributeSource attributeSource : embeddableSource.attributeSources() ) { for ( AttributeSource attributeSource : embeddableSource.attributeSources() ) {
Property attribute = null; Property attribute;
if ( SingularAttributeSourceBasic.class.isInstance( attributeSource ) ) { if ( attributeSource instanceof SingularAttributeSourceBasic ) {
attribute = createBasicAttribute( attribute = createBasicAttribute(
sourceDocument, sourceDocument,
(SingularAttributeSourceBasic) attributeSource, (SingularAttributeSourceBasic) attributeSource,
@ -2788,7 +2754,7 @@ private void bindAllCompositeAttributes(
component.getComponentClassName() component.getComponentClassName()
); );
} }
else if ( SingularAttributeSourceEmbedded.class.isInstance( attributeSource ) ) { else if ( attributeSource instanceof SingularAttributeSourceEmbedded ) {
attribute = createEmbeddedAttribute( attribute = createEmbeddedAttribute(
sourceDocument, sourceDocument,
(SingularAttributeSourceEmbedded) attributeSource, (SingularAttributeSourceEmbedded) attributeSource,
@ -2796,7 +2762,7 @@ else if ( SingularAttributeSourceEmbedded.class.isInstance( attributeSource ) )
component.getComponentClassName() component.getComponentClassName()
); );
} }
else if ( SingularAttributeSourceManyToOne.class.isInstance( attributeSource ) ) { else if ( attributeSource instanceof SingularAttributeSourceManyToOne ) {
attribute = createManyToOneAttribute( attribute = createManyToOneAttribute(
sourceDocument, sourceDocument,
(SingularAttributeSourceManyToOne) attributeSource, (SingularAttributeSourceManyToOne) attributeSource,
@ -2804,7 +2770,7 @@ else if ( SingularAttributeSourceManyToOne.class.isInstance( attributeSource ) )
component.getComponentClassName() component.getComponentClassName()
); );
} }
else if ( SingularAttributeSourceOneToOne.class.isInstance( attributeSource ) ) { else if ( attributeSource instanceof SingularAttributeSourceOneToOne ) {
attribute = createOneToOneAttribute( attribute = createOneToOneAttribute(
sourceDocument, sourceDocument,
(SingularAttributeSourceOneToOne) attributeSource, (SingularAttributeSourceOneToOne) attributeSource,
@ -2812,7 +2778,7 @@ else if ( SingularAttributeSourceOneToOne.class.isInstance( attributeSource ) )
component.getComponentClassName() component.getComponentClassName()
); );
} }
else if ( SingularAttributeSourceAny.class.isInstance( attributeSource ) ) { else if ( attributeSource instanceof SingularAttributeSourceAny ) {
attribute = createAnyAssociationAttribute( attribute = createAnyAssociationAttribute(
sourceDocument, sourceDocument,
(SingularAttributeSourceAny) attributeSource, (SingularAttributeSourceAny) attributeSource,
@ -2820,7 +2786,7 @@ else if ( SingularAttributeSourceAny.class.isInstance( attributeSource ) ) {
component.getComponentClassName() component.getComponentClassName()
); );
} }
else if ( PluralAttributeSource.class.isInstance( attributeSource ) ) { else if ( attributeSource instanceof PluralAttributeSource ) {
attribute = createPluralAttribute( attribute = createPluralAttribute(
sourceDocument, sourceDocument,
(PluralAttributeSource) attributeSource, (PluralAttributeSource) attributeSource,
@ -2917,8 +2883,8 @@ private Table bindEntityTableSpecification(
determineSchemaName( tableSpecSource ) determineSchemaName( tableSpecSource )
); );
final boolean isTable = TableSource.class.isInstance( tableSpecSource ); final boolean isTable = tableSpecSource instanceof TableSource;
final boolean isAbstract = entityDescriptor.isAbstract() == null ? false : entityDescriptor.isAbstract(); final boolean isAbstract = entityDescriptor.isAbstract() != null && entityDescriptor.isAbstract();
final String subselect; final String subselect;
final Identifier logicalTableName; final Identifier logicalTableName;
final Table table; final Table table;
@ -2991,7 +2957,6 @@ public MetadataBuildingContext getBuildingContext() {
EntityTableXref superEntityTableXref = null; EntityTableXref superEntityTableXref = null;
if ( entitySource.getSuperType() != null ) { if ( entitySource.getSuperType() != null ) {
//noinspection SuspiciousMethodCalls
final String superEntityName = ( (EntitySource) entitySource.getSuperType() ).getEntityNamingSource() final String superEntityName = ( (EntitySource) entitySource.getSuperType() ).getEntityNamingSource()
.getEntityName(); .getEntityName();
superEntityTableXref = mappingDocument.getMetadataCollector().getEntityTableXref( superEntityName ); superEntityTableXref = mappingDocument.getMetadataCollector().getEntityTableXref( superEntityName );
@ -3406,27 +3371,22 @@ protected void bindCollectionKey() {
); );
key.setForeignKeyName( keySource.getExplicitForeignKeyName() ); key.setForeignKeyName( keySource.getExplicitForeignKeyName() );
key.setCascadeDeleteEnabled( getPluralAttributeSource().getKeySource().isCascadeDeleteEnabled() ); key.setCascadeDeleteEnabled( getPluralAttributeSource().getKeySource().isCascadeDeleteEnabled() );
//
final ImplicitJoinColumnNameSource.Nature implicitNamingNature; // final ImplicitJoinColumnNameSource.Nature implicitNamingNature;
if ( getPluralAttributeSource().getElementSource() instanceof PluralAttributeElementSourceManyToMany // if ( getPluralAttributeSource().getElementSource() instanceof PluralAttributeElementSourceManyToMany
|| getPluralAttributeSource().getElementSource() instanceof PluralAttributeElementSourceOneToMany ) { // || getPluralAttributeSource().getElementSource() instanceof PluralAttributeElementSourceOneToMany ) {
implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ENTITY_COLLECTION; // implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ENTITY_COLLECTION;
} // }
else { // else {
implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ELEMENT_COLLECTION; // implicitNamingNature = ImplicitJoinColumnNameSource.Nature.ELEMENT_COLLECTION;
} // }
relationalObjectBinder.bindColumnsAndFormulas( relationalObjectBinder.bindColumnsAndFormulas(
mappingDocument, mappingDocument,
getPluralAttributeSource().getKeySource().getRelationalValueSources(), getPluralAttributeSource().getKeySource().getRelationalValueSources(),
key, key,
getPluralAttributeSource().getKeySource().areValuesNullableByDefault(), getPluralAttributeSource().getKeySource().areValuesNullableByDefault(),
new RelationalObjectBinder.ColumnNamingDelegate() { context -> context.getMetadataCollector().getDatabase().toIdentifier( Collection.DEFAULT_KEY_COLUMN_NAME )
@Override
public Identifier determineImplicitName(final LocalMetadataBuildingContext context) {
return context.getMetadataCollector().getDatabase().toIdentifier( Collection.DEFAULT_KEY_COLUMN_NAME );
}
}
); );
key.sortProperties(); key.sortProperties();
@ -3457,12 +3417,7 @@ protected void bindCollectionIdentifier() {
idSource.getColumnSource(), idSource.getColumnSource(),
idBinding, idBinding,
false, false,
new RelationalObjectBinder.ColumnNamingDelegate() { context -> database.toIdentifier( IdentifierCollection.DEFAULT_IDENTIFIER_COLUMN_NAME )
@Override
public Identifier determineImplicitName(LocalMetadataBuildingContext context) {
return database.toIdentifier( IdentifierCollection.DEFAULT_IDENTIFIER_COLUMN_NAME );
}
}
); );
idBagBinding.setIdentifier( idBinding ); idBagBinding.setIdentifier( idBinding );
@ -3506,12 +3461,7 @@ protected void bindCollectionElement() {
elementSource.getRelationalValueSources(), elementSource.getRelationalValueSources(),
elementBinding, elementBinding,
elementSource.areValuesNullableByDefault(), elementSource.areValuesNullableByDefault(),
new RelationalObjectBinder.ColumnNamingDelegate() { context -> context.getMetadataCollector().getDatabase().toIdentifier( Collection.DEFAULT_ELEMENT_COLUMN_NAME )
@Override
public Identifier determineImplicitName(LocalMetadataBuildingContext context) {
return context.getMetadataCollector().getDatabase().toIdentifier( Collection.DEFAULT_ELEMENT_COLUMN_NAME );
}
}
); );
getCollectionBinding().setElement( elementBinding ); getCollectionBinding().setElement( elementBinding );
@ -3593,14 +3543,8 @@ else if ( getPluralAttributeSource().getElementSource() instanceof PluralAttribu
elementSource.getRelationalValueSources(), elementSource.getRelationalValueSources(),
elementBinding, elementBinding,
false, false,
new RelationalObjectBinder.ColumnNamingDelegate() { context -> context.getMetadataCollector().getDatabase()
@Override .toIdentifier( Collection.DEFAULT_ELEMENT_COLUMN_NAME )
public Identifier determineImplicitName(final LocalMetadataBuildingContext context) {
return context.getMetadataCollector()
.getDatabase()
.toIdentifier( Collection.DEFAULT_ELEMENT_COLUMN_NAME );
}
}
); );
elementBinding.setLazy( elementBinding.setLazy(
@ -3829,10 +3773,10 @@ protected void createBackReferences() {
super.createBackReferences(); super.createBackReferences();
boolean indexIsFormula = false; boolean indexIsFormula = false;
Iterator itr = getCollectionBinding().getIndex().getColumnIterator(); for ( Selectable selectable: getCollectionBinding().getIndex().getSelectables() ) {
while ( itr.hasNext() ) { if ( selectable.isFormula() ) {
if ( ( (Selectable) itr.next() ).isFormula() ) {
indexIsFormula = true; indexIsFormula = true;
break;
} }
} }
@ -3993,24 +3937,19 @@ public void bindListOrArrayIndex(
indexSource.getRelationalValueSources(), indexSource.getRelationalValueSources(),
indexBinding, indexBinding,
attributeSource.getElementSource() instanceof PluralAttributeElementSourceOneToMany, attributeSource.getElementSource() instanceof PluralAttributeElementSourceOneToMany,
new RelationalObjectBinder.ColumnNamingDelegate() { context -> context.getBuildingOptions().getImplicitNamingStrategy().determineListIndexColumnName(
@Override new ImplicitIndexColumnNameSource() {
public Identifier determineImplicitName(final LocalMetadataBuildingContext context) { @Override
return context.getBuildingOptions().getImplicitNamingStrategy().determineListIndexColumnName( public AttributePath getPluralAttributePath() {
new ImplicitIndexColumnNameSource() { return attributeSource.getAttributePath();
@Override }
public AttributePath getPluralAttributePath() {
return attributeSource.getAttributePath();
}
@Override @Override
public MetadataBuildingContext getBuildingContext() { public MetadataBuildingContext getBuildingContext() {
return context; return context;
} }
} }
); )
}
}
); );
collectionBinding.setIndex( indexBinding ); collectionBinding.setIndex( indexBinding );
@ -4046,12 +3985,7 @@ private void bindMapKey(
mapKeySource.getRelationalValueSources(), mapKeySource.getRelationalValueSources(),
value, value,
true, true,
new RelationalObjectBinder.ColumnNamingDelegate() { context -> database.toIdentifier( IndexedCollection.DEFAULT_INDEX_COLUMN_NAME )
@Override
public Identifier determineImplicitName(LocalMetadataBuildingContext context) {
return database.toIdentifier( IndexedCollection.DEFAULT_INDEX_COLUMN_NAME );
}
}
); );
collectionBinding.setIndex( value ); collectionBinding.setIndex( value );
@ -4089,24 +4023,19 @@ else if ( pluralAttributeSource.getIndexSource() instanceof PluralAttributeMapKe
mapKeySource.getRelationalValueSources(), mapKeySource.getRelationalValueSources(),
mapKeyBinding, mapKeyBinding,
true, true,
new RelationalObjectBinder.ColumnNamingDelegate() { context -> implicitNamingStrategy.determineMapKeyColumnName(
@Override new ImplicitMapKeyColumnNameSource() {
public Identifier determineImplicitName(final LocalMetadataBuildingContext context) { @Override
return implicitNamingStrategy.determineMapKeyColumnName( public AttributePath getPluralAttributePath() {
new ImplicitMapKeyColumnNameSource() { return pluralAttributeSource.getAttributePath();
@Override }
public AttributePath getPluralAttributePath() {
return pluralAttributeSource.getAttributePath();
}
@Override @Override
public MetadataBuildingContext getBuildingContext() { public MetadataBuildingContext getBuildingContext() {
return context; return context;
} }
} }
); )
}
}
); );
collectionBinding.setIndex( mapKeyBinding ); collectionBinding.setIndex( mapKeyBinding );
} }
@ -4186,11 +4115,8 @@ public void doSecondPass(Map persistentClasses) throws org.hibernate.MappingExce
manyToOneSource.getRelationalValueSources(), manyToOneSource.getRelationalValueSources(),
manyToOneBinding, manyToOneBinding,
manyToOneSource.areValuesNullableByDefault(), manyToOneSource.areValuesNullableByDefault(),
new RelationalObjectBinder.ColumnNamingDelegate() { context -> {
@Override throw new AssertionFailure( "Argh!!!" );
public Identifier determineImplicitName(LocalMetadataBuildingContext context) {
throw new AssertionFailure( "Argh!!!" );
}
} }
); );
} }
@ -4214,29 +4140,24 @@ public Identifier determineImplicitName(LocalMetadataBuildingContext context) {
manyToOneSource.getRelationalValueSources(), manyToOneSource.getRelationalValueSources(),
manyToOneBinding, manyToOneBinding,
manyToOneSource.areValuesNullableByDefault(), manyToOneSource.areValuesNullableByDefault(),
new RelationalObjectBinder.ColumnNamingDelegate() { context -> implicitNamingStrategy.determineBasicColumnName(
@Override new ImplicitBasicColumnNameSource() {
public Identifier determineImplicitName(final LocalMetadataBuildingContext context) { @Override
return implicitNamingStrategy.determineBasicColumnName( public AttributePath getAttributePath() {
new ImplicitBasicColumnNameSource() { return manyToOneSource.getAttributePath();
@Override }
public AttributePath getAttributePath() {
return manyToOneSource.getAttributePath();
}
@Override @Override
public boolean isCollectionElement() { public boolean isCollectionElement() {
return false; return false;
} }
@Override @Override
public MetadataBuildingContext getBuildingContext() { public MetadataBuildingContext getBuildingContext() {
return context; return context;
} }
} }
); )
}
}
); );
} }
} }
@ -4327,10 +4248,8 @@ public void process() {
final UniqueKey uk = new UniqueKey(); final UniqueKey uk = new UniqueKey();
uk.setTable( entityBinding.getTable() ); uk.setTable( entityBinding.getTable() );
for ( Property attributeBinding : attributeBindings ) { for ( Property attributeBinding : attributeBindings ) {
final Iterator itr = attributeBinding.getColumnIterator(); for ( Selectable selectable : attributeBinding.getSelectables() ) {
while ( itr.hasNext() ) { if ( selectable instanceof Column ) {
final Object selectable = itr.next();
if ( Column.class.isInstance( selectable ) ) {
final Column column = (Column) selectable; final Column column = (Column) selectable;
uk.addColumn( column ); uk.addColumn( column );
columnNames.add( columnNames.add(
@ -4338,7 +4257,7 @@ public void process() {
); );
} }
} }
uk.addColumns( attributeBinding.getColumnIterator() ); uk.addColumns( attributeBinding.getValue() );
} }
final Identifier ukName = mappingDocument.getBuildingOptions().getImplicitNamingStrategy().determineUniqueKeyName( final Identifier ukName = mappingDocument.getBuildingOptions().getImplicitNamingStrategy().determineUniqueKeyName(

View File

@ -7,7 +7,6 @@
package org.hibernate.cfg; package org.hibernate.cfg;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -345,7 +344,7 @@ public static AnnotatedJoinColumn buildJoinColumn(
final ObjectNameNormalizer normalizer = context.getObjectNameNormalizer(); final ObjectNameNormalizer normalizer = context.getObjectNameNormalizer();
Column col = (Column) identifier.getColumnIterator().next(); Column col = identifier.getColumns().get(0);
String defaultName = context.getMetadataCollector().getLogicalColumnName( String defaultName = context.getMetadataCollector().getLogicalColumnName(
identifier.getTable(), identifier.getTable(),
col.getQuotedName() col.getQuotedName()
@ -449,17 +448,14 @@ public static void checkIfJoinColumn(Object columns, PropertyHolder holder, Prop
} }
} }
public void copyReferencedStructureAndCreateDefaultJoinColumns( public void copyReferencedStructureAndCreateDefaultJoinColumns(
PersistentClass referencedEntity, PersistentClass referencedEntity,
Iterator columnIterator, SimpleValue referencedValue,
SimpleValue value) { SimpleValue value) {
if ( !isNameDeferred() ) { if ( !isNameDeferred() ) {
throw new AssertionFailure( "Building implicit column but the column is not implicit" ); throw new AssertionFailure( "Building implicit column but the column is not implicit" );
} }
while ( columnIterator.hasNext() ) { for ( Column synthCol: referencedValue.getColumns() ) {
Column synthCol = (Column) columnIterator.next();
this.linkValueUsingDefaultColumnNaming( synthCol, referencedEntity, value ); this.linkValueUsingDefaultColumnNaming( synthCol, referencedEntity, value );
} }
//reset for the future //reset for the future
@ -586,8 +582,7 @@ public Identifier getReferencedColumnName() {
.getEntityBinding( mappedByEntityName ); .getEntityBinding( mappedByEntityName );
final Property mappedByProperty = mappedByEntityBinding.getProperty( mappedByPropertyName ); final Property mappedByProperty = mappedByEntityBinding.getProperty( mappedByPropertyName );
final SimpleValue value = (SimpleValue) mappedByProperty.getValue(); final SimpleValue value = (SimpleValue) mappedByProperty.getValue();
final Iterator<Selectable> selectableValues = value.getColumnIterator(); if ( value.getSelectables().isEmpty() ) {
if ( !selectableValues.hasNext() ) {
throw new AnnotationException( throw new AnnotationException(
String.format( String.format(
Locale.ENGLISH, Locale.ENGLISH,
@ -597,8 +592,8 @@ public Identifier getReferencedColumnName() {
) )
); );
} }
final Selectable selectable = selectableValues.next(); final Selectable selectable = value.getSelectables().get(0);
if ( !Column.class.isInstance( selectable ) ) { if ( !(selectable instanceof Column) ) {
throw new AnnotationException( throw new AnnotationException(
String.format( String.format(
Locale.ENGLISH, Locale.ENGLISH,
@ -608,7 +603,7 @@ public Identifier getReferencedColumnName() {
) )
); );
} }
if ( selectableValues.hasNext() ) { if ( value.getSelectables().size()>1 ) {
throw new AnnotationException( throw new AnnotationException(
String.format( String.format(
Locale.ENGLISH, Locale.ENGLISH,
@ -817,9 +812,8 @@ public static int checkReferencedColumnsType(
MetadataBuildingContext context) { MetadataBuildingContext context) {
//convenient container to find whether a column is an id one or not //convenient container to find whether a column is an id one or not
Set<Column> idColumns = new HashSet<>(); Set<Column> idColumns = new HashSet<>();
Iterator idColumnsIt = referencedEntity.getKey().getColumnIterator(); for ( Selectable selectable : referencedEntity.getKey().getSelectables() ) {
while ( idColumnsIt.hasNext() ) { idColumns.add( (Column) selectable );
idColumns.add( (Column) idColumnsIt.next() );
} }
boolean isFkReferencedColumnName = false; boolean isFkReferencedColumnName = false;

View File

@ -133,6 +133,7 @@
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property; import org.hibernate.mapping.Property;
import org.hibernate.mapping.RootClass; import org.hibernate.mapping.RootClass;
import org.hibernate.mapping.Selectable;
import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.SingleTableSubclass; import org.hibernate.mapping.SingleTableSubclass;
import org.hibernate.mapping.Subclass; import org.hibernate.mapping.Subclass;
@ -1284,9 +1285,8 @@ private static boolean mapAsIdClass(
persistentClass.addProperty( property ); persistentClass.addProperty( property );
entityBinder.setIgnoreIdAnnotations( true ); entityBinder.setIgnoreIdAnnotations( true );
Iterator properties = mapper.getPropertyIterator(); for ( Property prop : mapper.getProperties() ) {
while ( properties.hasNext() ) { idPropertiesIfIdClass.add( prop.getName() );
idPropertiesIfIdClass.add( ( ( Property ) properties.next() ).getName() );
} }
return true; return true;
} }
@ -3442,15 +3442,12 @@ private static void bindOneToOne(
mapToPK = false; mapToPK = false;
} }
else { else {
Iterator idColumns = identifier.getColumnIterator();
List<String> idColumnNames = new ArrayList<>(); List<String> idColumnNames = new ArrayList<>();
org.hibernate.mapping.Column currentColumn;
if ( identifier.getColumnSpan() != joinColumns.length ) { if ( identifier.getColumnSpan() != joinColumns.length ) {
mapToPK = false; mapToPK = false;
} }
else { else {
while ( idColumns.hasNext() ) { for ( org.hibernate.mapping.Column currentColumn : identifier.getColumns() ) {
currentColumn = ( org.hibernate.mapping.Column ) idColumns.next();
idColumnNames.add( currentColumn.getName() ); idColumnNames.add( currentColumn.getName() );
} }
for ( AnnotatedJoinColumn col : joinColumns ) { for ( AnnotatedJoinColumn col : joinColumns ) {

View File

@ -34,11 +34,9 @@
import org.hibernate.cfg.annotations.BasicValueBinder; import org.hibernate.cfg.annotations.BasicValueBinder;
import org.hibernate.cfg.annotations.EntityBinder; import org.hibernate.cfg.annotations.EntityBinder;
import org.hibernate.cfg.annotations.Nullability; import org.hibernate.cfg.annotations.Nullability;
import org.hibernate.cfg.annotations.TableBinder;
import org.hibernate.id.IdentifierGenerator; import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.PersistentIdentifierGenerator; import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.StringHelper;
import org.hibernate.mapping.Any; import org.hibernate.mapping.Any;
import org.hibernate.mapping.BasicValue; import org.hibernate.mapping.BasicValue;
@ -49,6 +47,7 @@
import org.hibernate.mapping.MappedSuperclass; import org.hibernate.mapping.MappedSuperclass;
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property; import org.hibernate.mapping.Property;
import org.hibernate.mapping.Selectable;
import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.SyntheticProperty; import org.hibernate.mapping.SyntheticProperty;
import org.hibernate.mapping.Table; import org.hibernate.mapping.Table;
@ -72,7 +71,6 @@ public class BinderHelper {
public static final String ANNOTATION_STRING_DEFAULT = ""; 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 static final Logger log = CoreLogging.logger( BinderHelper.class );
private BinderHelper() { private BinderHelper() {
@ -126,7 +124,7 @@ public static void createSyntheticPropertyReference(
columns[0].getPropertyHolder().getPersistentClass() : columns[0].getPropertyHolder().getPersistentClass() :
null; null;
if ( AnnotatedJoinColumn.NON_PK_REFERENCE == fkEnum ) { if ( AnnotatedJoinColumn.NON_PK_REFERENCE == fkEnum ) {
/** /*
* Create a synthetic property to refer to including an * Create a synthetic property to refer to including an
* embedded component value containing all the properties * embedded component value containing all the properties
* mapped to the referenced columns * mapped to the referenced columns
@ -166,7 +164,7 @@ public static void createSyntheticPropertyReference(
synthProp.setPropertyAccessorName( "embedded" ); synthProp.setPropertyAccessorName( "embedded" );
ownerEntity.addProperty( synthProp ); ownerEntity.addProperty( synthProp );
//make it unique //make it unique
TableBinder.createUniqueConstraint( embeddedComp ); embeddedComp.createUniqueKey();
} }
else { else {
//TODO use a ToOne type doing a second select //TODO use a ToOne type doing a second select
@ -201,12 +199,12 @@ public static void createSyntheticPropertyReference(
throw new AnnotationException( columnsList.toString() ); throw new AnnotationException( columnsList.toString() );
} }
/** /*
* creating the property ref to the new synthetic property * creating the property ref to the new synthetic property
*/ */
if ( value instanceof ToOne ) { if ( value instanceof ToOne ) {
( (ToOne) value ).setReferencedPropertyName( syntheticPropertyName ); ( (ToOne) value ).setReferencedPropertyName( syntheticPropertyName );
( (ToOne) value ).setReferenceToPrimaryKey( syntheticPropertyName == null ); ( (ToOne) value ).setReferenceToPrimaryKey( false );
context.getMetadataCollector().addUniquePropertyReference( context.getMetadataCollector().addUniquePropertyReference(
ownerEntity.getEntityName(), ownerEntity.getEntityName(),
syntheticPropertyName syntheticPropertyName
@ -267,11 +265,11 @@ else if ( columnOwner instanceof Join ) {
columnsToProperty.put( column, new HashSet<>() ); columnsToProperty.put( column, new HashSet<>() );
} }
boolean isPersistentClass = columnOwner instanceof PersistentClass; boolean isPersistentClass = columnOwner instanceof PersistentClass;
Iterator it = isPersistentClass ? List<Property> properties = isPersistentClass ?
( (PersistentClass) columnOwner ).getPropertyIterator() : ( (PersistentClass) columnOwner ).getProperties() :
( (Join) columnOwner ).getPropertyIterator(); ( (Join) columnOwner ).getProperties();
while ( it.hasNext() ) { for (Property property : properties) {
matchColumnsByProperty( (Property) it.next(), columnsToProperty ); matchColumnsByProperty( property, columnsToProperty );
} }
if ( isPersistentClass ) { if ( isPersistentClass ) {
matchColumnsByProperty( ( (PersistentClass) columnOwner ).getIdentifierProperty(), columnsToProperty ); matchColumnsByProperty( ( (PersistentClass) columnOwner ).getIdentifierProperty(), columnsToProperty );
@ -314,13 +312,12 @@ private static void matchColumnsByProperty(Property property, Map<Column, Set<Pr
// } // }
// } // }
else { else {
Iterator columnIt = property.getColumnIterator(); for (Selectable selectable : property.getSelectables()) {
while ( columnIt.hasNext() ) { //can be a Formula, so we don't cast
//can be a Formula so we don't cast
Object column = columnIt.next();
//noinspection SuspiciousMethodCalls //noinspection SuspiciousMethodCalls
if ( columnsToProperty.containsKey( column ) ) { if ( columnsToProperty.containsKey( selectable ) ) {
columnsToProperty.get( column ).add( property ); //noinspection SuspiciousMethodCalls
columnsToProperty.get( selectable ).add( property );
} }
} }
} }
@ -526,7 +523,7 @@ public static void makeIdGenerator(
if ( id.getColumnSpan() == 1 ) { if ( id.getColumnSpan() == 1 ) {
params.setProperty( params.setProperty(
PersistentIdentifierGenerator.PK, 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 // YUCK! but cannot think of a clean way to do this given the string-config based scheme
@ -774,7 +771,6 @@ public String getGeneratedValueGeneratorName() {
); );
} }
@SuppressWarnings("ConstantConditions")
private static GenerationType interpretGenerationType(GeneratedValue generatedValueAnn) { private static GenerationType interpretGenerationType(GeneratedValue generatedValueAnn) {
if ( generatedValueAnn.strategy() == null ) { if ( generatedValueAnn.strategy() == null ) {
return GenerationType.AUTO; return GenerationType.AUTO;
@ -854,7 +850,7 @@ public static Any buildAnyValue(
); );
value.setDiscriminatorValueMappings( discriminatorValueMappings ); 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; assert keyColumns.length == 1;
keyColumns[0].setTable( value.getTable() ); keyColumns[0].setTable( value.getTable() );
keyValueBinder.setColumns( keyColumns ); keyValueBinder.setColumns( keyColumns );
@ -887,8 +883,8 @@ private static void processAnyDiscriminatorValues(
if ( valuesAnn != null ) { if ( valuesAnn != null ) {
final AnyDiscriminatorValue[] valueAnns = valuesAnn.value(); final AnyDiscriminatorValue[] valueAnns = valuesAnn.value();
if ( valueAnns != null && valueAnns.length > 0 ) { if ( valueAnns != null && valueAnns.length > 0 ) {
for ( int i = 0; i < valueAnns.length; i++ ) { for ( AnyDiscriminatorValue ann : valueAnns ) {
consumer.accept( valueAnns[i] ); consumer.accept(ann);
} }
} }
} }

View File

@ -6,7 +6,6 @@
*/ */
package org.hibernate.cfg; package org.hibernate.cfg;
import java.util.Iterator;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
@ -64,7 +63,6 @@ public boolean isInPrimaryKey() {
} }
@Override @Override
@SuppressWarnings({ "unchecked" })
public void doSecondPass(Map persistentClasses) throws MappingException { public void doSecondPass(Map persistentClasses) throws MappingException {
PersistentClass referencedPersistentClass = (PersistentClass) persistentClasses.get( referencedEntityName ); PersistentClass referencedPersistentClass = (PersistentClass) persistentClasses.get( referencedEntityName );
// TODO better error names // TODO better error names
@ -78,8 +76,6 @@ public void doSecondPass(Map persistentClasses) throws MappingException {
); );
} }
Component referencedComponent = (Component) referencedPersistentClass.getIdentifier(); Component referencedComponent = (Component) referencedPersistentClass.getIdentifier();
Iterator<Property> properties = referencedComponent.getPropertyIterator();
//prepare column name structure //prepare column name structure
boolean isExplicitReference = true; boolean isExplicitReference = true;
@ -101,8 +97,7 @@ public void doSecondPass(Map persistentClasses) throws MappingException {
} }
MutableInteger index = new MutableInteger(); MutableInteger index = new MutableInteger();
while ( properties.hasNext() ) { for ( Property referencedProperty : referencedComponent.getProperties() ) {
Property referencedProperty = properties.next();
if ( referencedProperty.isComposite() ) { if ( referencedProperty.isComposite() ) {
Property property = createComponentProperty( referencedPersistentClass, isExplicitReference, columnByReferencedName, index, referencedProperty ); Property property = createComponentProperty( referencedPersistentClass, isExplicitReference, columnByReferencedName, index, referencedProperty );
component.addProperty( property ); component.addProperty( property );
@ -135,10 +130,7 @@ private Property createComponentProperty(
value.setComponentClassName( referencedValue.getComponentClassName() ); value.setComponentClassName( referencedValue.getComponentClassName() );
Iterator<Property> propertyIterator = referencedValue.getPropertyIterator(); for ( Property referencedComponentProperty : referencedValue.getProperties() ) {
while(propertyIterator.hasNext()) {
Property referencedComponentProperty = propertyIterator.next();
if ( referencedComponentProperty.isComposite() ) { if ( referencedComponentProperty.isComposite() ) {
Property componentProperty = createComponentProperty( referencedValue.getOwner(), isExplicitReference, columnByReferencedName, index, referencedComponentProperty ); Property componentProperty = createComponentProperty( referencedValue.getOwner(), isExplicitReference, columnByReferencedName, index, referencedComponentProperty );
value.addProperty( componentProperty ); value.addProperty( componentProperty );
@ -169,19 +161,18 @@ private Property createSimpleProperty(
property.setValue( value ); property.setValue( value );
final SimpleValue referencedValue = (SimpleValue) referencedProperty.getValue(); final SimpleValue referencedValue = (SimpleValue) referencedProperty.getValue();
value.copyTypeFrom( referencedValue ); value.copyTypeFrom( referencedValue );
final Iterator<Selectable> columns = referencedValue.getColumnIterator();
if ( joinColumns[0].isNameDeferred() ) { if ( joinColumns[0].isNameDeferred() ) {
joinColumns[0].copyReferencedStructureAndCreateDefaultJoinColumns( joinColumns[0].copyReferencedStructureAndCreateDefaultJoinColumns(
referencedPersistentClass, referencedPersistentClass,
columns, referencedValue,
value); value
);
} }
else { else {
//FIXME take care of Formula //FIXME take care of Formula
while ( columns.hasNext() ) { for ( Selectable selectable : referencedValue.getSelectables() ) {
final Selectable selectable = columns.next(); if ( !(selectable instanceof Column) ) {
if ( ! Column.class.isInstance( selectable ) ) {
log.debug( "Encountered formula definition; skipping" ); log.debug( "Encountered formula definition; skipping" );
continue; continue;
} }

View File

@ -18,6 +18,7 @@
import org.hibernate.mapping.Index; import org.hibernate.mapping.Index;
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property; import org.hibernate.mapping.Property;
import org.hibernate.mapping.Selectable;
import org.hibernate.mapping.Table; import org.hibernate.mapping.Table;
import org.hibernate.mapping.UniqueKey; import org.hibernate.mapping.UniqueKey;
@ -64,7 +65,7 @@ public IndexOrUniqueKeySecondPass(String indexName, AnnotatedColumn column, Meta
} }
@Override @Override
public void doSecondPass(Map persistentClasses) throws MappingException { public void doSecondPass(Map<String, PersistentClass> persistentClasses) throws MappingException {
if ( columns != null ) { if ( columns != null ) {
for ( String column1 : columns ) { for ( String column1 : columns ) {
addConstraintToColumn( column1 ); addConstraintToColumn( column1 );
@ -79,18 +80,18 @@ public void doSecondPass(Map persistentClasses) throws MappingException {
propertyHolder.getPersistentClass().getEntityName() : propertyHolder.getPersistentClass().getEntityName() :
propertyHolder.getEntityName(); propertyHolder.getEntityName();
final PersistentClass persistentClass = (PersistentClass) persistentClasses.get( entityName ); final PersistentClass persistentClass = persistentClasses.get( entityName );
final Property property = persistentClass.getProperty( column.getPropertyName() ); final Property property = persistentClass.getProperty( column.getPropertyName() );
if ( property.getValue() instanceof Component ) { if ( property.getValue() instanceof Component ) {
final Component component = (Component) property.getValue(); final Component component = (Component) property.getValue();
List<Column> columns = new ArrayList<>(); List<Column> columns = new ArrayList<>();
component.getColumnIterator().forEachRemaining( selectable -> { for ( Selectable selectable: component.getSelectables() ) {
if ( selectable instanceof Column ) { if ( selectable instanceof Column ) {
columns.add( (Column) selectable ); columns.add( (Column) selectable );
} }
} ); }
addConstraintToColumns( columns ); addConstraintToColumns( columns );
} }
else { else {

View File

@ -27,7 +27,7 @@
import org.hibernate.mapping.OneToOne; import org.hibernate.mapping.OneToOne;
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property; import org.hibernate.mapping.Property;
import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.Selectable;
import org.hibernate.mapping.SortableValue; import org.hibernate.mapping.SortableValue;
import org.hibernate.type.ForeignKeyDirection; import org.hibernate.type.ForeignKeyDirection;
@ -36,18 +36,18 @@
* - * -
*/ */
public class OneToOneSecondPass implements SecondPass { public class OneToOneSecondPass implements SecondPass {
private MetadataBuildingContext buildingContext; private final MetadataBuildingContext buildingContext;
private String mappedBy; private final String mappedBy;
private String ownerEntity; private final String ownerEntity;
private String ownerProperty; private final String ownerProperty;
private PropertyHolder propertyHolder; private final PropertyHolder propertyHolder;
private boolean ignoreNotFound; private final boolean ignoreNotFound;
private PropertyData inferredData; private final PropertyData inferredData;
private XClass targetEntity; private final XClass targetEntity;
private boolean cascadeOnDelete; private final boolean cascadeOnDelete;
private boolean optional; private final boolean optional;
private String cascadeStrategy; private final String cascadeStrategy;
private AnnotatedJoinColumn[] joinColumns; private final AnnotatedJoinColumn[] joinColumns;
//that sucks, we should read that from the property mainly //that sucks, we should read that from the property mainly
public OneToOneSecondPass( public OneToOneSecondPass(
@ -176,10 +176,10 @@ public void doSecondPass(Map persistentClasses) throws MappingException {
propertyHolder.addProperty( prop, inferredData.getDeclaringClass() ); propertyHolder.addProperty( prop, inferredData.getDeclaringClass() );
} }
else if ( otherSideProperty.getValue() instanceof ManyToOne ) { else if ( otherSideProperty.getValue() instanceof ManyToOne ) {
Iterator it = otherSide.getJoinIterator(); Iterator<Join> it = otherSide.getJoinIterator();
Join otherSideJoin = null; Join otherSideJoin = null;
while ( it.hasNext() ) { while ( it.hasNext() ) {
Join otherSideJoinValue = (Join) it.next(); Join otherSideJoinValue = it.next();
if ( otherSideJoinValue.containsProperty( otherSideProperty ) ) { if ( otherSideJoinValue.containsProperty( otherSideProperty ) ) {
otherSideJoin = otherSideJoinValue; otherSideJoin = otherSideJoinValue;
break; break;
@ -200,9 +200,7 @@ else if ( otherSideProperty.getValue() instanceof ManyToOne ) {
manyToOne.setUnwrapProxy( value.isUnwrapProxy() ); manyToOne.setUnwrapProxy( value.isUnwrapProxy() );
manyToOne.markAsLogicalOneToOne(); manyToOne.markAsLogicalOneToOne();
prop.setValue( manyToOne ); prop.setValue( manyToOne );
Iterator otherSideJoinKeyColumns = otherSideJoin.getKey().getColumnIterator(); for ( Column column: otherSideJoin.getKey().getColumns() ) {
while ( otherSideJoinKeyColumns.hasNext() ) {
Column column = (Column) otherSideJoinKeyColumns.next();
Column copy = new Column(); Column copy = new Column();
copy.setLength( column.getLength() ); copy.setLength( column.getLength() );
copy.setScale( column.getScale() ); copy.setScale( column.getScale() );
@ -287,9 +285,7 @@ private Join buildJoinFromMappedBySide(PersistentClass persistentClass, Property
//TODO support for inverse and optional //TODO support for inverse and optional
join.setOptional( true ); //perhaps not quite per-spec, but a Good Thing anyway join.setOptional( true ); //perhaps not quite per-spec, but a Good Thing anyway
key.setCascadeDeleteEnabled( false ); key.setCascadeDeleteEnabled( false );
Iterator mappedByColumns = otherSideProperty.getValue().getColumnIterator(); for ( Column column: otherSideProperty.getValue().getColumns() ) {
while ( mappedByColumns.hasNext() ) {
Column column = (Column) mappedByColumns.next();
Column copy = new Column(); Column copy = new Column();
copy.setLength( column.getLength() ); copy.setLength( column.getLength() );
copy.setScale( column.getScale() ); copy.setScale( column.getScale() );

View File

@ -50,7 +50,7 @@ public void doSecondPass(Map persistentClasses) throws MappingException {
} }
TableBinder.linkJoinColumnWithValueOverridingNameIfImplicit( TableBinder.linkJoinColumnWithValueOverridingNameIfImplicit(
referencedEntity, referencedEntity,
referencedEntity.getKey().getColumnIterator(), referencedEntity.getKey(),
columns, columns,
value); value);
} }

View File

@ -8,6 +8,7 @@
import java.io.Serializable; import java.io.Serializable;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.mapping.PersistentClass;
/** /**
* Second pass operation * Second pass operation
@ -16,7 +17,7 @@
*/ */
public interface SecondPass extends Serializable { public interface SecondPass extends Serializable {
void doSecondPass(java.util.Map persistentClasses) void doSecondPass(java.util.Map<String, PersistentClass> persistentClasses)
throws MappingException; throws MappingException;
} }

View File

@ -30,10 +30,10 @@
* @author Emmanuel Bernard * @author Emmanuel Bernard
*/ */
public class ToOneFkSecondPass extends FkSecondPass { public class ToOneFkSecondPass extends FkSecondPass {
private MetadataBuildingContext buildingContext; private final MetadataBuildingContext buildingContext;
private boolean unique; private final boolean unique;
private String path; private final String path;
private String entityClassName; private final String entityClassName;
public ToOneFkSecondPass( public ToOneFkSecondPass(
ToOne value, ToOne value,
@ -76,9 +76,9 @@ else if ( property != null) {
if ( path.startsWith( "id." ) ) { if ( path.startsWith( "id." ) ) {
localPath = path.substring( 3 ); localPath = path.substring( 3 );
} }
Iterator it = ( (Component) valueIdentifier ).getPropertyIterator();
while ( it.hasNext() ) { Component component = (Component) valueIdentifier;
Property idProperty = (Property) it.next(); for ( Property idProperty : component.getProperties() ) {
if ( localPath.equals( idProperty.getName() ) || localPath.startsWith( idProperty.getName() + "." ) ) { if ( localPath.equals( idProperty.getName() ) || localPath.startsWith( idProperty.getName() + "." ) ) {
return true; return true;
} }

View File

@ -1352,9 +1352,7 @@ else if ( "desc".equals( orderByFragment ) ) {
private static String buildOrderById(PersistentClass associatedClass, String order) { private static String buildOrderById(PersistentClass associatedClass, String order) {
final StringBuilder sb = new StringBuilder(); final StringBuilder sb = new StringBuilder();
final Iterator<Selectable> columnIterator = associatedClass.getIdentifier().getColumnIterator(); for ( Selectable selectable: associatedClass.getIdentifier().getSelectables() ) {
while ( columnIterator.hasNext() ) {
final Selectable selectable = columnIterator.next();
sb.append( selectable.getText() ); sb.append( selectable.getText() );
sb.append( order ); sb.append( order );
sb.append( ", " ); sb.append( ", " );
@ -1812,7 +1810,7 @@ else if ( owner.getIdentifierProperty() != null ) {
} }
else if ( owner.getIdentifierMapper() != null && owner.getIdentifierMapper().getPropertySpan() > 0 ) { else if ( owner.getIdentifierMapper() != null && owner.getIdentifierMapper().getPropertySpan() > 0 ) {
// use the access for the owning entity's "id mapper", if one // 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" ) baseAccessType = prop.getPropertyAccessorName().equals( "property" )
? AccessType.PROPERTY ? AccessType.PROPERTY
: AccessType.FIELD; : AccessType.FIELD;
@ -2016,16 +2014,16 @@ public static void bindManytoManyInverseFk(
final String mappedBy = columns[0].getMappedBy(); final String mappedBy = columns[0].getMappedBy();
if ( StringHelper.isNotEmpty( mappedBy ) ) { if ( StringHelper.isNotEmpty( mappedBy ) ) {
final Property property = referencedEntity.getRecursiveProperty( mappedBy ); final Property property = referencedEntity.getRecursiveProperty( mappedBy );
Iterator<Selectable> mappedByColumns; List<Selectable> mappedByColumns;
if ( property.getValue() instanceof Collection ) { if ( property.getValue() instanceof Collection ) {
mappedByColumns = ( (Collection) property.getValue() ).getKey().getColumnIterator(); mappedByColumns = ( (Collection) property.getValue() ).getKey().getSelectables();
} }
else { else {
//find the appropriate reference key, can be in a join //find the appropriate reference key, can be in a join
Iterator<Join> joinsIt = referencedEntity.getJoinIterator(); Iterator<Join> joinsIt = referencedEntity.getJoinIterator();
KeyValue key = null; KeyValue key = null;
while ( joinsIt.hasNext() ) { while ( joinsIt.hasNext() ) {
Join join = (Join) joinsIt.next(); Join join = joinsIt.next();
if ( join.containsProperty( property ) ) { if ( join.containsProperty( property ) ) {
key = join.getKey(); key = join.getKey();
break; break;
@ -2034,10 +2032,10 @@ public static void bindManytoManyInverseFk(
if ( key == null ) { if ( key == null ) {
key = property.getPersistentClass().getIdentifier(); key = property.getPersistentClass().getIdentifier();
} }
mappedByColumns = key.getColumnIterator(); mappedByColumns = key.getSelectables();
} }
while ( mappedByColumns.hasNext() ) { for ( Selectable selectable: mappedByColumns ) {
Column column = (Column) mappedByColumns.next(); Column column = (Column) selectable;
columns[0].linkValueUsingAColumnCopy( column, value ); columns[0].linkValueUsingAColumnCopy( column, value );
} }
String referencedPropertyName = String referencedPropertyName =

View File

@ -119,11 +119,11 @@ private void makeOneToManyMapKeyColumnNullableIfNotInProperty(
if ( indexValue.getColumnSpan() != 1 ) { if ( indexValue.getColumnSpan() != 1 ) {
throw new AssertionFailure( "Map key mapped by @MapKeyColumn does not have 1 column" ); 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() ) { if ( selectable.isFormula() ) {
throw new AssertionFailure( "Map key mapped by @MapKeyColumn is a Formula" ); 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() ) { if ( !column.isNullable() ) {
final PersistentClass persistentClass = ( ( OneToMany ) map.getElement() ).getAssociatedClass(); final PersistentClass persistentClass = ( ( OneToMany ) map.getElement() ).getAssociatedClass();
// check if the index column has been mapped by the associated entity to a property; // check if the index column has been mapped by the associated entity to a property;
@ -138,11 +138,10 @@ private void makeOneToManyMapKeyColumnNullableIfNotInProperty(
} }
} }
private boolean propertyIteratorContainsColumn(Iterator propertyIterator, Column column) { private boolean propertyIteratorContainsColumn(Iterator<Property> propertyIterator, Column column) {
for ( Iterator it = propertyIterator; it.hasNext(); ) { for (; propertyIterator.hasNext(); ) {
final Property property = (Property) it.next(); final Property property = propertyIterator.next();
for ( Iterator<Selectable> selectableIterator = property.getColumnIterator(); selectableIterator.hasNext(); ) { for ( Selectable selectable: property.getSelectables() ) {
final Selectable selectable = selectableIterator.next();
if ( column.equals( selectable ) ) { if ( column.equals( selectable ) ) {
final Column iteratedColumn = (Column) selectable; final Column iteratedColumn = (Column) selectable;
if ( column.getValue().getTable().equals( iteratedColumn.getValue().getTable() ) ) { if ( column.getValue().getTable().equals( iteratedColumn.getValue().getTable() ) ) {
@ -190,7 +189,7 @@ private void bindKeyFromAssociationTable(
//this is a true Map mapping //this is a true Map mapping
//TODO ugly copy/paste from CollectionBinder.bindManyToManySecondPass //TODO ugly copy/paste from CollectionBinder.bindManyToManySecondPass
String mapKeyType; String mapKeyType;
Class target = void.class; Class<?> target = void.class;
/* /*
* target has priority over reflection for the map key type * target has priority over reflection for the map key type
* JPA 2 has priority * JPA 2 has priority
@ -264,8 +263,9 @@ private void bindKeyFromAssociationTable(
: AccessType.FIELD; : AccessType.FIELD;
} }
else if ( owner.getIdentifierMapper() != null && owner.getIdentifierMapper().getPropertySpan() > 0 ) { else if ( owner.getIdentifierMapper() != null && owner.getIdentifierMapper().getPropertySpan() > 0 ) {
Property prop = (Property) owner.getIdentifierMapper().getPropertyIterator().next(); Property prop = owner.getIdentifierMapper().getProperties().get(0);
accessType = prop.getPropertyAccessorName().equals( "property" ) ? AccessType.PROPERTY accessType = prop.getPropertyAccessorName().equals( "property" )
? AccessType.PROPERTY
: AccessType.FIELD; : AccessType.FIELD;
} }
else { else {
@ -301,7 +301,7 @@ else if ( owner.getIdentifierMapper() != null && owner.getIdentifierMapper().get
mapValue.setIndex( component ); mapValue.setIndex( component );
} }
else { else {
final BasicValueBinder elementBinder = new BasicValueBinder( BasicValueBinder.Kind.MAP_KEY, buildingContext ); final BasicValueBinder<?> elementBinder = new BasicValueBinder<>( BasicValueBinder.Kind.MAP_KEY, buildingContext );
elementBinder.setReturnedClassName( mapKeyType ); elementBinder.setReturnedClassName( mapKeyType );
AnnotatedColumn[] elementColumns = mapKeyColumns; AnnotatedColumn[] elementColumns = mapKeyColumns;
@ -423,11 +423,9 @@ protected Value createFormulatedValue(
if ( value instanceof Component ) { if ( value instanceof Component ) {
Component component = (Component) value; Component component = (Component) value;
Iterator properties = component.getPropertyIterator();
Component indexComponent = new Component( getBuildingContext(), collection ); Component indexComponent = new Component( getBuildingContext(), collection );
indexComponent.setComponentClassName( component.getComponentClassName() ); indexComponent.setComponentClassName( component.getComponentClassName() );
while ( properties.hasNext() ) { for ( Property current : component.getProperties() ) {
Property current = (Property) properties.next();
Property newProperty = new Property(); Property newProperty = new Property();
newProperty.setCascade( current.getCascade() ); newProperty.setCascade( current.getCascade() );
newProperty.setValueGenerationStrategy( current.getValueGenerationStrategy() ); newProperty.setValueGenerationStrategy( current.getValueGenerationStrategy() );
@ -489,9 +487,7 @@ else if ( value instanceof SimpleValue ) {
targetValue = new BasicValue( getBuildingContext(), mapKeyTable ); targetValue = new BasicValue( getBuildingContext(), mapKeyTable );
targetValue.copyTypeFrom( sourceValue ); targetValue.copyTypeFrom( sourceValue );
} }
final Iterator<Selectable> columns = sourceValue.getColumnIterator(); for ( Selectable current : sourceValue.getSelectables() ) {
while ( columns.hasNext() ) {
Selectable current = columns.next();
if ( current instanceof Column ) { if ( current instanceof Column ) {
targetValue.addColumn( ( (Column) current ).clone() ); targetValue.addColumn( ( (Column) current ).clone() );
} }

View File

@ -216,59 +216,59 @@ private List<String> getFollowers(Iterator parentPropIter, String reducedName, S
} }
return followers; return followers;
} }
//
private Iterator getSubPropertyIterator(PersistentClass pc, String reducedName) { // private Iterator getSubPropertyIterator(PersistentClass pc, String reducedName) {
Value value = pc.getRecursiveProperty( reducedName ).getValue(); // Value value = pc.getRecursiveProperty( reducedName ).getValue();
Iterator parentPropIter; // Iterator parentPropIter;
if ( value instanceof Component ) { // if ( value instanceof Component ) {
Component comp = (Component) value; // Component comp = (Component) value;
parentPropIter = comp.getPropertyIterator(); // parentPropIter = comp.getPropertyIterator();
} // }
else if ( value instanceof ToOne ) { // else if ( value instanceof ToOne ) {
ToOne toOne = (ToOne) value; // ToOne toOne = (ToOne) value;
PersistentClass referencedPc = context.getMetadataCollector().getEntityBinding( toOne.getReferencedEntityName() ); // PersistentClass referencedPc = context.getMetadataCollector().getEntityBinding( toOne.getReferencedEntityName() );
if ( toOne.getReferencedPropertyName() != null ) { // if ( toOne.getReferencedPropertyName() != null ) {
try { // try {
parentPropIter = ( (Component) referencedPc.getRecursiveProperty( // parentPropIter = ( (Component) referencedPc.getRecursiveProperty(
toOne.getReferencedPropertyName() // toOne.getReferencedPropertyName()
).getValue() ).getPropertyIterator(); // ).getValue() ).getPropertyIterator();
} // }
catch (ClassCastException e) { // catch (ClassCastException e) {
throw new MappingException( // throw new MappingException(
"dotted notation references neither a component nor a many/one to one", e // "dotted notation references neither a component nor a many/one to one", e
); // );
} // }
} // }
else { // else {
try { // try {
if ( referencedPc.getIdentifierMapper() == null ) { // if ( referencedPc.getIdentifierMapper() == null ) {
parentPropIter = ( (Component) referencedPc.getIdentifierProperty() // parentPropIter = ( (Component) referencedPc.getIdentifierProperty()
.getValue() ).getPropertyIterator(); // .getValue() ).getPropertyIterator();
} // }
else { // else {
parentPropIter = referencedPc.getIdentifierMapper().getPropertyIterator(); // parentPropIter = referencedPc.getIdentifierMapper().getPropertyIterator();
} // }
} // }
catch (ClassCastException e) { // catch (ClassCastException e) {
throw new MappingException( // throw new MappingException(
"dotted notation references neither a component nor a many/one to one", e // "dotted notation references neither a component nor a many/one to one", e
); // );
} // }
} // }
} // }
else { // else {
throw new MappingException( "dotted notation references neither a component nor a many/one to one" ); // throw new MappingException( "dotted notation references neither a component nor a many/one to one" );
} // }
return parentPropIter; // return parentPropIter;
} // }
//
private static int getIndexOfFirstMatchingProperty(List propertyNames, String follower) { // private static int getIndexOfFirstMatchingProperty(List propertyNames, String follower) {
int propertySize = propertyNames.size(); // int propertySize = propertyNames.size();
for (int propIndex = 0; propIndex < propertySize; propIndex++) { // for (int propIndex = 0; propIndex < propertySize; propIndex++) {
if ( ( (String) propertyNames.get( propIndex ) ).startsWith( follower ) ) { // if ( ( (String) propertyNames.get( propIndex ) ).startsWith( follower ) ) {
return propIndex; // return propIndex;
} // }
} // }
return -1; // return -1;
} // }
} }

View File

@ -29,6 +29,7 @@
import org.hibernate.cfg.JPAIndexHolder; import org.hibernate.cfg.JPAIndexHolder;
import org.hibernate.cfg.ObjectNameSource; import org.hibernate.cfg.ObjectNameSource;
import org.hibernate.cfg.UniqueConstraintHolder; import org.hibernate.cfg.UniqueConstraintHolder;
import org.hibernate.dialect.Dialect;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.internal.util.collections.CollectionHelper;
@ -39,6 +40,7 @@
import org.hibernate.mapping.JoinedSubclass; import org.hibernate.mapping.JoinedSubclass;
import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.Property; import org.hibernate.mapping.Property;
import org.hibernate.mapping.Selectable;
import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.SortableValue; import org.hibernate.mapping.SortableValue;
import org.hibernate.mapping.Table; import org.hibernate.mapping.Table;
@ -52,7 +54,6 @@
* *
* @author Emmanuel Bernard * @author Emmanuel Bernard
*/ */
@SuppressWarnings("unchecked")
public class TableBinder { public class TableBinder {
//TODO move it to a getter/setter strategy //TODO move it to a getter/setter strategy
private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, TableBinder.class.getName() ); private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, TableBinder.class.getName() );
@ -525,13 +526,6 @@ public static Table buildAndFillTable(
return table; return table;
} }
private static String extract(Identifier identifier) {
if ( identifier == null ) {
return null;
}
return identifier.render();
}
public static void bindFk( public static void bindFk(
PersistentClass referencedEntity, PersistentClass referencedEntity,
PersistentClass destinationEntity, PersistentClass destinationEntity,
@ -551,14 +545,14 @@ public static void bindFk(
} }
final String mappedByProperty = columns[0].getMappedBy(); final String mappedByProperty = columns[0].getMappedBy();
if ( StringHelper.isNotEmpty( mappedByProperty ) ) { if ( StringHelper.isNotEmpty( mappedByProperty ) ) {
/** /*
* Get the columns of the mapped-by property * Get the columns of the mapped-by property
* copy them and link the copy to the actual value * copy them and link the copy to the actual value
*/ */
LOG.debugf( "Retrieving property %s.%s", associatedClass.getEntityName(), mappedByProperty ); LOG.debugf( "Retrieving property %s.%s", associatedClass.getEntityName(), mappedByProperty );
final Property property = associatedClass.getRecursiveProperty( columns[0].getMappedBy() ); final Property property = associatedClass.getRecursiveProperty( columns[0].getMappedBy() );
Iterator mappedByColumns; List<Column> mappedByColumns;
if ( property.getValue() instanceof Collection ) { if ( property.getValue() instanceof Collection ) {
Collection collection = ( (Collection) property.getValue() ); Collection collection = ( (Collection) property.getValue() );
Value element = collection.getElement(); Value element = collection.getElement();
@ -568,31 +562,25 @@ public static void bindFk(
+ associatedClass.getEntityName() + "." + mappedByProperty + associatedClass.getEntityName() + "." + mappedByProperty
); );
} }
mappedByColumns = element.getColumnIterator(); mappedByColumns = element.getColumns();
} }
else { else {
mappedByColumns = property.getValue().getColumnIterator(); mappedByColumns = property.getValue().getColumns();
} }
while ( mappedByColumns.hasNext() ) { for ( Column column: mappedByColumns ) {
Column column = (Column) mappedByColumns.next();
columns[0].overrideFromReferencedColumnIfNecessary( column ); columns[0].overrideFromReferencedColumnIfNecessary( column );
columns[0].linkValueUsingAColumnCopy( column, value ); columns[0].linkValueUsingAColumnCopy( column, value );
} }
} }
else if ( columns[0].isImplicit() ) { else if ( columns[0].isImplicit() ) {
/** /*
* if columns are implicit, then create the columns based on the * if columns are implicit, then create the columns based on the
* referenced entity id columns * referenced entity id columns
*/ */
Iterator idColumns; List<Column> idColumns = referencedEntity instanceof JoinedSubclass
if ( referencedEntity instanceof JoinedSubclass ) { ? referencedEntity.getKey().getColumns()
idColumns = referencedEntity.getKey().getColumnIterator(); : referencedEntity.getIdentifier().getColumns();
} for ( Column column: idColumns ) {
else {
idColumns = referencedEntity.getIdentifier().getColumnIterator();
}
while ( idColumns.hasNext() ) {
Column column = (Column) idColumns.next();
columns[0].linkValueUsingDefaultColumnNaming( column, referencedEntity, value ); columns[0].linkValueUsingDefaultColumnNaming( column, referencedEntity, value );
columns[0].overrideFromReferencedColumnIfNecessary( column ); columns[0].overrideFromReferencedColumnIfNecessary( column );
} }
@ -635,7 +623,7 @@ else if ( value instanceof DependantValue ) {
); );
} }
linkJoinColumnWithValueOverridingNameIfImplicit( linkJoinColumnWithValueOverridingNameIfImplicit(
referencedEntity, synthProp.getColumnIterator(), columns, value referencedEntity, synthProp.getValue(), columns, value
); );
if ( value instanceof SortableValue ) { if ( value instanceof SortableValue ) {
( (SortableValue) value ).sortProperties(); ( (SortableValue) value ).sortProperties();
@ -654,7 +642,7 @@ else if ( value instanceof DependantValue ) {
} }
linkJoinColumnWithValueOverridingNameIfImplicit( linkJoinColumnWithValueOverridingNameIfImplicit(
referencedEntity, referencedEntity,
referencedEntity.getIdentifier().getColumnIterator(), referencedEntity.getIdentifier(),
columns, columns,
value value
); );
@ -668,25 +656,25 @@ else if ( value instanceof DependantValue ) {
( (Component) referencedEntity.getKey() ).sortProperties(); ( (Component) referencedEntity.getKey() ).sortProperties();
} }
//explicit referencedColumnName //explicit referencedColumnName
Iterator idColItr = referencedEntity.getKey().getColumnIterator(); List<Column> idColumns = referencedEntity.getKey().getColumns();
Column col;
//works cause the pk has to be on the primary table //works cause the pk has to be on the primary table
Table table = referencedEntity.getTable(); Table table = referencedEntity.getTable();
if ( !idColItr.hasNext() ) { if ( idColumns.isEmpty() ) {
LOG.debug( "No column in the identifier!" ); LOG.debug( "No column in the identifier!" );
} }
while ( idColItr.hasNext() ) { for ( Column col: idColumns ) {
boolean match = false; boolean match = false;
//for each PK column, find the associated FK column. //for each PK column, find the associated FK column.
col = (Column) idColItr.next(); Dialect dialect = buildingContext.getMetadataCollector().getDatabase()
final String colName = col.getQuotedName( buildingContext.getMetadataCollector().getDatabase().getJdbcEnvironment().getDialect() ); .getJdbcEnvironment().getDialect();
final String colName = col.getQuotedName(dialect);
for (AnnotatedJoinColumn joinCol : columns) { for (AnnotatedJoinColumn joinCol : columns) {
String referencedColumn = joinCol.getReferencedColumn(); String referencedColumn = joinCol.getReferencedColumn();
referencedColumn = buildingContext.getMetadataCollector().getPhysicalColumnName( referencedColumn = buildingContext.getMetadataCollector().getPhysicalColumnName(
table, table,
referencedColumn referencedColumn
); );
//In JPA 2 referencedColumnName is case insensitive //In JPA 2 referencedColumnName is case-insensitive
if ( referencedColumn.equalsIgnoreCase( colName ) ) { if ( referencedColumn.equalsIgnoreCase( colName ) ) {
//proper join column //proper join column
if ( joinCol.isNameDeferred() ) { if ( joinCol.isNameDeferred() ) {
@ -718,15 +706,16 @@ else if ( value instanceof DependantValue ) {
} }
value.createForeignKey(); value.createForeignKey();
if ( unique ) { if ( unique ) {
createUniqueConstraint( value ); value.createUniqueKey();
} }
} }
public static void linkJoinColumnWithValueOverridingNameIfImplicit( public static void linkJoinColumnWithValueOverridingNameIfImplicit(
PersistentClass referencedEntity, PersistentClass referencedEntity,
Iterator columnIterator, Value v,
AnnotatedJoinColumn[] columns, AnnotatedJoinColumn[] columns,
SimpleValue value) { SimpleValue value) {
Iterator<Selectable> columnIterator = v.getColumnIterator();
for (AnnotatedJoinColumn joinCol : columns) { for (AnnotatedJoinColumn joinCol : columns) {
Column synthCol = (Column) columnIterator.next(); Column synthCol = (Column) columnIterator.next();
if ( joinCol.isNameDeferred() ) { if ( joinCol.isNameDeferred() ) {
@ -740,15 +729,6 @@ public static void linkJoinColumnWithValueOverridingNameIfImplicit(
} }
} }
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) { public static void addIndexes(Table hibTable, Index[] indexes, MetadataBuildingContext buildingContext) {
for (Index index : indexes) { for (Index index : indexes) {
//no need to handle inSecondPass here since it is only called from EntityBinder //no need to handle inSecondPass here since it is only called from EntityBinder

View File

@ -10,7 +10,6 @@
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -280,9 +279,7 @@ private static void applyMin(Property property, ConstraintDescriptor<?> descript
ConstraintDescriptor<Min> minConstraint = (ConstraintDescriptor<Min>) descriptor; ConstraintDescriptor<Min> minConstraint = (ConstraintDescriptor<Min>) descriptor;
long min = minConstraint.getAnnotation().value(); long min = minConstraint.getAnnotation().value();
final Iterator<Selectable> itor = property.getColumnIterator(); for ( Selectable selectable : property.getSelectables() ) {
if ( itor.hasNext() ) {
final Selectable selectable = itor.next();
if ( selectable instanceof Column ) { if ( selectable instanceof Column ) {
Column col = (Column) selectable; Column col = (Column) selectable;
String checkConstraint = col.getQuotedName(dialect) + ">=" + min; String checkConstraint = col.getQuotedName(dialect) + ">=" + min;
@ -298,9 +295,7 @@ private static void applyMax(Property property, ConstraintDescriptor<?> descript
ConstraintDescriptor<Max> maxConstraint = (ConstraintDescriptor<Max>) descriptor; ConstraintDescriptor<Max> maxConstraint = (ConstraintDescriptor<Max>) descriptor;
long max = maxConstraint.getAnnotation().value(); long max = maxConstraint.getAnnotation().value();
final Iterator<Selectable> itor = property.getColumnIterator(); for ( Selectable selectable : property.getSelectables() ) {
if ( itor.hasNext() ) {
final Selectable selectable = itor.next();
if ( selectable instanceof Column ) { if ( selectable instanceof Column ) {
Column col = (Column) selectable; Column col = (Column) selectable;
String checkConstraint = col.getQuotedName( dialect ) + "<=" + max; String checkConstraint = col.getQuotedName( dialect ) + "<=" + max;
@ -327,9 +322,7 @@ private static boolean applyNotNull(Property property, ConstraintDescriptor<?> d
if ( !( property.getPersistentClass() instanceof SingleTableSubclass ) ) { if ( !( property.getPersistentClass() instanceof SingleTableSubclass ) ) {
//composite should not add not-null on all columns //composite should not add not-null on all columns
if ( !property.isComposite() ) { if ( !property.isComposite() ) {
final Iterator<Selectable> itr = property.getColumnIterator(); for ( Selectable selectable : property.getSelectables() ) {
while ( itr.hasNext() ) {
final Selectable selectable = itr.next();
if ( selectable instanceof Column ) { if ( selectable instanceof Column ) {
((Column) selectable).setNullable( false ); ((Column) selectable).setNullable( false );
} }
@ -356,9 +349,7 @@ private static void applyDigits(Property property, ConstraintDescriptor<?> descr
int integerDigits = digitsConstraint.getAnnotation().integer(); int integerDigits = digitsConstraint.getAnnotation().integer();
int fractionalDigits = digitsConstraint.getAnnotation().fraction(); int fractionalDigits = digitsConstraint.getAnnotation().fraction();
final Iterator<Selectable> itor = property.getColumnIterator(); for ( Selectable selectable : property.getSelectables() ) {
if ( itor.hasNext() ) {
final Selectable selectable = itor.next();
if ( selectable instanceof Column ) { if ( selectable instanceof Column ) {
Column col = (Column) selectable; Column col = (Column) selectable;
col.setPrecision( integerDigits + fractionalDigits ); col.setPrecision( integerDigits + fractionalDigits );
@ -376,10 +367,7 @@ private static void applySize(Property property, ConstraintDescriptor<?> descrip
ConstraintDescriptor<Size> sizeConstraint = (ConstraintDescriptor<Size>) descriptor; ConstraintDescriptor<Size> sizeConstraint = (ConstraintDescriptor<Size>) descriptor;
int max = sizeConstraint.getAnnotation().max(); int max = sizeConstraint.getAnnotation().max();
final Iterator<Selectable> itor = property.getColumnIterator(); for ( Column col : property.getColumns() ) {
if ( itor.hasNext() ) {
final Selectable selectable = itor.next();
Column col = (Column) selectable;
if ( max < Integer.MAX_VALUE ) { if ( max < Integer.MAX_VALUE ) {
col.setLength( max ); col.setLength( max );
} }
@ -394,9 +382,7 @@ private static void applyLength(Property property, ConstraintDescriptor<?> descr
&& String.class.equals( propertyDescriptor.getElementClass() ) ) { && String.class.equals( propertyDescriptor.getElementClass() ) ) {
int max = (Integer) descriptor.getAttributes().get( "max" ); int max = (Integer) descriptor.getAttributes().get( "max" );
final Iterator<Selectable> itor = property.getColumnIterator(); for ( Selectable selectable : property.getSelectables() ) {
if ( itor.hasNext() ) {
final Selectable selectable = itor.next();
if ( selectable instanceof Column ) { if ( selectable instanceof Column ) {
Column col = (Column) selectable; Column col = (Column) selectable;
if ( max < Integer.MAX_VALUE ) { if ( max < Integer.MAX_VALUE ) {

View File

@ -28,9 +28,7 @@ public NullableDiscriminatorColumnSecondPass(String rootEntityName) {
public void doSecondPass(Map persistentClasses) throws MappingException { public void doSecondPass(Map persistentClasses) throws MappingException {
PersistentClass rootPersistenceClass = (PersistentClass) persistentClasses.get( rootEntityName ); PersistentClass rootPersistenceClass = (PersistentClass) persistentClasses.get( rootEntityName );
if ( hasNullDiscriminatorValue( rootPersistenceClass ) ) { if ( hasNullDiscriminatorValue( rootPersistenceClass ) ) {
for ( Iterator<Selectable> iterator = rootPersistenceClass.getDiscriminator().getColumnIterator(); for ( Selectable selectable: rootPersistenceClass.getDiscriminator().getSelectables() ) {
iterator.hasNext(); ) {
Selectable selectable = iterator.next();
if ( selectable instanceof Column ) { if ( selectable instanceof Column ) {
( (Column) selectable ).setNullable( true ); ( (Column) selectable ).setNullable( true );
} }
@ -38,7 +36,6 @@ public void doSecondPass(Map persistentClasses) throws MappingException {
} }
} }
@SuppressWarnings({ "unchecked" })
private boolean hasNullDiscriminatorValue(PersistentClass rootPersistenceClass) { private boolean hasNullDiscriminatorValue(PersistentClass rootPersistenceClass) {
if ( rootPersistenceClass.isDiscriminatorValueNull() ) { if ( rootPersistenceClass.isDiscriminatorValueNull() ) {
return true; return true;

View File

@ -125,12 +125,10 @@ public static TemporaryTable createIdTable(
final PersistentClass entityBinding = runtimeModelCreationContext.getBootModel() final PersistentClass entityBinding = runtimeModelCreationContext.getBootModel()
.getEntityBinding( entityDescriptor.getEntityName() ); .getEntityBinding( entityDescriptor.getEntityName() );
final Iterator<Selectable> itr = entityBinding.getKey().getColumnIterator();
final Iterator<JdbcMapping> jdbcMappings = entityDescriptor.getIdentifierMapping() final Iterator<JdbcMapping> jdbcMappings = entityDescriptor.getIdentifierMapping()
.getJdbcMappings() .getJdbcMappings()
.iterator(); .iterator();
while ( itr.hasNext() ) { for ( Column column : entityBinding.getKey().getColumns() ) {
final Column column = (Column) itr.next();
final JdbcMapping jdbcMapping = jdbcMappings.next(); final JdbcMapping jdbcMapping = jdbcMappings.next();
columns.add( columns.add(
new TemporaryTableColumn( new TemporaryTableColumn(
@ -155,8 +153,8 @@ public static TemporaryTable createIdTable(
if ( !( fkTarget instanceof EntityIdentifierMapping ) ) { if ( !( fkTarget instanceof EntityIdentifierMapping ) ) {
final Value value = entityBinding.getSubclassProperty( pluralAttribute.getAttributeName() ) final Value value = entityBinding.getSubclassProperty( pluralAttribute.getAttributeName() )
.getValue(); .getValue();
final Iterator<Selectable> columnIterator = ( (Collection) value ).getKey() final Iterator<Selectable> columnIterator =
.getColumnIterator(); ( (Collection) value ).getKey().getColumnIterator();
fkTarget.forEachSelectable( fkTarget.forEachSelectable(
(columnIndex, selection) -> { (columnIndex, selection) -> {
final Selectable selectable = columnIterator.next(); final Selectable selectable = columnIterator.next();
@ -207,12 +205,10 @@ public static TemporaryTable createEntityTable(
final boolean hasOptimizer; final boolean hasOptimizer;
if ( identityColumn ) { if ( identityColumn ) {
hasOptimizer = false; hasOptimizer = false;
final Iterator<Selectable> itr = entityBinding.getKey().getColumnIterator();
final Iterator<JdbcMapping> jdbcMappings = entityDescriptor.getIdentifierMapping() final Iterator<JdbcMapping> jdbcMappings = entityDescriptor.getIdentifierMapping()
.getJdbcMappings() .getJdbcMappings()
.iterator(); .iterator();
while ( itr.hasNext() ) { for ( Column column : entityBinding.getKey().getColumns() ) {
final Column column = (Column) itr.next();
final JdbcMapping jdbcMapping = jdbcMappings.next(); final JdbcMapping jdbcMapping = jdbcMappings.next();
columns.add( columns.add(
new TemporaryTableColumn( new TemporaryTableColumn(
@ -237,12 +233,10 @@ public static TemporaryTable createEntityTable(
hasOptimizer = false; hasOptimizer = false;
} }
} }
final Iterator<Selectable> itr = entityBinding.getKey().getColumnIterator();
final Iterator<JdbcMapping> jdbcMappings = entityDescriptor.getIdentifierMapping() final Iterator<JdbcMapping> jdbcMappings = entityDescriptor.getIdentifierMapping()
.getJdbcMappings() .getJdbcMappings()
.iterator(); .iterator();
while ( itr.hasNext() ) { for ( Column column : entityBinding.getKey().getColumns() ) {
final Column column = (Column) itr.next();
final JdbcMapping jdbcMapping = jdbcMappings.next(); final JdbcMapping jdbcMapping = jdbcMappings.next();
columns.add( columns.add(
new TemporaryTableColumn( new TemporaryTableColumn(
@ -259,7 +253,7 @@ public static TemporaryTable createEntityTable(
final EntityDiscriminatorMapping discriminatorMapping = entityDescriptor.getDiscriminatorMapping(); final EntityDiscriminatorMapping discriminatorMapping = entityDescriptor.getDiscriminatorMapping();
if ( entityBinding.getDiscriminator() != null && !discriminatorMapping.isFormula() ) { if ( entityBinding.getDiscriminator() != null && !discriminatorMapping.isFormula() ) {
final Column discriminator = (Column) entityBinding.getDiscriminator().getColumnIterator().next(); final Column discriminator = entityBinding.getDiscriminator().getColumns().get(0);
columns.add( columns.add(
new TemporaryTableColumn( new TemporaryTableColumn(
temporaryTable, temporaryTable,

View File

@ -6,7 +6,6 @@
*/ */
package org.hibernate.id; package org.hibernate.id;
import java.util.Arrays;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
@ -69,14 +68,19 @@ public int getColumnSpan() {
return 1; return 1;
} }
@Override @Override @Deprecated
public Iterator<Selectable> getColumnIterator() { public Iterator<Selectable> getColumnIterator() {
return new ColumnIterator( column ); return new ColumnIterator( column );
} }
@Override @Override
public List<Selectable> getSelectables() { public List<Selectable> getSelectables() {
return Arrays.asList( column ); return List.of( column );
}
@Override
public List<Column> getColumns() {
return List.of( column );
} }
@Override @Override
@ -130,7 +134,11 @@ public boolean hasAnyUpdatableColumns() {
} }
@Override @Override
public void createForeignKey() throws MappingException { public void createForeignKey() {
}
@Override
public void createUniqueKey() {
} }
@Override @Override

View File

@ -30,6 +30,7 @@ public JoinedIterator(List<Iterator<T>> wrappedIterators) {
this( wrappedIterators.toArray(new Iterator[0]) ); this( wrappedIterators.toArray(new Iterator[0]) );
} }
@SafeVarargs
public JoinedIterator(Iterator<? extends T>... iteratorsToWrap) { public JoinedIterator(Iterator<? extends T>... iteratorsToWrap) {
if( iteratorsToWrap == null ) { if( iteratorsToWrap == null ) {
throw new NullPointerException( "Iterators to join were null" ); throw new NullPointerException( "Iterators to join were null" );

View File

@ -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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
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<E> extends AbstractList<E> {
private final List<List<E>> lists;
private final int size;
public JoinedList(List<List<E>> lists) {
this.lists = lists;
size = lists.stream().map(List::size).reduce(0, Integer::sum);
}
@SafeVarargs
public JoinedList(List<E>... lists) {
this( Arrays.asList(lists) );
}
@Override
public E get(int index) {
for (List<E> list: lists) {
if ( list.size() > index ) {
return list.get(index);
}
index -= list.size();
}
return null;
}
@Override
public int size() {
return size;
}
@Override
public Iterator<E> iterator() {
return lists.stream().flatMap(List::stream).iterator();
}
}

View File

@ -47,7 +47,7 @@ public abstract class Collection implements Fetchable, Value, Filterable {
public static final String DEFAULT_KEY_COLUMN_NAME = "id"; public static final String DEFAULT_KEY_COLUMN_NAME = "id";
private final MetadataBuildingContext buildingContext; private final MetadataBuildingContext buildingContext;
private PersistentClass owner; private final PersistentClass owner;
private KeyValue key; private KeyValue key;
private Value element; private Value element;
@ -346,14 +346,12 @@ private void checkColumnDuplication(java.util.Set<String> distinctColumns, Value
throws MappingException { throws MappingException {
final boolean[] insertability = value.getColumnInsertability(); final boolean[] insertability = value.getColumnInsertability();
final boolean[] updatability = value.getColumnUpdateability(); final boolean[] updatability = value.getColumnUpdateability();
final Iterator<Selectable> iterator = value.getColumnIterator();
int i = 0; int i = 0;
while ( iterator.hasNext() ) { for ( Selectable selectable : value.getSelectables() ) {
Selectable s = iterator.next();
// exclude formulas and columns that are not insertable or updatable // exclude formulas and columns that are not insertable or updatable
// since these values can be repeated (HHH-5393) // since these values can be repeated (HHH-5393)
if ( !s.isFormula() && ( insertability[i] || updatability[i] ) ) { if ( !selectable.isFormula() && ( insertability[i] || updatability[i] ) ) {
Column col = (Column) s; Column col = (Column) selectable;
if ( !distinctColumns.add( col.getName() ) ) { if ( !distinctColumns.add( col.getName() ) ) {
throw new MappingException( throw new MappingException(
"Repeated column in mapping for collection: " "Repeated column in mapping for collection: "
@ -387,6 +385,7 @@ private void checkColumnDuplication() throws MappingException {
} }
} }
@Deprecated
public Iterator<Selectable> getColumnIterator() { public Iterator<Selectable> getColumnIterator() {
return Collections.emptyIterator(); return Collections.emptyIterator();
} }
@ -396,6 +395,11 @@ public List<Selectable> getSelectables() {
return Collections.emptyList(); return Collections.emptyList();
} }
@Override
public List<Column> getColumns() {
return Collections.emptyList();
}
public int getColumnSpan() { public int getColumnSpan() {
return 0; return 0;
} }
@ -404,8 +408,7 @@ public Type getType() throws MappingException {
return getCollectionType(); return getCollectionType();
} }
@SuppressWarnings("rawtypes") public CollectionSemantics<?,?> getCollectionSemantics() {
public CollectionSemantics getCollectionSemantics() {
if ( cachedCollectionSemantics == null ) { if ( cachedCollectionSemantics == null ) {
cachedCollectionSemantics = resolveCollectionSemantics(); cachedCollectionSemantics = resolveCollectionSemantics();
} }
@ -475,6 +478,10 @@ public Table getTable() {
public void createForeignKey() { public void createForeignKey() {
} }
@Override
public void createUniqueKey() {
}
public boolean isSimpleValue() { public boolean isSimpleValue() {
return false; return false;
} }

View File

@ -12,6 +12,7 @@
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.boot.model.relational.Database; import org.hibernate.boot.model.relational.Database;
@ -41,7 +42,7 @@
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public class Component extends SimpleValue implements MetaAttributable, SortableValue { public class Component extends SimpleValue implements MetaAttributable, SortableValue {
private ArrayList<Property> properties = new ArrayList<>(); private final ArrayList<Property> properties = new ArrayList<>();
private int[] originalPropertyOrder = ArrayHelper.EMPTY_INT_ARRAY; private int[] originalPropertyOrder = ArrayHelper.EMPTY_INT_ARRAY;
private String componentClassName; private String componentClassName;
private boolean embedded; private boolean embedded;
@ -88,6 +89,10 @@ public Iterator<Property> getPropertyIterator() {
return properties.iterator(); return properties.iterator();
} }
public List<Property> getProperties() {
return properties;
}
public void addProperty(Property p) { public void addProperty(Property p) {
properties.add( p ); properties.add( p );
} }
@ -100,37 +105,35 @@ public void addColumn(Column column) {
@Override @Override
public int getColumnSpan() { public int getColumnSpan() {
int n=0; int n=0;
Iterator iter = getPropertyIterator(); for ( Property property : getProperties() ) {
while ( iter.hasNext() ) { n += property.getColumnSpan();
Property p = (Property) iter.next();
n+= p.getColumnSpan();
} }
return n; return n;
} }
@Override @Override @Deprecated
@SuppressWarnings("unchecked")
public Iterator<Selectable> getColumnIterator() { public Iterator<Selectable> getColumnIterator() {
@SuppressWarnings("unchecked")
Iterator<Selectable>[] iters = new Iterator[ getPropertySpan() ]; Iterator<Selectable>[] iters = new Iterator[ getPropertySpan() ];
Iterator<Property> iter = getPropertyIterator();
int i = 0; int i = 0;
while ( iter.hasNext() ) { for ( Property property : getProperties() ) {
iters[i++] = iter.next().getColumnIterator(); iters[i++] = property.getColumnIterator();
} }
return new JoinedIterator<>( iters ); return new JoinedIterator<>( iters );
} }
@Override @Override
public List<Selectable> getSelectables() { public List<Selectable> getSelectables() {
final List<Selectable> columns = new ArrayList<>(); return properties.stream()
final Iterator<Property> propertyIterator = getPropertyIterator(); .flatMap( p -> p.getSelectables().stream() )
while ( propertyIterator.hasNext() ) { .collect(Collectors.toList());
final Iterator<Selectable> columnIterator = propertyIterator.next().getColumnIterator(); }
while ( columnIterator.hasNext() ) {
columns.add( columnIterator.next() ); @Override
} public List<Column> getColumns() {
} return properties.stream()
return columns; .flatMap( p -> p.getValue().getColumns().stream() )
.collect(Collectors.toList());
} }
public boolean isEmbedded() { public boolean isEmbedded() {
@ -141,7 +144,7 @@ public String getComponentClassName() {
return componentClassName; return componentClassName;
} }
public Class getComponentClass() throws MappingException { public Class<?> getComponentClass() throws MappingException {
final ClassLoaderService classLoaderService = getMetadata() final ClassLoaderService classLoaderService = getMetadata()
.getMetadataBuildingOptions() .getMetadataBuildingOptions()
.getServiceRegistry() .getServiceRegistry()
@ -256,10 +259,8 @@ public boolean isSame(Component other) {
@Override @Override
public boolean[] getColumnInsertability() { public boolean[] getColumnInsertability() {
boolean[] result = new boolean[ getColumnSpan() ]; boolean[] result = new boolean[ getColumnSpan() ];
Iterator iter = getPropertyIterator();
int i=0; int i=0;
while ( iter.hasNext() ) { for ( Property prop : getProperties() ) {
Property prop = (Property) iter.next();
boolean[] chunk = prop.getValue().getColumnInsertability(); boolean[] chunk = prop.getValue().getColumnInsertability();
if ( prop.isInsertable() ) { if ( prop.isInsertable() ) {
System.arraycopy(chunk, 0, result, i, chunk.length); System.arraycopy(chunk, 0, result, i, chunk.length);
@ -284,10 +285,8 @@ public boolean hasAnyInsertableColumns() {
@Override @Override
public boolean[] getColumnUpdateability() { public boolean[] getColumnUpdateability() {
boolean[] result = new boolean[ getColumnSpan() ]; boolean[] result = new boolean[ getColumnSpan() ];
Iterator iter = getPropertyIterator();
int i=0; int i=0;
while ( iter.hasNext() ) { for ( Property prop : getProperties() ) {
Property prop = (Property) iter.next();
boolean[] chunk = prop.getValue().getColumnUpdateability(); boolean[] chunk = prop.getValue().getColumnUpdateability();
if ( prop.isUpdateable() ) { if ( prop.isUpdateable() ) {
System.arraycopy(chunk, 0, result, i, chunk.length); System.arraycopy(chunk, 0, result, i, chunk.length);
@ -334,9 +333,7 @@ public Property getProperty(int index) {
} }
public Property getProperty(String propertyName) throws MappingException { public Property getProperty(String propertyName) throws MappingException {
Iterator iter = getPropertyIterator(); for ( Property prop : getProperties() ) {
while ( iter.hasNext() ) {
Property prop = (Property) iter.next();
if ( prop.getName().equals(propertyName) ) { if ( prop.getName().equals(propertyName) ) {
return prop; return prop;
} }
@ -391,8 +388,8 @@ private IdentifierGenerator buildIdentifierGenerator(
); );
} }
final Class entityClass = rootClass.getMappedClass(); final Class<?> entityClass = rootClass.getMappedClass();
final Class attributeDeclarer; // what class is the declarer of the composite pk attributes final Class<?> attributeDeclarer; // what class is the declarer of the composite pk attributes
CompositeNestedGeneratedValueGenerator.GenerationContextLocator locator; CompositeNestedGeneratedValueGenerator.GenerationContextLocator locator;
// IMPL NOTE : See the javadoc discussion on CompositeNestedGeneratedValueGenerator wrt the // IMPL NOTE : See the javadoc discussion on CompositeNestedGeneratedValueGenerator wrt the
@ -413,9 +410,7 @@ else if ( rootClass.getIdentifierProperty() != null ) {
locator = new StandardGenerationContextLocator( rootClass.getEntityName() ); locator = new StandardGenerationContextLocator( rootClass.getEntityName() );
final CompositeNestedGeneratedValueGenerator generator = new CompositeNestedGeneratedValueGenerator( locator ); final CompositeNestedGeneratedValueGenerator generator = new CompositeNestedGeneratedValueGenerator( locator );
Iterator itr = getPropertyIterator(); for ( Property property : getProperties() ) {
while ( itr.hasNext() ) {
final Property property = (Property) itr.next();
if ( property.getValue().isSimpleValue() ) { if ( property.getValue().isSimpleValue() ) {
final SimpleValue value = (SimpleValue) property.getValue(); final SimpleValue value = (SimpleValue) property.getValue();
@ -443,13 +438,13 @@ else if ( rootClass.getIdentifierProperty() != null ) {
return generator; return generator;
} }
private Setter injector(Property property, Class attributeDeclarer) { private Setter injector(Property property, Class<?> attributeDeclarer) {
return property.getPropertyAccessStrategy( attributeDeclarer ) return property.getPropertyAccessStrategy( attributeDeclarer )
.buildPropertyAccess( attributeDeclarer, property.getName(), true ) .buildPropertyAccess( attributeDeclarer, property.getName(), true )
.getSetter(); .getSetter();
} }
private Class resolveComponentClass() { private Class<?> resolveComponentClass() {
try { try {
return getComponentClass(); return getComponentClass();
} }
@ -543,9 +538,7 @@ private int[] sortProperties(boolean forceRetainOriginalOrder) {
final List<Column> columns = primaryKey.getColumns(); final List<Column> columns = primaryKey.getColumns();
columns.clear(); columns.clear();
for ( int i = 0; i < properties.size(); i++ ) { for ( int i = 0; i < properties.size(); i++ ) {
final Iterator<Selectable> columnIterator = properties.get( i ).getColumnIterator(); for ( Selectable selectable : properties.get(i).getSelectables() ) {
while ( columnIterator.hasNext() ) {
final Selectable selectable = columnIterator.next();
if ( selectable instanceof Column ) { if ( selectable instanceof Column ) {
columns.add( (Column) selectable ); columns.add( (Column) selectable );
} }

View File

@ -17,6 +17,7 @@
import java.util.Locale; import java.util.Locale;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.boot.model.relational.Exportable; import org.hibernate.boot.model.relational.Exportable;
import org.hibernate.boot.model.relational.SqlStringGenerationContext; import org.hibernate.boot.model.relational.SqlStringGenerationContext;
import org.hibernate.dialect.Dialect; import org.hibernate.dialect.Dialect;
@ -129,11 +130,13 @@ public void addColumn(Column column) {
} }
} }
public void addColumns(Iterator columnIterator) { public void addColumns(Value value) {
while ( columnIterator.hasNext() ) { for ( Selectable selectable : value.getSelectables() ) {
Selectable col = (Selectable) columnIterator.next(); if ( selectable.isFormula() ) {
if ( !col.isFormula() ) { throw new MappingException( "constraint involves a formula: " + this.name );
addColumn( (Column) col ); }
else {
addColumn( (Column) selectable );
} }
} }
} }

View File

@ -7,7 +7,9 @@
package org.hibernate.mapping; 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 * @author Steve Ebersole
*/ */
public interface Contributable { public interface Contributable {

View File

@ -7,17 +7,18 @@
package org.hibernate.mapping; package org.hibernate.mapping;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.naming.Identifier;
import org.hibernate.boot.model.relational.Namespace; import org.hibernate.boot.model.relational.Namespace;
import org.hibernate.internal.util.collections.JoinedIterator; import org.hibernate.internal.util.collections.JoinedIterator;
import org.hibernate.internal.util.collections.JoinedList;
/** /**
* @author Gavin King * @author Gavin King
*/ */
@SuppressWarnings("unchecked")
public class DenormalizedTable extends Table { public class DenormalizedTable extends Table {
private final Table includedTable; private final Table includedTable;
@ -59,9 +60,9 @@ public DenormalizedTable(
@Override @Override
public void createForeignKeys() { public void createForeignKeys() {
includedTable.createForeignKeys(); includedTable.createForeignKeys();
Iterator iter = includedTable.getForeignKeyIterator(); Iterator<ForeignKey> iter = includedTable.getForeignKeyIterator();
while ( iter.hasNext() ) { while ( iter.hasNext() ) {
ForeignKey fk = (ForeignKey) iter.next(); ForeignKey fk = iter.next();
createForeignKey( createForeignKey(
Constraint.generateName( Constraint.generateName(
fk.generatedConstraintNamePrefix(), fk.generatedConstraintNamePrefix(),
@ -79,29 +80,27 @@ public void createForeignKeys() {
@Override @Override
public Column getColumn(Column column) { public Column getColumn(Column column) {
Column superColumn = super.getColumn( column ); Column superColumn = super.getColumn( column );
if ( superColumn != null ) { return superColumn != null ? superColumn : includedTable.getColumn(column);
return superColumn;
}
else {
return includedTable.getColumn( column );
}
} }
public Column getColumn(Identifier name) { public Column getColumn(Identifier name) {
Column superColumn = super.getColumn( name ); Column superColumn = super.getColumn( name );
if ( superColumn != null ) { return superColumn != null ? superColumn : includedTable.getColumn(name);
return superColumn; }
}
else { @Override @Deprecated
return includedTable.getColumn( name ); public Iterator<Column> getColumnIterator() {
} return new JoinedIterator<>(
includedTable.getColumnIterator(),
super.getColumnIterator()
);
} }
@Override @Override
public Iterator getColumnIterator() { public Collection<Column> getColumns() {
return new JoinedIterator( return new JoinedList<>(
includedTable.getColumnIterator(), new ArrayList<>( includedTable.getColumns() ),
super.getColumnIterator() new ArrayList<>( super.getColumns() )
); );
} }
@ -116,11 +115,11 @@ public PrimaryKey getPrimaryKey() {
} }
@Override @Override
public Iterator getUniqueKeyIterator() { public Iterator<UniqueKey> getUniqueKeyIterator() {
if ( !includedTable.isPhysicalTable() ) { if ( !includedTable.isPhysicalTable() ) {
Iterator iter = includedTable.getUniqueKeyIterator(); Iterator<UniqueKey> iter = includedTable.getUniqueKeyIterator();
while ( iter.hasNext() ) { while ( iter.hasNext() ) {
UniqueKey uk = (UniqueKey) iter.next(); UniqueKey uk = iter.next();
createUniqueKey( uk.getColumns() ); createUniqueKey( uk.getColumns() );
} }
} }
@ -128,18 +127,18 @@ public Iterator getUniqueKeyIterator() {
} }
@Override @Override
public Iterator getIndexIterator() { public Iterator<Index> getIndexIterator() {
List indexes = new ArrayList(); List<Index> indexes = new ArrayList<>();
Iterator iter = includedTable.getIndexIterator(); Iterator<Index> iter = includedTable.getIndexIterator();
while ( iter.hasNext() ) { while ( iter.hasNext() ) {
Index parentIndex = (Index) iter.next(); Index parentIndex = iter.next();
Index index = new Index(); Index index = new Index();
index.setName( getName() + parentIndex.getName() ); index.setName( getName() + parentIndex.getName() );
index.setTable( this ); index.setTable( this );
index.addColumns( parentIndex.getColumnIterator() ); index.addColumns( parentIndex.getColumnIterator() );
indexes.add( index ); indexes.add( index );
} }
return new JoinedIterator( return new JoinedIterator<>(
indexes.iterator(), indexes.iterator(),
super.getIndexIterator() super.getIndexIterator()
); );

View File

@ -14,8 +14,8 @@
public class DependantBasicValue extends BasicValue { public class DependantBasicValue extends BasicValue {
private final BasicValue referencedValue; private final BasicValue referencedValue;
private boolean nullable; private final boolean nullable;
private boolean updateable; private final boolean updateable;
public DependantBasicValue( public DependantBasicValue(
MetadataBuildingContext buildingContext, MetadataBuildingContext buildingContext,

View File

@ -20,7 +20,7 @@
public class FetchProfile { public class FetchProfile {
private final String name; private final String name;
private final MetadataSource source; private final MetadataSource source;
private LinkedHashSet<Fetch> fetches = new LinkedHashSet<>(); private final LinkedHashSet<Fetch> fetches = new LinkedHashSet<>();
/** /**
* Create a fetch profile representation. * Create a fetch profile representation.

View File

@ -9,6 +9,7 @@
/** /**
* Any mapping with an outer-join attribute * Any mapping with an outer-join attribute
*
* @author Gavin King * @author Gavin King
*/ */
public interface Fetchable { public interface Fetchable {

View File

@ -25,7 +25,7 @@ public class ForeignKey extends Constraint {
private String referencedEntityName; private String referencedEntityName;
private String keyDefinition; private String keyDefinition;
private boolean cascadeDeleteEnabled; private boolean cascadeDeleteEnabled;
private List<Column> referencedColumns = new ArrayList<>(); private final List<Column> referencedColumns = new ArrayList<>();
private boolean creationEnabled = true; private boolean creationEnabled = true;
public ForeignKey() { public ForeignKey() {
@ -73,10 +73,10 @@ public String sqlConstraintString(
referencedColumnItr = referencedColumns.iterator(); referencedColumnItr = referencedColumns.iterator();
} }
Iterator columnItr = getColumnIterator(); Iterator<Column> columnItr = getColumnIterator();
int i = 0; int i = 0;
while ( columnItr.hasNext() ) { while ( columnItr.hasNext() ) {
columnNames[i] = ( (Column) columnItr.next() ).getQuotedName( dialect ); columnNames[i] = columnItr.next().getQuotedName( dialect );
referencedColumnNames[i] = referencedColumnItr.next().getQuotedName( dialect ); referencedColumnNames[i] = referencedColumnItr.next().getQuotedName( dialect );
i++; i++;
} }
@ -105,9 +105,9 @@ public Table getReferencedTable() {
return referencedTable; return referencedTable;
} }
private void appendColumns(StringBuilder buf, Iterator columns) { private void appendColumns(StringBuilder buf, Iterator<Column> columns) {
while ( columns.hasNext() ) { while ( columns.hasNext() ) {
Column column = (Column) columns.next(); Column column = columns.next();
buf.append( column.getName() ); buf.append( column.getName() );
if ( columns.hasNext() ) { if ( columns.hasNext() ) {
buf.append( "," ); buf.append( "," );
@ -149,10 +149,10 @@ private void alignColumns(Table referencedTable) {
throw new MappingException( sb.toString() ); throw new MappingException( sb.toString() );
} }
Iterator fkCols = getColumnIterator(); Iterator<Column> fkCols = getColumnIterator();
Iterator pkCols = referencedTable.getPrimaryKey().getColumnIterator(); Iterator<Column> pkCols = referencedTable.getPrimaryKey().getColumnIterator();
while ( pkCols.hasNext() ) { while ( pkCols.hasNext() ) {
( (Column) fkCols.next() ).setLength( ( (Column) pkCols.next() ).getLength() ); fkCols.next().setLength( pkCols.next().getLength() );
} }
} }
@ -207,7 +207,7 @@ && getTable().isPhysicalTable()
/** /**
* Returns the referenced columns if the foreignkey does not refer to the primary key * Returns the referenced columns if the foreignkey does not refer to the primary key
*/ */
public List getReferencedColumns() { public List<Column> getReferencedColumns() {
return referencedColumns; return referencedColumns;
} }
@ -218,9 +218,9 @@ public boolean isReferenceToPrimaryKey() {
return referencedColumns.isEmpty(); return referencedColumns.isEmpty();
} }
public void addReferencedColumns(Iterator referencedColumnsIterator) { public void addReferencedColumns(Iterator<Column> referencedColumnsIterator) {
while ( referencedColumnsIterator.hasNext() ) { while ( referencedColumnsIterator.hasNext() ) {
Selectable col = (Selectable) referencedColumnsIterator.next(); Selectable col = referencedColumnsIterator.next();
if ( !col.isFormula() ) { if ( !col.isFormula() ) {
addReferencedColumn( (Column) col ); addReferencedColumn( (Column) col );
} }

View File

@ -55,7 +55,7 @@ public boolean isSame(IdentifierCollection other) {
void createPrimaryKey() { void createPrimaryKey() {
if ( !isOneToMany() ) { if ( !isOneToMany() ) {
PrimaryKey pk = new PrimaryKey( getCollectionTable() ); PrimaryKey pk = new PrimaryKey( getCollectionTable() );
pk.addColumns( getIdentifier().getColumnIterator() ); pk.addColumns( getIdentifier() );
getCollectionTable().setPrimaryKey(pk); getCollectionTable().setPrimaryKey(pk);
} }
// create an index on the key columns?? // create an index on the key columns??

View File

@ -58,23 +58,21 @@ public boolean isSame(IndexedCollection other) {
void createPrimaryKey() { void createPrimaryKey() {
if ( !isOneToMany() ) { if ( !isOneToMany() ) {
PrimaryKey pk = new PrimaryKey( getCollectionTable() ); PrimaryKey pk = new PrimaryKey( getCollectionTable() );
pk.addColumns( getKey().getColumnIterator() ); pk.addColumns( getKey() );
// index should be last column listed // index should be last column listed
boolean indexIsPartOfElement = false; boolean indexIsPartOfElement = false;
final Iterator<Selectable> iter = getIndex().getColumnIterator(); for ( Selectable selectable: getIndex().getSelectables() ) {
while ( iter.hasNext() ) {
final Selectable selectable = iter.next();
if ( selectable.isFormula() || !getCollectionTable().containsColumn( (Column) selectable ) ) { if ( selectable.isFormula() || !getCollectionTable().containsColumn( (Column) selectable ) ) {
indexIsPartOfElement = true; indexIsPartOfElement = true;
} }
} }
if ( indexIsPartOfElement ) { if ( indexIsPartOfElement ) {
//if it is part of the element, use the element columns in the PK //if it is part of the element, use the element columns in the PK
pk.addColumns( getElement().getColumnIterator() ); pk.addColumns( getElement() );
} }
else { else {
pk.addColumns( getIndex().getColumnIterator() ); pk.addColumns( getIndex() );
} }
getCollectionTable().setPrimaryKey(pk); getCollectionTable().setPrimaryKey(pk);
} }

View File

@ -9,6 +9,7 @@
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle; import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle;
import org.hibernate.sql.Alias; import org.hibernate.sql.Alias;
@ -52,6 +53,15 @@ public void addMappedsuperclassProperty(Property prop) {
prop.setPersistentClass( getPersistentClass() ); prop.setPersistentClass( getPersistentClass() );
} }
public List<Property> getDeclaredProperties() {
return declaredProperties;
}
public List<Property> getProperties() {
return properties;
}
@Deprecated(since = "6.0")
public Iterator<Property> getDeclaredPropertyIterator() { public Iterator<Property> getDeclaredPropertyIterator() {
return declaredProperties.iterator(); return declaredProperties.iterator();
} }
@ -59,6 +69,8 @@ public Iterator<Property> getDeclaredPropertyIterator() {
public boolean containsProperty(Property prop) { public boolean containsProperty(Property prop) {
return properties.contains(prop); return properties.contains(prop);
} }
@Deprecated(since = "6.0")
public Iterator<Property> getPropertyIterator() { public Iterator<Property> getPropertyIterator() {
return properties.iterator(); return properties.iterator();
} }
@ -95,7 +107,7 @@ public void createPrimaryKey() {
pk.setName( PK_ALIAS.toAliasString( table.getName() ) ); pk.setName( PK_ALIAS.toAliasString( table.getName() ) );
table.setPrimaryKey(pk); table.setPrimaryKey(pk);
pk.addColumns( getKey().getColumnIterator() ); pk.addColumns( getKey() );
} }
public int getPropertySpan() { public int getPropertySpan() {

View File

@ -6,6 +6,7 @@
*/ */
package org.hibernate.mapping; package org.hibernate.mapping;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataBuildingContext;
@ -52,10 +53,15 @@ public void validate(Mapping mapping) throws MappingException {
} }
} }
@Deprecated
public Iterator<Property> getReferenceablePropertyIterator() { public Iterator<Property> getReferenceablePropertyIterator() {
return getPropertyIterator(); return getPropertyIterator();
} }
public List<Property> getReferenceableProperties() {
return getProperties();
}
public Object accept(PersistentClassVisitor mv) { public Object accept(PersistentClassVisitor mv) {
return mv.accept(this); return mv.accept(this);
} }

View File

@ -48,16 +48,21 @@ public Type getType() throws MappingException {
return resolvedType; return resolvedType;
} }
public void createForeignKey() throws MappingException { public void createForeignKey() {
// Ensure properties are sorted before we create a foreign key // Ensure properties are sorted before we create a foreign key
sortProperties(); sortProperties();
// the case of a foreign key to something other than the pk is handled in createPropertyRefConstraints // 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() ); createForeignKeyOfEntity( ( (EntityType) getType() ).getAssociatedEntityName() );
} }
} }
@Override
public void createUniqueKey() {
if ( !hasFormula() ) {
getTable().createUniqueKey( getConstraintColumns() );
}
}
public void createPropertyRefConstraints(Map persistentClasses) { public void createPropertyRefConstraints(Map persistentClasses) {
if (referencedPropertyName!=null) { if (referencedPropertyName!=null) {
@ -82,19 +87,12 @@ public void createPropertyRefConstraints(Map persistentClasses) {
} }
// todo : if "none" another option is to create the ForeignKey object still but to set its #disableCreation flag // todo : if "none" another option is to create the ForeignKey object still but to set its #disableCreation flag
if ( !hasFormula() && !"none".equals( getForeignKeyName() ) ) { 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( ForeignKey fk = getTable().createForeignKey(
getForeignKeyName(), getForeignKeyName(),
getConstraintColumns(), getConstraintColumns(),
( (EntityType) getType() ).getAssociatedEntityName(), ( (EntityType) getType() ).getAssociatedEntityName(),
getForeignKeyDefinition(), getForeignKeyDefinition(),
refColumns new ArrayList<>( property.getColumns() )
); );
fk.setCascadeDeleteEnabled(isCascadeDeleteEnabled() ); fk.setCascadeDeleteEnabled(isCascadeDeleteEnabled() );
} }

View File

@ -33,7 +33,7 @@ public class OneToMany implements Value {
public OneToMany(MetadataBuildingContext buildingContext, PersistentClass owner) throws MappingException { public OneToMany(MetadataBuildingContext buildingContext, PersistentClass owner) throws MappingException {
this.buildingContext = buildingContext; this.buildingContext = buildingContext;
this.referencingTable = ( owner == null ) ? null : owner.getTable(); this.referencingTable = owner == null ? null : owner.getTable();
} }
public MetadataBuildingContext getBuildingContext() { public MetadataBuildingContext getBuildingContext() {
@ -74,6 +74,11 @@ public void createForeignKey() {
// no foreign key element for a one-to-many // no foreign key element for a one-to-many
} }
@Override
public void createUniqueKey() {
}
@Deprecated
public Iterator<Selectable> getColumnIterator() { public Iterator<Selectable> getColumnIterator() {
return associatedClass.getKey().getColumnIterator(); return associatedClass.getKey().getColumnIterator();
} }
@ -83,6 +88,11 @@ public List<Selectable> getSelectables() {
return associatedClass.getKey().getSelectables(); return associatedClass.getKey().getSelectables();
} }
@Override
public List<Column> getColumns() {
return associatedClass.getKey().getColumns();
}
public int getColumnSpan() { public int getColumnSpan() {
return associatedClass.getKey().getColumnSpan(); return associatedClass.getKey().getColumnSpan();
} }
@ -150,8 +160,8 @@ public boolean isSame(Value other) {
public boolean isSame(OneToMany other) { public boolean isSame(OneToMany other) {
return Objects.equals( referencingTable, other.referencingTable ) return Objects.equals( referencingTable, other.referencingTable )
&& Objects.equals( referencedEntityName, other.referencedEntityName ) && Objects.equals( referencedEntityName, other.referencedEntityName )
&& Objects.equals( associatedClass, other.associatedClass ); && Objects.equals( associatedClass, other.associatedClass );
} }
public boolean[] getColumnInsertability() { public boolean[] getColumnInsertability() {

View File

@ -6,14 +6,12 @@
*/ */
package org.hibernate.mapping; package org.hibernate.mapping;
import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.boot.spi.MetadataImplementor;
import org.hibernate.type.EntityType; import org.hibernate.type.EntityType;
import org.hibernate.type.ForeignKeyDirection; import org.hibernate.type.ForeignKeyDirection;
import org.hibernate.type.Type; import org.hibernate.type.Type;
@ -28,7 +26,7 @@ public class OneToOne extends ToOne {
private ForeignKeyDirection foreignKeyType; private ForeignKeyDirection foreignKeyType;
private KeyValue identifier; private KeyValue identifier;
private String propertyName; private String propertyName;
private String entityName; private final String entityName;
private String mappedByProperty; private String mappedByProperty;
public OneToOne(MetadataBuildingContext buildingContext, Table table, PersistentClass owner) throws MappingException { public OneToOne(MetadataBuildingContext buildingContext, Table table, PersistentClass owner) throws MappingException {
@ -48,13 +46,9 @@ public void setPropertyName(String propertyName) {
public String getEntityName() { public String getEntityName() {
return entityName; return entityName;
} }
public void setEntityName(String propertyName) {
this.entityName = entityName==null ? null : entityName.intern();
}
public Type getType() throws MappingException { public Type getType() throws MappingException {
if ( getColumnIterator().hasNext() ) { if ( getColumnSpan()>0 ) {
return MappingHelper.specialOneToOne( return MappingHelper.specialOneToOne(
getReferencedEntityName(), getReferencedEntityName(),
getForeignKeyType(), getForeignKeyType(),
@ -95,20 +89,27 @@ public void createForeignKey() throws MappingException {
} }
@Override @Override
public List<Selectable> getSelectables() { public void createUniqueKey() {
if ( super.getSelectables().size() > 0 ) { if ( !hasFormula() && getColumnSpan()>0 ) {
return super.getSelectables(); getTable().createUniqueKey( getConstraintColumns() );
} }
return getConstraintColumns();
} }
public List getConstraintColumns() { @Override
ArrayList list = new ArrayList(); public List<Selectable> getVirtualSelectables() {
Iterator iter = identifier.getColumnIterator(); List<Selectable> selectables = super.getVirtualSelectables();
while ( iter.hasNext() ) { if ( selectables.isEmpty() ) {
list.add( iter.next() ); selectables = identifier.getSelectables();
} }
return list; return selectables;
}
public List<Column> getConstraintColumns() {
List<Column> columns = super.getColumns();
if ( columns.isEmpty() ) {
columns = identifier.getColumns();
}
return columns;
} }
@Override @Override

View File

@ -12,6 +12,7 @@
import java.util.Comparator; import java.util.Comparator;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.StringTokenizer; import java.util.StringTokenizer;
@ -25,6 +26,7 @@
import org.hibernate.internal.FilterConfiguration; import org.hibernate.internal.FilterConfiguration;
import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.JoinedIterator; import org.hibernate.internal.util.collections.JoinedIterator;
import org.hibernate.internal.util.collections.JoinedList;
import org.hibernate.internal.util.collections.SingletonIterator; import org.hibernate.internal.util.collections.SingletonIterator;
import org.hibernate.metamodel.RepresentationMode; import org.hibernate.metamodel.RepresentationMode;
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;
@ -58,8 +60,8 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl
private String discriminatorValue; private String discriminatorValue;
private boolean lazy; private boolean lazy;
private java.util.List<Property> properties = new ArrayList<>(); private final java.util.List<Property> properties = new ArrayList<>();
private java.util.List<Property> declaredProperties = new ArrayList<>(); private final java.util.List<Property> declaredProperties = new ArrayList<>();
private final java.util.List<Subclass> subclasses = new ArrayList<>(); private final java.util.List<Subclass> subclasses = new ArrayList<>();
private final java.util.List<Property> subclassProperties = new ArrayList<>(); private final java.util.List<Property> subclassProperties = new ArrayList<>();
private final java.util.List<Table> subclassTables = new ArrayList<>(); private final java.util.List<Table> subclassTables = new ArrayList<>();
@ -68,7 +70,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl
private int batchSize = -1; private int batchSize = -1;
private boolean selectBeforeUpdate; private boolean selectBeforeUpdate;
private java.util.Map metaAttributes; private java.util.Map metaAttributes;
private java.util.List<Join> joins = new ArrayList<>(); private final java.util.List<Join> joins = new ArrayList<>();
private final java.util.List<Join> subclassJoins = new ArrayList<>(); private final java.util.List<Join> subclassJoins = new ArrayList<>();
private final java.util.List<FilterConfiguration> filters = new ArrayList<>(); private final java.util.List<FilterConfiguration> filters = new ArrayList<>();
protected final Set<String> synchronizedTables = new HashSet<>(); protected final Set<String> synchronizedTables = new HashSet<>();
@ -89,8 +91,6 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl
private boolean customDeleteCallable; private boolean customDeleteCallable;
private ExecuteUpdateResultCheckStyle deleteCheckStyle; private ExecuteUpdateResultCheckStyle deleteCheckStyle;
private java.util.Map tuplizerImpls;
private MappedSuperclass superMappedSuperclass; private MappedSuperclass superMappedSuperclass;
private Component declaredIdentifierMapper; private Component declaredIdentifierMapper;
private OptimisticLockStyle optimisticLockStyle; private OptimisticLockStyle optimisticLockStyle;
@ -218,6 +218,7 @@ public int getSubclassSpan() {
* first. * first.
*/ */
public Iterator<Subclass> getSubclassIterator() { public Iterator<Subclass> getSubclassIterator() {
@SuppressWarnings("unchecked")
Iterator<Subclass>[] iters = new Iterator[subclasses.size() + 1]; Iterator<Subclass>[] iters = new Iterator[subclasses.size() + 1];
Iterator<Subclass> iter = subclasses.iterator(); Iterator<Subclass> iter = subclasses.iterator();
int i = 0; int i = 0;
@ -317,6 +318,9 @@ public void setCachingExplicitlyRequested(boolean cached) {
public abstract boolean isDiscriminatorInsertable(); public abstract boolean isDiscriminatorInsertable();
public abstract List<Property> getPropertyClosure();
@Deprecated(since = "6.0")
public abstract Iterator<Property> getPropertyClosureIterator(); public abstract Iterator<Property> getPropertyClosureIterator();
public abstract Iterator<Table> getTableClosureIterator(); public abstract Iterator<Table> getTableClosureIterator();
@ -335,17 +339,27 @@ protected void addSubclassTable(Table subclassTable) {
subclassTables.add( subclassTable ); subclassTables.add( subclassTable );
} }
@Deprecated(since = "6.0")
public Iterator<Property> getSubclassPropertyClosureIterator() { public Iterator<Property> getSubclassPropertyClosureIterator() {
ArrayList<Iterator<Property>> iters = new ArrayList<>(); ArrayList<Iterator<Property>> iters = new ArrayList<>();
iters.add( getPropertyClosureIterator() ); iters.add( getPropertyClosureIterator() );
iters.add( subclassProperties.iterator() ); iters.add( subclassProperties.iterator() );
for ( int i = 0; i < subclassJoins.size(); i++ ) { for (Join join : subclassJoins) {
Join join = subclassJoins.get( i );
iters.add( join.getPropertyIterator() ); iters.add( join.getPropertyIterator() );
} }
return new JoinedIterator<>( iters ); return new JoinedIterator<>( iters );
} }
public List<Property> getSubclassPropertyClosure() {
ArrayList<List<Property>> lists = new ArrayList<>();
lists.add( getPropertyClosure() );
lists.add( subclassProperties );
for (Join join : subclassJoins) {
lists.add( join.getProperties() );
}
return new JoinedList<>( lists );
}
public Iterator<Join> getSubclassJoinClosureIterator() { public Iterator<Join> getSubclassJoinClosureIterator() {
return new JoinedIterator<>( getJoinClosureIterator(), subclassJoins.iterator() ); return new JoinedIterator<>( getJoinClosureIterator(), subclassJoins.iterator() );
} }
@ -397,7 +411,7 @@ public void createPrimaryKey() {
pk.setName( PK_ALIAS.toAliasString( table.getName() ) ); pk.setName( PK_ALIAS.toAliasString( table.getName() ) );
table.setPrimaryKey( pk ); table.setPrimaryKey( pk );
pk.addColumns( getKey().getColumnIterator() ); pk.addColumns( getKey() );
} }
public abstract String getWhere(); public abstract String getWhere();
@ -425,12 +439,29 @@ public void setSelectBeforeUpdate(boolean selectBeforeUpdate) {
* Includes all properties defined as part of a join. * Includes all properties defined as part of a join.
* *
* @see #getReferencedProperty for a discussion of "referenceable" * @see #getReferencedProperty for a discussion of "referenceable"
*
* @return The referenceable property iterator. * @return The referenceable property iterator.
*
* @deprecated use {@link #getReferenceableProperties()}
*/ */
@Deprecated(since = "6.0")
public Iterator<Property> getReferenceablePropertyIterator() { public Iterator<Property> getReferenceablePropertyIterator() {
return getPropertyClosureIterator(); return getPropertyClosureIterator();
} }
/**
* Build a list of properties which may be referenced in association mappings.
* <p>
* 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<Property> getReferenceableProperties() {
return getPropertyClosure();
}
/** /**
* Given a property path, locate the appropriate referenceable property reference. * Given a property path, locate the appropriate referenceable property reference.
* <p/> * <p/>
@ -445,7 +476,7 @@ public Iterator<Property> getReferenceablePropertyIterator() {
*/ */
public Property getReferencedProperty(String propertyPath) throws MappingException { public Property getReferencedProperty(String propertyPath) throws MappingException {
try { try {
return getRecursiveProperty( propertyPath, getReferenceablePropertyIterator() ); return getRecursiveProperty( propertyPath, getReferenceableProperties() );
} }
catch (MappingException e) { catch (MappingException e) {
throw new MappingException( throw new MappingException(
@ -456,7 +487,7 @@ public Property getReferencedProperty(String propertyPath) throws MappingExcepti
public Property getRecursiveProperty(String propertyPath) throws MappingException { public Property getRecursiveProperty(String propertyPath) throws MappingException {
try { try {
return getRecursiveProperty( propertyPath, getPropertyClosureIterator() ); return getRecursiveProperty( propertyPath, getPropertyClosure() );
} }
catch (MappingException e) { catch (MappingException e) {
throw new MappingException( throw new MappingException(
@ -465,7 +496,7 @@ public Property getRecursiveProperty(String propertyPath) throws MappingExceptio
} }
} }
private Property getRecursiveProperty(String propertyPath, Iterator<Property> iter) throws MappingException { private Property getRecursiveProperty(String propertyPath, List<Property> iter) throws MappingException {
Property property = null; Property property = null;
StringTokenizer st = new StringTokenizer( propertyPath, ".", false ); StringTokenizer st = new StringTokenizer( propertyPath, ".", false );
try { try {
@ -482,12 +513,10 @@ private Property getRecursiveProperty(String propertyPath, Iterator<Property> it
else if ( identifierProperty == null && getIdentifierMapper() != null ) { else if ( identifierProperty == null && getIdentifierMapper() != null ) {
// we have an embedded composite identifier // we have an embedded composite identifier
try { try {
identifierProperty = getProperty( element, getIdentifierMapper().getPropertyIterator() ); identifierProperty = getProperty( element, getIdentifierMapper().getProperties() );
if ( identifierProperty != null ) { // the root of the incoming property path matched one
// the root of the incoming property path matched one // of the embedded composite identifier properties
// of the embedded composite identifier properties property = identifierProperty;
property = identifierProperty;
}
} }
catch (MappingException ignore) { catch (MappingException ignore) {
// ignore it... // ignore it...
@ -511,16 +540,13 @@ else if ( identifierProperty == null && getIdentifierMapper() != null ) {
return property; return property;
} }
private Property getProperty(String propertyName, Iterator<Property> iterator) throws MappingException { private Property getProperty(String propertyName, List<Property> properties) throws MappingException {
if ( iterator.hasNext() ) { String root = StringHelper.root( propertyName );
String root = StringHelper.root( propertyName ); for ( Property prop : properties ) {
while ( iterator.hasNext() ) { if ( prop.getName().equals( root )
Property prop = iterator.next(); || ( prop instanceof Backref || prop instanceof IndexBackref )
if ( prop.getName().equals( root ) && prop.getName().equals( propertyName ) ) {
|| (prop instanceof Backref || prop instanceof IndexBackref) return prop;
&& prop.getName().equals( propertyName ) ) {
return prop;
}
} }
} }
throw new MappingException( "property [" + propertyName + "] not found on entity [" + getEntityName() + "]" ); throw new MappingException( "property [" + propertyName + "] not found on entity [" + getEntityName() + "]" );
@ -533,12 +559,12 @@ public Property getProperty(String propertyName) throws MappingException {
return identifierProperty; return identifierProperty;
} }
else { else {
Iterator<Property> iter = getPropertyClosureIterator(); List<Property> closure = getPropertyClosure();
Component identifierMapper = getIdentifierMapper(); Component identifierMapper = getIdentifierMapper();
if ( identifierMapper != null ) { 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 Property getSubclassProperty(String propertyName) throws MappingException
return identifierProperty; return identifierProperty;
} }
else { else {
Iterator<Property> iter = getSubclassPropertyClosureIterator(); List<Property> closure = getSubclassPropertyClosure();
Component identifierMapper = getIdentifierMapper(); Component identifierMapper = getIdentifierMapper();
if ( identifierMapper != null ) { 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 boolean isPropertyDefinedInSuperHierarchy(String name) {
* @return {@code true} if a property with that name exists; {@code false} if not * @return {@code true} if a property with that name exists; {@code false} if not
*/ */
public boolean isPropertyDefinedInHierarchy(String name) { public boolean isPropertyDefinedInHierarchy(String name) {
if ( hasProperty( name ) ) { return hasProperty( name )
return true; || getSuperMappedSuperclass() != null && getSuperMappedSuperclass().isPropertyDefinedInHierarchy( name )
} ||getSuperclass() != null && getSuperclass().isPropertyDefinedInHierarchy(name);
if ( getSuperMappedSuperclass() != null
&& getSuperMappedSuperclass().isPropertyDefinedInHierarchy( name ) ) {
return true;
}
if ( getSuperclass() != null
&& getSuperclass().isPropertyDefinedInHierarchy( name ) ) {
return true;
}
return false;
} }
/** /**
@ -648,9 +662,7 @@ public void setOptimisticLockStyle(OptimisticLockStyle optimisticLockStyle) {
} }
public void validate(Mapping mapping) throws MappingException { public void validate(Mapping mapping) throws MappingException {
Iterator<Property> iter = getPropertyIterator(); for ( Property prop : getProperties() ) {
while ( iter.hasNext() ) {
Property prop = iter.next();
if ( !prop.isValid( mapping ) ) { if ( !prop.isValid( mapping ) ) {
throw new MappingException( throw new MappingException(
"property mapping has wrong number of columns: " + "property mapping has wrong number of columns: " +
@ -666,9 +678,7 @@ public void validate(Mapping mapping) throws MappingException {
private void checkPropertyDuplication() throws MappingException { private void checkPropertyDuplication() throws MappingException {
HashSet<String> names = new HashSet<>(); HashSet<String> names = new HashSet<>();
Iterator<Property> iter = getPropertyIterator(); for ( Property prop : getProperties() ) {
while ( iter.hasNext() ) {
Property prop = iter.next();
if ( !names.add( prop.getName() ) ) { if ( !names.add( prop.getName() ) ) {
throw new MappingException( "Duplicate property mapping of " + prop.getName() + " found in " + getEntityName() ); throw new MappingException( "Duplicate property mapping of " + prop.getName() + " found in " + getEntityName() );
} }
@ -756,24 +766,46 @@ public int getJoinNumber(Property prop) {
public Iterator<Property> getPropertyIterator() { public Iterator<Property> getPropertyIterator() {
ArrayList<Iterator<Property>> iterators = new ArrayList<>(); ArrayList<Iterator<Property>> iterators = new ArrayList<>();
iterators.add( properties.iterator() ); iterators.add( properties.iterator() );
for ( int i = 0; i < joins.size(); i++ ) { for (Join join : joins) {
Join join = joins.get( i );
iterators.add( join.getPropertyIterator() ); iterators.add( join.getPropertyIterator() );
} }
return new JoinedIterator<>( iterators ); return new JoinedIterator<>( iterators );
} }
public List<Property> getProperties() {
ArrayList<List<Property>> 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 <b>which * Build an iterator over the properties defined on this class <b>which
* are not defined as part of a join</b>. As with {@link #getPropertyIterator}, * are not defined as part of a join</b>. As with {@link #getPropertyIterator},
* the returned iterator only accounts for non-identifier properties. * the returned iterator only accounts for non-identifier properties.
* *
* @return An iterator over the non-joined "normal" properties. * @return An iterator over the non-joined "normal" properties.
*
* @deprecated use {@link #getUnjoinedProperties()}
*/ */
@Deprecated(since = "6.0")
public Iterator<Property> getUnjoinedPropertyIterator() { public Iterator<Property> getUnjoinedPropertyIterator() {
return properties.iterator(); return properties.iterator();
} }
/**
* Get a list of the properties defined on this class <b>which
* are not defined as part of a join</b>. As with {@link #getProperties},
* the returned iterator only accounts for non-identifier properties.
*
* @return An iterator over the non-joined "normal" properties.
*/
public List<Property> getUnjoinedProperties() {
return properties;
}
public void setCustomSqlInsert(CustomSql customSql) { public void setCustomSqlInsert(CustomSql customSql) {
if ( customSql != null ) { if ( customSql != null ) {
setCustomSQLInsert( setCustomSQLInsert(
@ -908,10 +940,12 @@ public void setAbstract(Boolean isAbstract) {
this.isAbstract = isAbstract; this.isAbstract = isAbstract;
} }
protected void checkColumnDuplication(Set<String> distinctColumns, Iterator<Selectable> columns) protected void checkColumnDuplication(Set<String> distinctColumns, Value value)
throws MappingException { throws MappingException {
while ( columns.hasNext() ) { if (value == null) {
Selectable columnOrFormula = columns.next(); return;
}
for ( Selectable columnOrFormula : value.getSelectables() ) {
if ( !columnOrFormula.isFormula() ) { if ( !columnOrFormula.isFormula() ) {
Column col = (Column) columnOrFormula; Column col = (Column) columnOrFormula;
if ( !distinctColumns.add( col.getName() ) ) { if ( !distinctColumns.add( col.getName() ) ) {
@ -927,26 +961,30 @@ protected void checkColumnDuplication(Set<String> distinctColumns, Iterator<Sele
} }
} }
protected void checkPropertyColumnDuplication(Set distinctColumns, Iterator properties) protected void checkPropertyColumnDuplication(Set<String> distinctColumns, List<Property> properties)
throws MappingException { throws MappingException {
while ( properties.hasNext() ) { for (Property prop : properties) {
Property prop = (Property) properties.next();
if ( prop.getValue() instanceof Component ) { //TODO: remove use of instanceof! if ( prop.getValue() instanceof Component ) { //TODO: remove use of instanceof!
Component component = (Component) prop.getValue(); Component component = (Component) prop.getValue();
checkPropertyColumnDuplication( distinctColumns, component.getPropertyIterator() ); checkPropertyColumnDuplication( distinctColumns, component.getProperties() );
} }
else { else {
if ( prop.isUpdateable() || prop.isInsertable() ) { if ( prop.isUpdateable() || prop.isInsertable() ) {
checkColumnDuplication( distinctColumns, prop.getColumnIterator() ); checkColumnDuplication( distinctColumns, prop.getValue() );
} }
} }
} }
} }
@Deprecated(since = "6.0")
protected Iterator<Property> getNonDuplicatedPropertyIterator() { protected Iterator<Property> getNonDuplicatedPropertyIterator() {
return getUnjoinedPropertyIterator(); return getUnjoinedPropertyIterator();
} }
protected List<Property> getNonDuplicatedProperties() {
return getUnjoinedProperties();
}
protected Iterator<Selectable> getDiscriminatorColumnIterator() { protected Iterator<Selectable> getDiscriminatorColumnIterator() {
return Collections.emptyIterator(); return Collections.emptyIterator();
} }
@ -956,16 +994,16 @@ protected void checkColumnDuplication() {
if ( getIdentifierMapper() == null ) { if ( getIdentifierMapper() == null ) {
//an identifier mapper => getKey will be included in the getNonDuplicatedPropertyIterator() //an identifier mapper => getKey will be included in the getNonDuplicatedPropertyIterator()
//and checked later, so it needs to be excluded //and checked later, so it needs to be excluded
checkColumnDuplication( cols, getKey().getColumnIterator() ); checkColumnDuplication( cols, getKey() );
} }
checkColumnDuplication( cols, getDiscriminatorColumnIterator() ); checkColumnDuplication( cols, getDiscriminator() );
checkPropertyColumnDuplication( cols, getNonDuplicatedPropertyIterator() ); checkPropertyColumnDuplication( cols, getNonDuplicatedProperties() );
Iterator<Join> iter = getJoinIterator(); Iterator<Join> iter = getJoinIterator();
while ( iter.hasNext() ) { while ( iter.hasNext() ) {
cols.clear(); cols.clear();
Join join = iter.next(); Join join = iter.next();
checkColumnDuplication( cols, join.getKey().getColumnIterator() ); checkColumnDuplication( cols, join.getKey() );
checkPropertyColumnDuplication( cols, join.getPropertyIterator() ); checkPropertyColumnDuplication( cols, join.getProperties() );
} }
} }
@ -1029,17 +1067,11 @@ public void setIdentifierMapper(Component handle) {
} }
public String getTuplizerImplClassName(RepresentationMode mode) { public String getTuplizerImplClassName(RepresentationMode mode) {
if ( tuplizerImpls == null ) { return null;
return null;
}
return (String) tuplizerImpls.get( mode );
} }
public java.util.Map getTuplizerMap() { public java.util.Map getTuplizerMap() {
if ( tuplizerImpls == null ) { return null;
return null;
}
return Collections.unmodifiableMap( tuplizerImpls );
} }
private Boolean hasNaturalId; private Boolean hasNaturalId;

View File

@ -77,10 +77,30 @@ public Type getType() throws MappingException {
public int getColumnSpan() { public int getColumnSpan() {
return value.getColumnSpan(); return value.getColumnSpan();
} }
/**
* @deprecated moving away from the use of {@link Iterator} as a return type
*/
@Deprecated(since = "6.0")
public Iterator<Selectable> getColumnIterator() { public Iterator<Selectable> getColumnIterator() {
return value.getColumnIterator(); return value.getColumnIterator();
} }
/**
* Delegates to {@link Value#getSelectables()}.
*/
public java.util.List<Selectable> getSelectables() {
return value.getSelectables();
}
/**
* Delegates to {@link Value#getColumns()}.
*
* @throws org.hibernate.AssertionFailure if the mapping involves formulas
*/
public java.util.List<Column> getColumns() {
return value.getColumns();
}
public String getName() { public String getName() {
return name; return name;
@ -104,9 +124,7 @@ public void resetUpdateable(boolean updateable) {
public void resetOptional(boolean optional) { public void resetOptional(boolean optional) {
setOptional(optional); setOptional(optional);
Iterator<Selectable> columnIterator = getValue().getColumnIterator(); for ( Selectable column: getValue().getSelectables() ) {
while ( columnIterator.hasNext() ) {
Selectable column = columnIterator.next();
if (column instanceof Column) { if (column instanceof Column) {
( (Column) column ).setNullable(optional); ( (Column) column ).setNullable(optional);
} }

View File

@ -8,6 +8,7 @@
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.Set; import java.util.Set;
import org.hibernate.MappingException; import org.hibernate.MappingException;
@ -125,11 +126,16 @@ public RootClass getRootClass() {
return this; return this;
} }
@Override @Override @Deprecated
public Iterator<Property> getPropertyClosureIterator() { public Iterator<Property> getPropertyClosureIterator() {
return getPropertyIterator(); return getPropertyIterator();
} }
@Override
public List<Property> getPropertyClosure() {
return getProperties();
}
@Override @Override
public Iterator<Table> getTableClosureIterator() { public Iterator<Table> getTableClosureIterator() {
return new SingletonIterator<>( getTable() ); return new SingletonIterator<>( getTable() );

View File

@ -6,7 +6,6 @@
*/ */
package org.hibernate.mapping; package org.hibernate.mapping;
import java.util.Iterator;
import java.util.function.Supplier; import java.util.function.Supplier;
import org.hibernate.MappingException; import org.hibernate.MappingException;
@ -71,10 +70,8 @@ public CollectionType getDefaultCollectionType() {
void createPrimaryKey() { void createPrimaryKey() {
if ( !isOneToMany() ) { if ( !isOneToMany() ) {
PrimaryKey pk = new PrimaryKey( getCollectionTable() ); PrimaryKey pk = new PrimaryKey( getCollectionTable() );
pk.addColumns( getKey().getColumnIterator() ); pk.addColumns( getKey() );
Iterator<?> iter = getElement().getColumnIterator(); for ( Selectable selectable : getElement().getSelectables() ) {
while ( iter.hasNext() ) {
Object selectable = iter.next();
if ( selectable instanceof Column ) { if ( selectable instanceof Column ) {
Column col = (Column) selectable; Column col = (Column) selectable;
if ( !col.isNullable() ) { if ( !col.isNullable() ) {
@ -85,18 +82,18 @@ void createPrimaryKey() {
} }
} }
} }
if ( pk.getColumnSpan() == getKey().getColumnSpan() ) { if ( pk.getColumnSpan() != getKey().getColumnSpan() ) {
getCollectionTable().setPrimaryKey( pk );
}
// else {
//for backward compatibility, allow a set with no not-null //for backward compatibility, allow a set with no not-null
//element columns, using all columns in the row locator SQL //element columns, using all columns in the row locator SQL
//TODO: create an implicit not null constraint on all cols? //TODO: create an implicit not null constraint on all cols?
} // }
else {
getCollectionTable().setPrimaryKey( pk );
}
} }
else { // else {
//create an index on the key columns?? //create an index on the key columns??
} // }
} }
public Object accept(ValueVisitor visitor) { public Object accept(ValueVisitor visitor) {

View File

@ -17,6 +17,7 @@
import java.util.Objects; import java.util.Objects;
import java.util.Properties; import java.util.Properties;
import org.hibernate.AssertionFailure;
import org.hibernate.FetchMode; import org.hibernate.FetchMode;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.TimeZoneStorageStrategy; import org.hibernate.TimeZoneStorageStrategy;
@ -70,7 +71,7 @@ public abstract class SimpleValue implements KeyValue {
public static final String DEFAULT_ID_GEN_STRATEGY = "assigned"; public static final String DEFAULT_ID_GEN_STRATEGY = "assigned";
private MetadataBuildingContext buildingContext; private final MetadataBuildingContext buildingContext;
private final MetadataImplementor metadata; private final MetadataImplementor metadata;
private final List<Selectable> columns = new ArrayList<>(); private final List<Selectable> columns = new ArrayList<>();
@ -187,10 +188,8 @@ public void sortColumns(int[] originalOrder) {
@Override @Override
public boolean hasFormula() { public boolean hasFormula() {
Iterator iter = getColumnIterator(); for ( Selectable selectable : getSelectables() ) {
while ( iter.hasNext() ) { if ( selectable instanceof Formula ) {
Object o = iter.next();
if (o instanceof Formula) {
return true; return true;
} }
} }
@ -206,7 +205,7 @@ protected Selectable getColumn(int position){
return columns.get( position ); return columns.get( position );
} }
@Override @Override @Deprecated
public Iterator<Selectable> getColumnIterator() { public Iterator<Selectable> getColumnIterator() {
return columns.iterator(); return columns.iterator();
} }
@ -216,8 +215,15 @@ public List<Selectable> getSelectables() {
return columns; return columns;
} }
public List getConstraintColumns() { @Override
return columns; public List<Column> 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<Selectable> getConstraintColumnIterator() { public Iterator<Selectable> getConstraintColumnIterator() {
@ -236,7 +242,7 @@ public void setTypeName(String typeName) {
.getServiceRegistry() .getServiceRegistry()
.getService( ClassLoaderService.class ); .getService( ClassLoaderService.class );
try { try {
final Class<? extends AttributeConverter> converterClass = cls.classForName( converterClassName ); final Class<? extends AttributeConverter<?,?>> converterClass = cls.classForName( converterClassName );
this.attributeConverterDescriptor = new ClassBasedConverterDescriptor( this.attributeConverterDescriptor = new ClassBasedConverterDescriptor(
converterClass, converterClass,
false, false,
@ -285,12 +291,20 @@ public void createForeignKey() throws MappingException {}
@Override @Override
public void createForeignKeyOfEntity(String entityName) { public void createForeignKeyOfEntity(String entityName) {
if ( !hasFormula() && !"none".equals(getForeignKeyName())) { if ( !hasFormula() && !"none".equals( getForeignKeyName() ) ) {
ForeignKey fk = table.createForeignKey( getForeignKeyName(), getConstraintColumns(), entityName, getForeignKeyDefinition() ); table.createForeignKey( getForeignKeyName(), getConstraintColumns(), entityName, getForeignKeyDefinition() )
fk.setCascadeDeleteEnabled(cascadeDeleteEnabled); .setCascadeDeleteEnabled(cascadeDeleteEnabled);
} }
} }
@Override
public void createUniqueKey() {
if ( hasFormula() ) {
throw new MappingException( "unique key constraint involves formulas" );
}
getTable().createUniqueKey( getConstraintColumns() );
}
private IdentifierGeneratorCreator customIdGeneratorCreator; private IdentifierGeneratorCreator customIdGeneratorCreator;
private IdentifierGenerator identifierGenerator; private IdentifierGenerator identifierGenerator;
@ -395,7 +409,7 @@ public RootClass getRootClass() {
params.setProperty( PersistentIdentifierGenerator.TABLE, tableName ); params.setProperty( PersistentIdentifierGenerator.TABLE, tableName );
//pass the column name (a generated id almost always has a single column) //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 ); params.setProperty( PersistentIdentifierGenerator.PK, columnName );
//pass the entity-name, if not a collection-id //pass the entity-name, if not a collection-id
@ -485,7 +499,9 @@ public void setIdentifierGeneratorStrategy(String identifierGeneratorStrategy) {
} }
public boolean isIdentityColumn(IdentifierGeneratorFactory identifierGeneratorFactory, Dialect dialect) { public boolean isIdentityColumn(IdentifierGeneratorFactory identifierGeneratorFactory, Dialect dialect) {
return IdentityGenerator.class.isAssignableFrom(identifierGeneratorFactory.getIdentifierGeneratorClass( identifierGeneratorStrategy )); return IdentityGenerator.class.isAssignableFrom(
identifierGeneratorFactory.getIdentifierGeneratorClass( identifierGeneratorStrategy )
);
} }
public Properties getIdentifierGeneratorProperties() { public Properties getIdentifierGeneratorProperties() {
@ -553,9 +569,7 @@ public void setAlternateUniqueKey(boolean unique) {
} }
public boolean isNullable() { public boolean isNullable() {
Iterator itr = getColumnIterator(); for (Selectable selectable : getSelectables()) {
while ( itr.hasNext() ) {
final Object selectable = itr.next();
if ( selectable instanceof Formula ) { if ( selectable instanceof Formula ) {
// if there are *any* formulas, then the Value overall is // if there are *any* formulas, then the Value overall is
// considered nullable // considered nullable
@ -698,7 +712,6 @@ public void setTypeUsingReflection(String className, String propertyName) throws
* *
* @todo : see if we already have previously built a custom on-the-fly BasicType for this AttributeConverter; see note below about caching * @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() { private Type buildAttributeConverterTypeAdapter() {
// todo : validate the number of columns present here? // todo : validate the number of columns present here?
@ -721,7 +734,6 @@ public TypeConfiguration getTypeConfiguration() {
final BasicJavaType<?> domainJtd = (BasicJavaType<?>) jpaAttributeConverter.getDomainJavaType(); final BasicJavaType<?> domainJtd = (BasicJavaType<?>) jpaAttributeConverter.getDomainJavaType();
// build the SqlTypeDescriptor adapter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // build the SqlTypeDescriptor adapter ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Going back to the illustration, this should be a SqlTypeDescriptor that handles the Integer <-> String // 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 // conversions. This is the more complicated piece. First we need to determine the JDBC type code
@ -846,7 +858,7 @@ public boolean isSame(SimpleValue other) {
@Override @Override
public String toString() { public String toString() {
return getClass().getName() + '(' + columns.toString() + ')'; return getClass().getName() + '(' + columns + ')';
} }
public Object accept(ValueVisitor visitor) { public Object accept(ValueVisitor visitor) {
@ -937,7 +949,7 @@ protected void createParameterImpl() {
table.getCatalog(), table.getCatalog(),
table.getSchema(), table.getSchema(),
table.getName(), table.getName(),
Boolean.valueOf( typeParameters.getProperty( DynamicParameterizedType.IS_PRIMARY_KEY ) ), Boolean.parseBoolean( typeParameters.getProperty( DynamicParameterizedType.IS_PRIMARY_KEY ) ),
columnNames, columnNames,
columnLengths columnLengths
) )
@ -990,7 +1002,7 @@ public DynamicParameterizedType.ParameterType makeParameterImpl() {
private static final class ParameterTypeImpl implements DynamicParameterizedType.ParameterType { private static final class ParameterTypeImpl implements DynamicParameterizedType.ParameterType {
private final Class returnedClass; private final Class<?> returnedClass;
private final Annotation[] annotationsMethod; private final Annotation[] annotationsMethod;
private final String catalog; private final String catalog;
private final String schema; private final String schema;
@ -1000,7 +1012,7 @@ private static final class ParameterTypeImpl implements DynamicParameterizedType
private final Long[] columnLengths; private final Long[] columnLengths;
private ParameterTypeImpl( private ParameterTypeImpl(
Class returnedClass, Class<?> returnedClass,
Annotation[] annotationsMethod, Annotation[] annotationsMethod,
String catalog, String catalog,
String schema, String schema,
@ -1019,7 +1031,7 @@ private ParameterTypeImpl(
} }
@Override @Override
public Class getReturnedClass() { public Class<?> getReturnedClass() {
return returnedClass; return returnedClass;
} }

View File

@ -7,11 +7,13 @@
package org.hibernate.mapping; package org.hibernate.mapping;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.engine.spi.Mapping; import org.hibernate.engine.spi.Mapping;
import org.hibernate.internal.util.collections.JoinedIterator; import org.hibernate.internal.util.collections.JoinedIterator;
import org.hibernate.internal.util.collections.JoinedList;
/** /**
* @author Gavin King * @author Gavin King
@ -22,7 +24,7 @@ public SingleTableSubclass(PersistentClass superclass, MetadataBuildingContext m
super( superclass, metadataBuildingContext ); super( superclass, metadataBuildingContext );
} }
@SuppressWarnings("unchecked") @Deprecated
protected Iterator<Property> getNonDuplicatedPropertyIterator() { protected Iterator<Property> getNonDuplicatedPropertyIterator() {
return new JoinedIterator<>( return new JoinedIterator<>(
getSuperclass().getUnjoinedPropertyIterator(), getSuperclass().getUnjoinedPropertyIterator(),
@ -30,13 +32,14 @@ protected Iterator<Property> getNonDuplicatedPropertyIterator() {
); );
} }
protected List<Property> getNonDuplicatedProperties() {
return new JoinedList<>( getSuperclass().getUnjoinedProperties(), getUnjoinedProperties() );
}
protected Iterator<Selectable> getDiscriminatorColumnIterator() { protected Iterator<Selectable> getDiscriminatorColumnIterator() {
if ( isDiscriminatorInsertable() && !getDiscriminator().hasFormula() ) { return isDiscriminatorInsertable() && !getDiscriminator().hasFormula()
return getDiscriminator().getColumnIterator(); ? getDiscriminator().getColumnIterator()
} : super.getDiscriminatorColumnIterator();
else {
return super.getDiscriminatorColumnIterator();
}
} }
public Object accept(PersistentClassVisitor mv) { public Object accept(PersistentClassVisitor mv) {

View File

@ -6,9 +6,6 @@
*/ */
package org.hibernate.mapping; package org.hibernate.mapping;
/**
*
*/
public interface SortableValue { public interface SortableValue {
boolean isSorted(); boolean isSorted();

View File

@ -5,10 +5,12 @@
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/ */
package org.hibernate.mapping; package org.hibernate.mapping;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import java.util.Map; import java.util.Map;
import org.hibernate.AssertionFailure; import org.hibernate.AssertionFailure;
@ -16,6 +18,7 @@
import org.hibernate.engine.OptimisticLockStyle; import org.hibernate.engine.OptimisticLockStyle;
import org.hibernate.internal.FilterConfiguration; import org.hibernate.internal.FilterConfiguration;
import org.hibernate.internal.util.collections.JoinedIterator; import org.hibernate.internal.util.collections.JoinedIterator;
import org.hibernate.internal.util.collections.JoinedList;
import org.hibernate.internal.util.collections.SingletonIterator; import org.hibernate.internal.util.collections.SingletonIterator;
import org.hibernate.metamodel.RepresentationMode; import org.hibernate.metamodel.RepresentationMode;
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;
@ -102,12 +105,19 @@ public void addJoin(Join j) {
getSuperclass().addSubclassJoin(j); getSuperclass().addSubclassJoin(j);
} }
@Override
public List<Property> getPropertyClosure() {
return new JoinedList<>( getSuperclass().getPropertyClosure(), getProperties() );
}
@Deprecated
public Iterator<Property> getPropertyClosureIterator() { public Iterator<Property> getPropertyClosureIterator() {
return new JoinedIterator<>( return new JoinedIterator<>(
getSuperclass().getPropertyClosureIterator(), getSuperclass().getPropertyClosureIterator(),
getPropertyIterator() getPropertyIterator()
); );
} }
public Iterator<Table> getTableClosureIterator() { public Iterator<Table> getTableClosureIterator() {
return new JoinedIterator<>( return new JoinedIterator<>(
getSuperclass().getTableClosureIterator(), getSuperclass().getTableClosureIterator(),
@ -149,12 +159,9 @@ public boolean hasEmbeddedIdentifier() {
return getSuperclass().hasEmbeddedIdentifier(); return getSuperclass().hasEmbeddedIdentifier();
} }
public Class<? extends EntityPersister> getEntityPersisterClass() { public Class<? extends EntityPersister> getEntityPersisterClass() {
if (classPersisterClass==null) { return classPersisterClass == null
return getSuperclass().getEntityPersisterClass(); ? getSuperclass().getEntityPersisterClass()
} : classPersisterClass;
else {
return classPersisterClass;
}
} }
public Table getRootTable() { public Table getRootTable() {

View File

@ -9,6 +9,7 @@
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@ -38,7 +39,6 @@
* *
* @author Gavin King * @author Gavin King
*/ */
@SuppressWarnings("deprecation")
public class Table implements RelationalModel, Serializable, ContributableDatabaseObject { public class Table implements RelationalModel, Serializable, ContributableDatabaseObject {
private static final Logger log = Logger.getLogger( Table.class ); private static final Logger log = Logger.getLogger( Table.class );
private static final Column[] EMPTY_COLUMN_ARRAY = new Column[0]; 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 * contains all columns, including the primary key
*/ */
private Map<String, Column> columns = new LinkedHashMap<>(); private final Map<String, Column> columns = new LinkedHashMap<>();
private KeyValue idValue; private KeyValue idValue;
private PrimaryKey primaryKey; private PrimaryKey primaryKey;
private Map<ForeignKeyKey, ForeignKey> foreignKeys = new LinkedHashMap<>(); private final Map<ForeignKeyKey, ForeignKey> foreignKeys = new LinkedHashMap<>();
private Map<String, Index> indexes = new LinkedHashMap<>(); private final Map<String, Index> indexes = new LinkedHashMap<>();
private Map<String,UniqueKey> uniqueKeys = new LinkedHashMap<>(); private final Map<String,UniqueKey> uniqueKeys = new LinkedHashMap<>();
private int uniqueInteger; private int uniqueInteger;
private List<String> checkConstraints = new ArrayList<>(); private final List<String> checkConstraints = new ArrayList<>();
private String rowId; private String rowId;
private String subselect; private String subselect;
private boolean isAbstract; private boolean isAbstract;
@ -229,7 +229,7 @@ public Column getColumn(Column column) {
return null; return null;
} }
Column myColumn = (Column) columns.get( column.getCanonicalName() ); Column myColumn = columns.get( column.getCanonicalName() );
return column.equals( myColumn ) ? return column.equals( myColumn ) ?
myColumn : myColumn :
@ -241,7 +241,7 @@ public Column getColumn(Identifier name) {
return null; return null;
} }
return (Column) columns.get( name.getCanonicalName() ); return columns.get( name.getCanonicalName() );
} }
public Column getColumn(int n) { public Column getColumn(int n) {
@ -249,7 +249,7 @@ public Column getColumn(int n) {
for ( int i = 0; i < n - 1; i++ ) { for ( int i = 0; i < n - 1; i++ ) {
iter.next(); iter.next();
} }
return (Column) iter.next(); return iter.next();
} }
public void addColumn(Column column) { public void addColumn(Column column) {
@ -285,6 +285,10 @@ public Iterator<Column> getColumnIterator() {
return columns.values().iterator(); return columns.values().iterator();
} }
public Collection<Column> getColumns() {
return columns.values();
}
public Iterator<Index> getIndexIterator() { public Iterator<Index> getIndexIterator() {
return indexes.values().iterator(); return indexes.values().iterator();
} }
@ -425,7 +429,7 @@ public Iterator<String> sqlAlterStrings(
List<String> results = new ArrayList<>(); List<String> results = new ArrayList<>();
while ( iter.hasNext() ) { 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() ) ); final ColumnInformation columnInfo = tableInfo.getColumn( Identifier.toIdentifier( column.getName(), column.isQuoted() ) );
if ( columnInfo == null ) { if ( columnInfo == null ) {
@ -651,7 +655,9 @@ public UniqueKey addUniqueKey(UniqueKey uniqueKey) {
public UniqueKey createUniqueKey(List<Column> keyColumns) { public UniqueKey createUniqueKey(List<Column> keyColumns) {
String keyName = Constraint.generateName( "UK_", this, keyColumns ); String keyName = Constraint.generateName( "UK_", this, keyColumns );
UniqueKey uk = getOrCreateUniqueKey( keyName ); UniqueKey uk = getOrCreateUniqueKey( keyName );
uk.addColumns( keyColumns.iterator() ); for (Column keyColumn : keyColumns) {
uk.addColumn( keyColumn );
}
return uk; return uk;
} }
@ -691,8 +697,10 @@ public ForeignKey createForeignKey(
fk = new ForeignKey(); fk = new ForeignKey();
fk.setTable( this ); fk.setTable( this );
fk.setReferencedEntityName( referencedEntityName ); fk.setReferencedEntityName( referencedEntityName );
fk.setKeyDefinition(keyDefinition); fk.setKeyDefinition( keyDefinition );
fk.addColumns( keyColumns.iterator() ); for (Column keyColumn : keyColumns) {
fk.addColumn( keyColumn );
}
if ( referencedColumns != null ) { if ( referencedColumns != null ) {
fk.addReferencedColumns( referencedColumns.iterator() ); fk.addReferencedColumns( referencedColumns.iterator() );
} }

View File

@ -12,8 +12,6 @@
import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataBuildingContext;
import org.hibernate.engine.spi.Mapping; import org.hibernate.engine.spi.Mapping;
import org.hibernate.internal.util.ReflectHelper; import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.type.ComponentType;
import org.hibernate.type.Type;
import java.util.Objects; import java.util.Objects;
@ -44,9 +42,6 @@ public void setFetchMode(FetchMode fetchMode) {
this.fetchMode=fetchMode; this.fetchMode=fetchMode;
} }
public abstract void createForeignKey() throws MappingException;
public abstract Type getType() throws MappingException;
public String getReferencedPropertyName() { public String getReferencedPropertyName() {
return referencedPropertyName; return referencedPropertyName;
} }
@ -98,8 +93,8 @@ public boolean isSame(SimpleValue other) {
public boolean isSame(ToOne other) { public boolean isSame(ToOne other) {
return super.isSame( other ) return super.isSame( other )
&& Objects.equals( referencedPropertyName, other.referencedPropertyName ) && Objects.equals( referencedPropertyName, other.referencedPropertyName )
&& Objects.equals( referencedEntityName, other.referencedEntityName ); && Objects.equals( referencedEntityName, other.referencedEntityName );
} }
public boolean isValid(Mapping mapping) throws MappingException { public boolean isValid(Mapping mapping) throws MappingException {

View File

@ -6,6 +6,7 @@
*/ */
package org.hibernate.mapping; package org.hibernate.mapping;
import java.util.Iterator; import java.util.Iterator;
import java.util.List;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.boot.spi.MetadataBuildingContext; import org.hibernate.boot.spi.MetadataBuildingContext;
@ -35,11 +36,17 @@ public void setTable(Table table) {
public java.util.Set<String> getSynchronizedTables() { public java.util.Set<String> getSynchronizedTables() {
return synchronizedTables; return synchronizedTables;
} }
@Deprecated
protected Iterator<Property> getNonDuplicatedPropertyIterator() { protected Iterator<Property> getNonDuplicatedPropertyIterator() {
return getPropertyClosureIterator(); return getPropertyClosureIterator();
} }
@Override
protected List<Property> getNonDuplicatedProperties() {
return getPropertyClosure();
}
public void validate(Mapping mapping) throws MappingException { public void validate(Mapping mapping) throws MappingException {
super.validate(mapping); super.validate(mapping);
if ( key!=null && !key.isValid(mapping) ) { if ( key!=null && !key.isValid(mapping) ) {

View File

@ -17,8 +17,8 @@
import org.hibernate.type.Type; import org.hibernate.type.Type;
/** /**
* A value is anything that is persisted by value, instead of * A value is anything that is persisted by value, instead of by
* by reference. It is essentially a Hibernate Type, together * reference. It is essentially a Hibernate {@link Type}, together
* with zero or more columns. Values are wrapped by things with * with zero or more columns. Values are wrapped by things with
* higher level semantics, for example properties, collections, * higher level semantics, for example properties, collections,
* classes. * classes.
@ -26,20 +26,71 @@
* @author Gavin King * @author Gavin King
*/ */
public interface Value extends Serializable { public interface Value extends Serializable {
/**
* The number of columns and formulas in the mapping.
*/
int getColumnSpan(); int getColumnSpan();
/**
* @deprecated moving away from the use of {@link Iterator} as a return type
*/
@Deprecated(since = "6.0")
Iterator<Selectable> getColumnIterator(); Iterator<Selectable> getColumnIterator();
/**
* The mapping to columns and formulas.
*/
List<Selectable> getSelectables(); List<Selectable> getSelectables();
/**
* If the mapping involves only columns, return them.
*
* @throws org.hibernate.AssertionFailure if the mapping involves formulas
*/
List<Column> getColumns();
/**
* Same as {@link #getSelectables()} except it returns the PK for the
* non-owning side of a one-to-one association.
*/
default List<Selectable> 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<Column> getConstraintColumns() {
return getColumns();
}
Type getType() throws MappingException; Type getType() throws MappingException;
FetchMode getFetchMode(); FetchMode getFetchMode();
Table getTable(); Table getTable();
boolean hasFormula(); boolean hasFormula();
boolean isAlternateUniqueKey(); boolean isAlternateUniqueKey();
boolean isNullable(); boolean isNullable();
void createForeignKey() throws MappingException;
void createForeignKey();
void createUniqueKey();
boolean isSimpleValue(); boolean isSimpleValue();
boolean isValid(Mapping mapping) throws MappingException; boolean isValid(Mapping mapping) throws MappingException;
void setTypeUsingReflection(String className, String propertyName) throws MappingException; void setTypeUsingReflection(String className, String propertyName) throws MappingException;
Object accept(ValueVisitor visitor); Object accept(ValueVisitor visitor);
boolean isSame(Value other); boolean isSame(Value other);
boolean[] getColumnInsertability(); boolean[] getColumnInsertability();

View File

@ -6,7 +6,6 @@
*/ */
package org.hibernate.metamodel.internal; package org.hibernate.metamodel.internal;
import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@ -40,14 +39,12 @@ public AbstractEmbeddableRepresentationStrategy(
this.attributeNameToPositionMap = new ConcurrentHashMap<>( propertySpan ); this.attributeNameToPositionMap = new ConcurrentHashMap<>( propertySpan );
boolean foundCustomAccessor = false; boolean foundCustomAccessor = false;
Iterator itr = bootDescriptor.getPropertyIterator();
int i = 0; int i = 0;
while ( itr.hasNext() ) { for ( Property property : bootDescriptor.getProperties() ) {
final Property prop = ( Property ) itr.next(); propertyAccesses[i] = buildPropertyAccess( property );
propertyAccesses[i] = buildPropertyAccess( prop ); attributeNameToPositionMap.put( property.getName(), i );
attributeNameToPositionMap.put( prop.getName(), i );
if ( !prop.isBasicPropertyAccessor() ) { if ( !property.isBasicPropertyAccessor() ) {
foundCustomAccessor = true; foundCustomAccessor = true;
} }

View File

@ -251,7 +251,8 @@ public static <Y> DomainType<Y> determineSimpleType(ValueContext typeContext, Me
else { else {
// we should have a non-dynamic embeddable // we should have a non-dynamic embeddable
assert component.getComponentClassName() != null; assert component.getComponentClassName() != null;
final Class<Y> embeddableClass = component.getComponentClass(); @SuppressWarnings("unchecked")
final Class<Y> embeddableClass = (Class<Y>) component.getComponentClass();
final EmbeddableDomainType<Y> cached = context.locateEmbeddable( embeddableClass, component ); final EmbeddableDomainType<Y> cached = context.locateEmbeddable( embeddableClass, component );
if ( cached != null ) { if ( cached != null ) {
@ -274,9 +275,7 @@ public static <Y> DomainType<Y> determineSimpleType(ValueContext typeContext, Me
} }
final EmbeddableTypeImpl.InFlightAccess<Y> inFlightAccess = embeddableType.getInFlightAccess(); final EmbeddableTypeImpl.InFlightAccess<Y> inFlightAccess = embeddableType.getInFlightAccess();
final Iterator<Property> subProperties = component.getPropertyIterator(); for ( Property property : component.getProperties() ) {
while ( subProperties.hasNext() ) {
final Property property = subProperties.next();
final PersistentAttribute<Y, Y> attribute = buildAttribute( embeddableType, property, context ); final PersistentAttribute<Y, Y> attribute = buildAttribute( embeddableType, property, context );
if ( attribute != null ) { if ( attribute != null ) {
inFlightAccess.addAttribute( attribute ); inFlightAccess.addAttribute( attribute );

View File

@ -113,7 +113,8 @@ public EntityRepresentationStrategyPojoStandard(
if ( bootDescriptor.getIdentifierMapper() != null ) { if ( bootDescriptor.getIdentifierMapper() != null ) {
mapsIdRepresentationStrategy = new EmbeddableRepresentationStrategyPojo( mapsIdRepresentationStrategy = new EmbeddableRepresentationStrategyPojo(
bootDescriptor.getIdentifierMapper(), bootDescriptor.getIdentifierMapper(),
() -> ( ( CompositeTypeImplementor) bootDescriptor.getIdentifierMapper().getType() ).getMappingModelPart().getEmbeddableTypeDescriptor(), () -> ( ( CompositeTypeImplementor) bootDescriptor.getIdentifierMapper().getType() )
.getMappingModelPart().getEmbeddableTypeDescriptor(),
// we currently do not support custom instantiators for identifiers // we currently do not support custom instantiators for identifiers
null, null,
creationContext creationContext
@ -122,7 +123,8 @@ public EntityRepresentationStrategyPojoStandard(
else if ( bootDescriptorIdentifier != null ) { else if ( bootDescriptorIdentifier != null ) {
mapsIdRepresentationStrategy = new EmbeddableRepresentationStrategyPojo( mapsIdRepresentationStrategy = new EmbeddableRepresentationStrategyPojo(
(Component) bootDescriptorIdentifier, (Component) bootDescriptorIdentifier,
() -> ( ( CompositeTypeImplementor) bootDescriptor.getIdentifierMapper().getType() ).getMappingModelPart().getEmbeddableTypeDescriptor(), () -> ( ( CompositeTypeImplementor) bootDescriptor.getIdentifierMapper().getType() )
.getMappingModelPart().getEmbeddableTypeDescriptor(),
// we currently do not support custom instantiators for identifiers // we currently do not support custom instantiators for identifiers
null, null,
creationContext creationContext
@ -223,14 +225,11 @@ private ProxyFactory createProxyFactory(
proxyInterfaces.add( HibernateProxy.class ); proxyInterfaces.add( HibernateProxy.class );
Iterator<?> properties = bootDescriptor.getPropertyIterator();
Class<?> clazz = bootDescriptor.getMappedClass(); Class<?> clazz = bootDescriptor.getMappedClass();
final Method idGetterMethod; final Method idGetterMethod;
final Method idSetterMethod; final Method idSetterMethod;
try { try {
while ( properties.hasNext() ) { for ( Property property : bootDescriptor.getProperties() ) {
Property property = (Property) properties.next();
ProxyFactoryHelper.validateGetterSetterMethodProxyability( ProxyFactoryHelper.validateGetterSetterMethodProxyability(
"Getter", "Getter",
property.getGetter( clazz ).getMethod() property.getGetter( clazz ).getMethod()

View File

@ -256,7 +256,8 @@ public void wrapUp() {
LOG.trace( "Wrapping up metadata context..." ); 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 //we need to process types from superclasses to subclasses
for ( Object mapping : orderedMappings ) { for ( Object mapping : orderedMappings ) {
@ -266,7 +267,8 @@ public void wrapUp() {
LOG.trace( "Starting entity [" + safeMapping.getEntityName() + ']' ); LOG.trace( "Starting entity [" + safeMapping.getEntityName() + ']' );
} }
try { try {
final EntityDomainType<Object> jpaMapping = (EntityDomainType<Object>) entityTypesByPersistentClass.get( safeMapping ); final EntityDomainType<Object> jpaMapping = (EntityDomainType<Object>)
entityTypesByPersistentClass.get( safeMapping );
applyIdMetadata( safeMapping, jpaMapping ); applyIdMetadata( safeMapping, jpaMapping );
applyVersionAttribute( safeMapping, jpaMapping ); applyVersionAttribute( safeMapping, jpaMapping );
@ -315,7 +317,8 @@ else if ( MappedSuperclass.class.isAssignableFrom( mapping.getClass() ) ) {
LOG.trace( "Starting mapped superclass [" + safeMapping.getMappedClass().getName() + ']' ); LOG.trace( "Starting mapped superclass [" + safeMapping.getMappedClass().getName() + ']' );
} }
try { try {
final MappedSuperclassDomainType<Object> jpaType = (MappedSuperclassDomainType<Object>) mappedSuperclassByMappedSuperclassMapping.get( safeMapping ); final MappedSuperclassDomainType<Object> jpaType = (MappedSuperclassDomainType<Object>)
mappedSuperclassByMappedSuperclassMapping.get( safeMapping );
applyIdMetadata( safeMapping, jpaType ); applyIdMetadata( safeMapping, jpaType );
applyVersionAttribute( safeMapping, jpaType ); applyVersionAttribute( safeMapping, jpaType );
@ -366,10 +369,9 @@ else if ( MappedSuperclass.class.isAssignableFrom( mapping.getClass() ) ) {
for ( EmbeddableDomainType<?> embeddable : processingEmbeddables ) { for ( EmbeddableDomainType<?> embeddable : processingEmbeddables ) {
final Component component = componentByEmbeddable.get( embeddable ); final Component component = componentByEmbeddable.get( embeddable );
final Iterator<Property> propertyItr = component.getPropertyIterator(); for ( Property property : component.getProperties() ) {
while ( propertyItr.hasNext() ) { final PersistentAttribute<Object, ?> attribute =
final Property property = propertyItr.next(); attributeFactory.buildAttribute( (ManagedDomainType<Object>) embeddable, property );
final PersistentAttribute<Object, ?> attribute = attributeFactory.buildAttribute( (ManagedDomainType<Object>) embeddable, property );
if ( attribute != null ) { if ( attribute != null ) {
addAttribute( embeddable, attribute ); addAttribute( embeddable, attribute );
} }
@ -386,16 +388,19 @@ else if ( MappedSuperclass.class.isAssignableFrom( mapping.getClass() ) ) {
} }
private void addAttribute(ManagedDomainType<?> type, PersistentAttribute<Object, ?> attribute) { private void addAttribute(ManagedDomainType<?> type, PersistentAttribute<Object, ?> attribute) {
final AttributeContainer.InFlightAccess<Object> inFlightAccess = ( (AttributeContainer<Object>) type ).getInFlightAccess(); //noinspection unchecked
AttributeContainer<Object> container = (AttributeContainer<Object>) type;
final AttributeContainer.InFlightAccess<Object> inFlightAccess = container.getInFlightAccess();
final boolean virtual = attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED final boolean virtual = attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED
&& attribute.getAttributeJavaType() instanceof EntityJavaType<?>; && attribute.getAttributeJavaType() instanceof EntityJavaType<?>;
if ( virtual ) { if ( virtual ) {
final EmbeddableDomainType<?> embeddableDomainType = (EmbeddableDomainType<?>) attribute.getValueGraphType(); final EmbeddableDomainType<?> embeddableDomainType = (EmbeddableDomainType<?>) attribute.getValueGraphType();
final Component component = componentByEmbeddable.get( embeddableDomainType ); final Component component = componentByEmbeddable.get( embeddableDomainType );
final Iterator<Property> propertyItr = component.getPropertyIterator(); for ( Property property : component.getProperties() ) {
while ( propertyItr.hasNext() ) { //noinspection unchecked
final Property property = propertyItr.next(); ManagedDomainType<Object> managedDomainType = (ManagedDomainType<Object>) embeddableDomainType;
final PersistentAttribute<Object, ?> subAttribute = attributeFactory.buildAttribute( (ManagedDomainType<Object>) embeddableDomainType, property ); final PersistentAttribute<Object, ?> subAttribute =
attributeFactory.buildAttribute( managedDomainType, property );
if ( subAttribute != null ) { if ( subAttribute != null ) {
inFlightAccess.addAttribute( subAttribute ); inFlightAccess.addAttribute( subAttribute );
} }
@ -411,7 +416,6 @@ private void addAttribute(ManagedDomainType<?> type, PersistentAttribute<Object,
// 2) register the part (mapping role) // 2) register the part (mapping role)
// 3) somehow get the mapping role "into" the part (setter, ?) // 3) somehow get the mapping role "into" the part (setter, ?)
@SuppressWarnings({"unchecked", "rawtypes"})
private void applyIdMetadata(PersistentClass persistentClass, IdentifiableDomainType<?> identifiableType) { private void applyIdMetadata(PersistentClass persistentClass, IdentifiableDomainType<?> identifiableType) {
if ( persistentClass.hasIdentifierProperty() ) { if ( persistentClass.hasIdentifierProperty() ) {
final Property declaredIdentifierProperty = persistentClass.getDeclaredIdentifierProperty(); final Property declaredIdentifierProperty = persistentClass.getDeclaredIdentifierProperty();
@ -421,53 +425,54 @@ private void applyIdMetadata(PersistentClass persistentClass, IdentifiableDomain
declaredIdentifierProperty declaredIdentifierProperty
); );
//noinspection unchecked rawtypes
( ( AttributeContainer) identifiableType ).getInFlightAccess().applyIdAttribute( idAttribute ); ( ( AttributeContainer) identifiableType ).getInFlightAccess().applyIdAttribute( idAttribute );
} }
} }
else { else {
// we have a non-aggregated composite-id // we have a non-aggregated composite-id
//noinspection RedundantClassCall if ( !(persistentClass.getIdentifier() instanceof Component) ) {
if ( ! Component.class.isInstance( persistentClass.getIdentifier() ) ) {
throw new MappingException( "Expecting Component for id mapping with no id-attribute" ); throw new MappingException( "Expecting Component for id mapping with no id-attribute" );
} }
// Handle the actual id-attributes // Handle the actual id-attributes
final Component cidValue = (Component) persistentClass.getIdentifier(); final Component cidValue = (Component) persistentClass.getIdentifier();
final Iterator<Property> cidPropertyItr; final List<Property> cidProperties;
final int propertySpan; final int propertySpan;
final EmbeddableTypeImpl<?> idClassType; final EmbeddableTypeImpl<?> idClassType;
final Component identifierMapper = persistentClass.getIdentifierMapper(); final Component identifierMapper = persistentClass.getIdentifierMapper();
if ( identifierMapper != null ) { if ( identifierMapper != null ) {
cidPropertyItr = identifierMapper.getPropertyIterator(); cidProperties = identifierMapper.getProperties();
propertySpan = identifierMapper.getPropertySpan(); propertySpan = identifierMapper.getPropertySpan();
idClassType = applyIdClassMetadata( (Component) persistentClass.getIdentifier() ); idClassType = applyIdClassMetadata( (Component) persistentClass.getIdentifier() );
} }
else { else {
cidPropertyItr = cidValue.getPropertyIterator(); cidProperties = cidValue.getProperties();
propertySpan = cidValue.getPropertySpan(); propertySpan = cidValue.getPropertySpan();
idClassType = null; idClassType = null;
} }
assert cidValue.isEmbedded(); 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(); Set idAttributes = idType.getIdClassAttributesSafely();
if ( idAttributes == null ) { if ( idAttributes == null ) {
idAttributes = new HashSet<>( propertySpan ); idAttributes = new HashSet<>( propertySpan );
while ( cidPropertyItr.hasNext() ) { for ( Property cidSubproperty : cidProperties ) {
final Property cidSubProperty = cidPropertyItr.next(); final SingularPersistentAttribute<?, Object> cidSubAttr =
final SingularPersistentAttribute<?, Object> cidSubAttr = attributeFactory.buildIdAttribute( attributeFactory.buildIdAttribute( idType, cidSubproperty );
idType, //noinspection unchecked
cidSubProperty
);
idAttributes.add( cidSubAttr ); idAttributes.add( cidSubAttr );
} }
} }
( ( AttributeContainer) identifiableType ).getInFlightAccess().applyNonAggregatedIdAttributes( idAttributes, idClassType ); AttributeContainer<?> container = (AttributeContainer<?>) identifiableType;
//noinspection unchecked
container.getInFlightAccess().applyNonAggregatedIdAttributes( idAttributes, idClassType );
} }
} }
@ -486,12 +491,12 @@ private EmbeddableTypeImpl<?> applyIdClassMetadata(Component idClassComponent) {
return embeddableType; return embeddableType;
} }
@SuppressWarnings({"unchecked", "rawtypes"})
private <X> void applyIdMetadata(MappedSuperclass mappingType, MappedSuperclassDomainType<X> jpaMappingType) { private <X> void applyIdMetadata(MappedSuperclass mappingType, MappedSuperclassDomainType<X> jpaMappingType) {
if ( mappingType.hasIdentifierProperty() ) { if ( mappingType.hasIdentifierProperty() ) {
final Property declaredIdentifierProperty = mappingType.getDeclaredIdentifierProperty(); final Property declaredIdentifierProperty = mappingType.getDeclaredIdentifierProperty();
if ( declaredIdentifierProperty != null ) { if ( declaredIdentifierProperty != null ) {
final SingularPersistentAttribute<X, Object> attribute = attributeFactory.buildIdAttribute( jpaMappingType, declaredIdentifierProperty ); final SingularPersistentAttribute<X, Object> attribute =
attributeFactory.buildIdAttribute( jpaMappingType, declaredIdentifierProperty );
//noinspection unchecked //noinspection unchecked
( ( AttributeContainer) jpaMappingType ).getInFlightAccess().applyIdAttribute( attribute ); ( ( AttributeContainer) jpaMappingType ).getInFlightAccess().applyIdAttribute( attribute );
} }
@ -500,7 +505,7 @@ private <X> void applyIdMetadata(MappedSuperclass mappingType, MappedSuperclassD
else if ( mappingType.getIdentifierMapper() != null ) { else if ( mappingType.getIdentifierMapper() != null ) {
Set<SingularPersistentAttribute<? super X, ?>> attributes = buildIdClassAttributes( Set<SingularPersistentAttribute<? super X, ?>> attributes = buildIdClassAttributes(
jpaMappingType, jpaMappingType,
mappingType.getIdentifierMapper().getPropertyIterator() mappingType.getIdentifierMapper().getProperties()
); );
//noinspection unchecked //noinspection unchecked
( ( AttributeContainer<X>) jpaMappingType ).getInFlightAccess().applyIdClassAttributes( attributes ); ( ( AttributeContainer<X>) jpaMappingType ).getInFlightAccess().applyIdClassAttributes( attributes );
@ -529,13 +534,13 @@ private <X> void applyVersionAttribute(MappedSuperclass mappingType, MappedSuper
private <X> Set<SingularPersistentAttribute<? super X, ?>> buildIdClassAttributes( private <X> Set<SingularPersistentAttribute<? super X, ?>> buildIdClassAttributes(
IdentifiableDomainType<X> ownerType, IdentifiableDomainType<X> ownerType,
Iterator<Property> propertyIterator) { List<Property> properties) {
if ( LOG.isTraceEnabled() ) { if ( LOG.isTraceEnabled() ) {
LOG.trace( "Building old-school composite identifier [" + ownerType.getJavaType().getName() + ']' ); LOG.trace( "Building old-school composite identifier [" + ownerType.getJavaType().getName() + ']' );
} }
Set<SingularPersistentAttribute<? super X, ?>> attributes = new HashSet<>(); Set<SingularPersistentAttribute<? super X, ?>> attributes = new HashSet<>();
while ( propertyIterator.hasNext() ) { for ( Property property : properties ) {
attributes.add( attributeFactory.buildIdAttribute( ownerType, propertyIterator.next() ) ); attributes.add( attributeFactory.buildIdAttribute( ownerType, property ) );
} }
return attributes; return attributes;
} }

View File

@ -7,7 +7,6 @@
package org.hibernate.metamodel.mapping.internal; package org.hibernate.metamodel.mapping.internal;
import java.io.Serializable; import java.io.Serializable;
import java.util.Iterator;
import java.util.Locale; import java.util.Locale;
import java.util.function.Consumer; import java.util.function.Consumer;
@ -152,9 +151,7 @@ protected static boolean finishInitialization(
int attributeIndex = 0; int attributeIndex = 0;
int columnPosition = 0; int columnPosition = 0;
final Iterator<Property> propertyIterator = bootDescriptor.getPropertyIterator(); for ( Property bootPropertyDescriptor : bootDescriptor.getProperties() ) {
while ( propertyIterator.hasNext() ) {
final Property bootPropertyDescriptor = propertyIterator.next();
final Type subtype = subtypes[ attributeIndex ]; final Type subtype = subtypes[ attributeIndex ];
attributeTypeValidator.check( bootPropertyDescriptor.getName(), subtype ); attributeTypeValidator.check( bootPropertyDescriptor.getName(), subtype );

View File

@ -292,9 +292,7 @@ private boolean finishInitialization(
// Reset the attribute mappings that were added in previous attempts // Reset the attribute mappings that were added in previous attempts
this.attributeMappings.clear(); this.attributeMappings.clear();
final Iterator<Property> propertyIterator = bootDescriptor.getPropertyIterator(); for ( Property bootPropertyDescriptor : bootDescriptor.getProperties() ) {
while ( propertyIterator.hasNext() ) {
final Property bootPropertyDescriptor = propertyIterator.next();
final AttributeMapping attributeMapping; final AttributeMapping attributeMapping;
final Type subtype = subtypes[attributeIndex]; final Type subtype = subtypes[attributeIndex];

View File

@ -286,7 +286,7 @@ private ForeignKeyDescriptor createForeignKeyDescriptor(
final BasicValuedModelPart basicFkTargetPart = (BasicValuedModelPart) fkTargetPart; final BasicValuedModelPart basicFkTargetPart = (BasicValuedModelPart) fkTargetPart;
final SelectableMapping keySelectableMapping = SelectableMappingImpl.from( final SelectableMapping keySelectableMapping = SelectableMappingImpl.from(
fkKeyTableName, fkKeyTableName,
fkBootDescriptorSource.getColumnIterator().next(), fkBootDescriptorSource.getSelectables().get(0),
basicFkTargetPart.getJdbcMapping(), basicFkTargetPart.getJdbcMapping(),
dialect, dialect,
creationProcess.getSqmFunctionRegistry() creationProcess.getSqmFunctionRegistry()

View File

@ -580,7 +580,7 @@ public static PluralAttributeMapping buildPluralAttributeMapping(
final BasicValue index = (BasicValue) ( (IndexedCollection) bootValueMapping ).getIndex(); final BasicValue index = (BasicValue) ( (IndexedCollection) bootValueMapping ).getIndex();
final SelectableMapping selectableMapping = SelectableMappingImpl.from( final SelectableMapping selectableMapping = SelectableMappingImpl.from(
tableExpression, tableExpression,
index.getColumnIterator().next(), index.getSelectables().get(0),
creationContext.getTypeConfiguration().getBasicTypeForJavaType( Integer.class ), creationContext.getTypeConfiguration().getBasicTypeForJavaType( Integer.class ),
dialect, dialect,
creationProcess.getSqmFunctionRegistry() creationProcess.getSqmFunctionRegistry()
@ -631,7 +631,7 @@ public static PluralAttributeMapping buildPluralAttributeMapping(
final BasicValue index = (BasicValue) ( (IndexedCollection) bootValueMapping ).getIndex(); final BasicValue index = (BasicValue) ( (IndexedCollection) bootValueMapping ).getIndex();
final SelectableMapping selectableMapping = SelectableMappingImpl.from( final SelectableMapping selectableMapping = SelectableMappingImpl.from(
tableExpression, tableExpression,
index.getColumnIterator().next(), index.getSelectables().get(0),
creationContext.getTypeConfiguration().getBasicTypeForJavaType( Integer.class ), creationContext.getTypeConfiguration().getBasicTypeForJavaType( Integer.class ),
dialect, dialect,
creationProcess.getSqmFunctionRegistry() creationProcess.getSqmFunctionRegistry()
@ -858,7 +858,7 @@ private static void interpretPluralAttributeMappingKeyDescriptor(
final String tableExpression = getTableIdentifierExpression( bootValueMappingKey.getTable(), creationProcess ); final String tableExpression = getTableIdentifierExpression( bootValueMappingKey.getTable(), creationProcess );
final SelectableMapping keySelectableMapping = SelectableMappingImpl.from( final SelectableMapping keySelectableMapping = SelectableMappingImpl.from(
tableExpression, tableExpression,
bootValueMappingKey.getColumnIterator().next(), bootValueMappingKey.getSelectables().get(0),
(JdbcMapping) keyType, (JdbcMapping) keyType,
dialect, dialect,
creationProcess.getSqmFunctionRegistry() creationProcess.getSqmFunctionRegistry()
@ -1320,7 +1320,7 @@ private static CollectionPart interpretMapKey(
final BasicValue basicValue = (BasicValue) bootMapKeyDescriptor; final BasicValue basicValue = (BasicValue) bootMapKeyDescriptor;
final SelectableMapping selectableMapping = SelectableMappingImpl.from( final SelectableMapping selectableMapping = SelectableMappingImpl.from(
tableExpression, tableExpression,
basicValue.getColumnIterator().next(), basicValue.getSelectables().get(0),
basicValue.resolve().getJdbcMapping(), basicValue.resolve().getJdbcMapping(),
dialect, dialect,
creationProcess.getSqmFunctionRegistry() creationProcess.getSqmFunctionRegistry()
@ -1403,7 +1403,7 @@ private static CollectionPart interpretElement(
final BasicValue basicElement = (BasicValue) element; final BasicValue basicElement = (BasicValue) element;
final SelectableMapping selectableMapping = SelectableMappingImpl.from( final SelectableMapping selectableMapping = SelectableMappingImpl.from(
tableExpression, tableExpression,
basicElement.getColumnIterator().next(), basicElement.getSelectables().get(0),
basicElement.resolve().getJdbcMapping(), basicElement.resolve().getJdbcMapping(),
dialect, dialect,
creationProcess.getSqmFunctionRegistry() creationProcess.getSqmFunctionRegistry()

View File

@ -64,13 +64,13 @@ public static SelectableMappings from(
final List<JdbcMapping> jdbcMappings = new ArrayList<>(); final List<JdbcMapping> jdbcMappings = new ArrayList<>();
resolveJdbcMappings( jdbcMappings, mapping, value.getType() ); resolveJdbcMappings( jdbcMappings, mapping, value.getType() );
final List<Selectable> constraintColumns = value.getSelectables(); final List<Selectable> selectables = value.getVirtualSelectables();
final SelectableMapping[] selectableMappings = new SelectableMapping[jdbcMappings.size()]; 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( selectableMappings[propertyOrder[i]] = SelectableMappingImpl.from(
containingTableExpression, containingTableExpression,
constraintColumns.get( i ), selectables.get( i ),
jdbcMappings.get( propertyOrder[i] ), jdbcMappings.get( propertyOrder[i] ),
dialect, dialect,
sqmFunctionRegistry sqmFunctionRegistry
@ -85,13 +85,9 @@ public static SelectableMappings from(EmbeddableMappingType embeddableMappingTyp
final List<SelectableMapping> selectableMappings = CollectionHelper.arrayList( propertySpan ); final List<SelectableMapping> selectableMappings = CollectionHelper.arrayList( propertySpan );
embeddableMappingType.forEachAttributeMapping( embeddableMappingType.forEachAttributeMapping(
(index, attributeMapping) -> { (index, attributeMapping) -> attributeMapping.forEachSelectable(
attributeMapping.forEachSelectable( (columnIndex, selection) -> selectableMappings.add( selection )
(columnIndex, selection) -> { )
selectableMappings.add( selection );
}
);
}
); );
return new SelectableMappingsImpl( selectableMappings.toArray( new SelectableMapping[0] ) ); return new SelectableMappingsImpl( selectableMappings.toArray( new SelectableMapping[0] ) );

View File

@ -229,7 +229,7 @@ public ToOneAttributeMapping(
if ( join.getPersistentClass().getEntityName().equals( entityBinding.getEntityName() ) if ( join.getPersistentClass().getEntityName().equals( entityBinding.getEntityName() )
&& join.getPropertySpan() == 1 && join.getPropertySpan() == 1
&& join.getTable() == manyToOne.getTable() && join.getTable() == manyToOne.getTable()
&& equal( join.getKey().getColumnIterator(), manyToOne.getColumnIterator() ) ) { && equal( join.getKey(), manyToOne ) ) {
bidirectionalAttributeName = join.getPropertyIterator().next().getName(); bidirectionalAttributeName = join.getPropertyIterator().next().getName();
break; break;
} }
@ -503,7 +503,9 @@ private ToOneAttributeMapping(
this.isConstrained = original.isConstrained; this.isConstrained = original.isConstrained;
} }
private static boolean equal(Iterator<Selectable> lhsColumns, Iterator<Selectable> rhsColumns) { private static boolean equal(Value lhsValue, Value rhsValue) {
Iterator<Selectable> lhsColumns = lhsValue.getColumnIterator();
Iterator<Selectable> rhsColumns = rhsValue.getColumnIterator();
boolean hasNext; boolean hasNext;
do { do {
final Selectable lhs = lhsColumns.next(); final Selectable lhs = lhsColumns.next();

View File

@ -358,14 +358,12 @@ public AbstractCollectionPersister(
// KEY // KEY
keyType = collectionBootDescriptor.getKey().getType(); keyType = collectionBootDescriptor.getKey().getType();
Iterator<Selectable> columnIter = collectionBootDescriptor.getKey().getColumnIterator();
int keySpan = collectionBootDescriptor.getKey().getColumnSpan(); int keySpan = collectionBootDescriptor.getKey().getColumnSpan();
keyColumnNames = new String[keySpan]; keyColumnNames = new String[keySpan];
keyColumnAliases = new String[keySpan]; keyColumnAliases = new String[keySpan];
int k = 0; int k = 0;
while ( columnIter.hasNext() ) { for ( Column column: collectionBootDescriptor.getKey().getColumns() ) {
// NativeSQL: collect key column and auto-aliases // NativeSQL: collect key column and auto-aliases
Column column = (Column) columnIter.next();
keyColumnNames[k] = column.getQuotedName( dialect ); keyColumnNames[k] = column.getQuotedName( dialect );
keyColumnAliases[k] = column.getAlias( dialect, table ); keyColumnAliases[k] = column.getAlias( dialect, table );
k++; k++;
@ -404,9 +402,7 @@ public AbstractCollectionPersister(
columnInsertability = elementBootDescriptor.getColumnInsertability(); columnInsertability = elementBootDescriptor.getColumnInsertability();
} }
int j = 0; int j = 0;
columnIter = elementBootDescriptor.getColumnIterator(); for ( Selectable selectable: elementBootDescriptor.getSelectables() ) {
while ( columnIter.hasNext() ) {
Selectable selectable = columnIter.next();
elementColumnAliases[j] = selectable.getAlias( dialect, table ); elementColumnAliases[j] = selectable.getAlias( dialect, table );
if ( selectable.isFormula() ) { if ( selectable.isFormula() ) {
Formula form = (Formula) selectable; Formula form = (Formula) selectable;
@ -455,7 +451,6 @@ public AbstractCollectionPersister(
int indexSpan = indexedCollection.getIndex().getColumnSpan(); int indexSpan = indexedCollection.getIndex().getColumnSpan();
boolean[] indexColumnInsertability = indexedCollection.getIndex().getColumnInsertability(); boolean[] indexColumnInsertability = indexedCollection.getIndex().getColumnInsertability();
boolean[] indexColumnUpdatability = indexedCollection.getIndex().getColumnUpdateability(); boolean[] indexColumnUpdatability = indexedCollection.getIndex().getColumnUpdateability();
columnIter = indexedCollection.getIndex().getColumnIterator();
indexColumnNames = new String[indexSpan]; indexColumnNames = new String[indexSpan];
indexFormulaTemplates = new String[indexSpan]; indexFormulaTemplates = new String[indexSpan];
indexFormulas = new String[indexSpan]; indexFormulas = new String[indexSpan];
@ -464,8 +459,7 @@ public AbstractCollectionPersister(
indexColumnAliases = new String[indexSpan]; indexColumnAliases = new String[indexSpan];
int i = 0; int i = 0;
boolean hasFormula = false; boolean hasFormula = false;
while ( columnIter.hasNext() ) { for ( Selectable s: indexedCollection.getIndex().getSelectables() ) {
Selectable s = columnIter.next();
indexColumnAliases[i] = s.getAlias( dialect ); indexColumnAliases[i] = s.getAlias( dialect );
if ( s.isFormula() ) { if ( s.isFormula() ) {
Formula indexForm = (Formula) s; Formula indexForm = (Formula) s;
@ -516,8 +510,7 @@ else if ( indexedCollection instanceof org.hibernate.mapping.Map
} }
IdentifierCollection idColl = (IdentifierCollection) collectionBootDescriptor; IdentifierCollection idColl = (IdentifierCollection) collectionBootDescriptor;
identifierType = idColl.getIdentifier().getType(); identifierType = idColl.getIdentifier().getType();
columnIter = idColl.getIdentifier().getColumnIterator(); Column col = idColl.getIdentifier().getColumns().get(0);
Column col = (Column) columnIter.next();
identifierColumnName = col.getQuotedName( dialect ); identifierColumnName = col.getQuotedName( dialect );
identifierColumnAlias = col.getAlias( dialect ); identifierColumnAlias = col.getAlias( dialect );
identifierGenerator = idColl.getIdentifier().createIdentifierGenerator( identifierGenerator = idColl.getIdentifier().createIdentifierGenerator(

View File

@ -284,7 +284,6 @@ public abstract class AbstractEntityPersister
public static final String VERSION_COLUMN_ALIAS = "version_"; public static final String VERSION_COLUMN_ALIAS = "version_";
private final String sqlAliasStem; private final String sqlAliasStem;
private EntityMappingType rootEntityDescriptor;
private final SingleIdEntityLoader<?> singleIdEntityLoader; private final SingleIdEntityLoader<?> singleIdEntityLoader;
private final MultiIdEntityLoader<?> multiIdEntityLoader; private final MultiIdEntityLoader<?> multiIdEntityLoader;
@ -774,24 +773,22 @@ else if ( batchSize > 1 ) {
multiIdEntityLoader = new MultiIdLoaderStandard<>( this, bootDescriptor, factory ); multiIdEntityLoader = new MultiIdLoaderStandard<>( this, bootDescriptor, factory );
Iterator<Selectable> idColumns = bootDescriptor.getIdentifier().getColumnIterator();
int i = 0; int i = 0;
while ( idColumns.hasNext() ) { for ( Column column: bootDescriptor.getIdentifier().getColumns() ) {
Column col = (Column) idColumns.next(); rootTableKeyColumnNames[i] = column.getQuotedName( dialect );
rootTableKeyColumnNames[i] = col.getQuotedName( dialect ); rootTableKeyColumnReaders[i] = column.getReadExpr( dialect );
rootTableKeyColumnReaders[i] = col.getReadExpr( dialect ); rootTableKeyColumnReaderTemplates[i] = column.getTemplate(
rootTableKeyColumnReaderTemplates[i] = col.getTemplate(
dialect, dialect,
factory.getQueryEngine().getSqmFunctionRegistry() factory.getQueryEngine().getSqmFunctionRegistry()
); );
identifierAliases[i] = col.getAlias( dialect, bootDescriptor.getRootTable() ); identifierAliases[i] = column.getAlias( dialect, bootDescriptor.getRootTable() );
i++; i++;
} }
// VERSION // VERSION
if ( bootDescriptor.isVersioned() ) { if ( bootDescriptor.isVersioned() ) {
versionColumnName = ( (Column) bootDescriptor.getVersion().getColumnIterator().next() ).getQuotedName( dialect ); versionColumnName = bootDescriptor.getVersion().getColumns().get(0).getQuotedName( dialect );
} }
else { else {
versionColumnName = null; versionColumnName = null;
@ -841,11 +838,9 @@ else if ( batchSize > 1 ) {
ArrayList<String[]> lazyColAliases = new ArrayList<>(); ArrayList<String[]> lazyColAliases = new ArrayList<>();
final ArrayList<Integer> lobPropertiesLocalCollector = new ArrayList<>(); final ArrayList<Integer> lobPropertiesLocalCollector = new ArrayList<>();
Iterator<Property> properties = bootDescriptor.getPropertyClosureIterator();
i = 0; i = 0;
boolean foundFormula = false; boolean foundFormula = false;
while ( properties.hasNext() ) { for ( Property prop : bootDescriptor.getPropertyClosure() ) {
Property prop = properties.next();
thisClassProperties.add( prop ); thisClassProperties.add( prop );
int span = prop.getColumnSpan(); int span = prop.getColumnSpan();
@ -856,18 +851,16 @@ else if ( batchSize > 1 ) {
String[] colReaderTemplates = new String[span]; String[] colReaderTemplates = new String[span];
String[] colWriters = new String[span]; String[] colWriters = new String[span];
String[] formulaTemplates = new String[span]; String[] formulaTemplates = new String[span];
Iterator<Selectable> colIter = prop.getColumnIterator();
int k = 0; int k = 0;
while ( colIter.hasNext() ) { for ( Selectable selectable: prop.getSelectables() ) {
Selectable thing = colIter.next(); colAliases[k] = selectable.getAlias( dialect, prop.getValue().getTable() );
colAliases[k] = thing.getAlias( dialect, prop.getValue().getTable() ); if ( selectable.isFormula() ) {
if ( thing.isFormula() ) {
foundFormula = true; foundFormula = true;
( (Formula) thing ).setFormula( substituteBrackets( ( (Formula) thing ).getFormula() ) ); ( (Formula) selectable ).setFormula( substituteBrackets( ( (Formula) selectable ).getFormula() ) );
formulaTemplates[k] = thing.getTemplate( dialect, factory.getQueryEngine().getSqmFunctionRegistry() ); formulaTemplates[k] = selectable.getTemplate( dialect, factory.getQueryEngine().getSqmFunctionRegistry() );
} }
else { else {
Column col = (Column) thing; Column col = (Column) selectable;
colNames[k] = col.getQuotedName( dialect ); colNames[k] = col.getQuotedName( dialect );
colReaderTemplates[k] = col.getTemplate( dialect, factory.getQueryEngine().getSqmFunctionRegistry() ); colReaderTemplates[k] = col.getTemplate( dialect, factory.getQueryEngine().getSqmFunctionRegistry() );
colWriters[k] = col.getWriteExpr(); colWriters[k] = col.getWriteExpr();
@ -945,9 +938,7 @@ else if ( batchSize > 1 ) {
ArrayList<Boolean> columnSelectables = new ArrayList<>(); ArrayList<Boolean> columnSelectables = new ArrayList<>();
ArrayList<Boolean> propNullables = new ArrayList<>(); ArrayList<Boolean> propNullables = new ArrayList<>();
Iterator<Property> iter = bootDescriptor.getSubclassPropertyClosureIterator(); for ( Property prop : bootDescriptor.getSubclassPropertyClosure() ) {
while ( iter.hasNext() ) {
final Property prop = iter.next();
names.add( prop.getName() ); names.add( prop.getName() );
classes.add( prop.getPersistentClass().getEntityName() ); classes.add( prop.getPersistentClass().getEntityName() );
types.add( prop.getType() ); types.add( prop.getType() );
@ -956,7 +947,6 @@ else if ( batchSize > 1 ) {
definedBySubclass.add( Boolean.valueOf( isDefinedBySubclass ) ); definedBySubclass.add( Boolean.valueOf( isDefinedBySubclass ) );
propNullables.add( Boolean.valueOf( prop.isOptional() || isDefinedBySubclass ) ); //TODO: is this completely correct? propNullables.add( Boolean.valueOf( prop.isOptional() || isDefinedBySubclass ) ); //TODO: is this completely correct?
final Iterator<Selectable> colIter = prop.getColumnIterator();
String[] cols = new String[ prop.getColumnSpan() ]; String[] cols = new String[ prop.getColumnSpan() ];
String[] readers = new String[ prop.getColumnSpan() ]; String[] readers = new String[ prop.getColumnSpan() ];
String[] readerTemplates = new String[ prop.getColumnSpan() ]; String[] readerTemplates = new String[ prop.getColumnSpan() ];
@ -968,7 +958,7 @@ else if ( batchSize > 1 ) {
final boolean lazy = ! EnhancementHelper.includeInBaseFetchGroup( final boolean lazy = ! EnhancementHelper.includeInBaseFetchGroup(
prop, prop,
entityMetamodel.isInstrumented(), entityMetamodel.isInstrumented(),
(entityName) -> { entityName -> {
final MetadataImplementor metadata = creationContext.getMetadata(); final MetadataImplementor metadata = creationContext.getMetadata();
final PersistentClass entityBinding = metadata.getEntityBinding( entityName ); final PersistentClass entityBinding = metadata.getEntityBinding( entityName );
assert entityBinding != null; assert entityBinding != null;
@ -976,26 +966,25 @@ else if ( batchSize > 1 ) {
}, },
sessionFactoryOptions.isCollectionsInDefaultFetchGroupEnabled() sessionFactoryOptions.isCollectionsInDefaultFetchGroupEnabled()
); );
while ( colIter.hasNext() ) { for ( Selectable selectable : prop.getSelectables() ) {
final Selectable thing = colIter.next(); if ( selectable.isFormula() ) {
if ( thing.isFormula() ) { String template = selectable.getTemplate( dialect, factory.getQueryEngine().getSqmFunctionRegistry() );
String template = thing.getTemplate( dialect, factory.getQueryEngine().getSqmFunctionRegistry() );
formnos[l] = formulaTemplates.size(); formnos[l] = formulaTemplates.size();
colnos[l] = -1; colnos[l] = -1;
formulaTemplates.add( template ); formulaTemplates.add( template );
forms[l] = template; forms[l] = template;
formulas.add( thing.getText( dialect ) ); formulas.add( selectable.getText( dialect ) );
formulaAliases.add( thing.getAlias( dialect ) ); formulaAliases.add( selectable.getAlias( dialect ) );
formulasLazy.add( lazy ); formulasLazy.add( lazy );
} }
else { else {
Column col = (Column) thing; Column col = (Column) selectable;
String colName = col.getQuotedName( dialect ); String colName = col.getQuotedName( dialect );
colnos[l] = columns.size(); //before add :-) colnos[l] = columns.size(); //before add :-)
formnos[l] = -1; formnos[l] = -1;
columns.add( colName ); columns.add( colName );
cols[l] = colName; cols[l] = colName;
aliases.add( thing.getAlias( dialect, prop.getValue().getTable() ) ); aliases.add( selectable.getAlias( dialect, prop.getValue().getTable() ) );
columnsLazy.add( lazy ); columnsLazy.add( lazy );
columnSelectables.add( Boolean.valueOf( prop.isSelectable() ) ); columnSelectables.add( Boolean.valueOf( prop.isSelectable() ) );
@ -1059,29 +1048,9 @@ else if ( batchSize > 1 ) {
filterHelper = null; filterHelper = null;
} }
// Check if we can use Reference Cached entities in 2lc useReferenceCacheEntries = useReferenceCacheEntries();
// todo : should really validate that the cache access type is read-only
boolean refCacheEntries = true;
if ( !factory.getSessionFactoryOptions().isDirectReferenceCacheEntriesEnabled() ) {
refCacheEntries = false;
}
// for now, limit this to just entities that: cacheEntryHelper = buildCacheEntryHelper();
// 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();
if ( sessionFactoryOptions.isSecondLevelCacheEnabled() ) { if ( sessionFactoryOptions.isSecondLevelCacheEnabled() ) {
this.invalidateCache = canWriteToCache && shouldInvalidateCache( bootDescriptor, creationContext ); this.invalidateCache = canWriteToCache && shouldInvalidateCache( bootDescriptor, creationContext );
@ -1092,6 +1061,30 @@ else if ( batchSize > 1 ) {
} }
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( private static SingleIdEntityLoader<?> createBatchingIdEntityLoader(
EntityMappingType entityDescriptor, EntityMappingType entityDescriptor,
int batchSize, int batchSize,
@ -2355,13 +2348,7 @@ public DiscriminatorMetadata getTypeDiscriminatorMetadata() {
} }
private DiscriminatorMetadata buildTypeDiscriminatorMetadata() { private DiscriminatorMetadata buildTypeDiscriminatorMetadata() {
return new DiscriminatorMetadata() { return () -> new DiscriminatorType( (BasicType<?>) getDiscriminatorType(), AbstractEntityPersister.this );
@Override
public Type getResolutionType() {
return new DiscriminatorType( (BasicType) getDiscriminatorType(), AbstractEntityPersister.this );
}
};
} }
public static String generateTableAlias(String rootAlias, int tableNumber) { public static String generateTableAlias(String rootAlias, int tableNumber) {
@ -2530,13 +2517,11 @@ public int[] resolveDirtyAttributeIndexes(
} ); } );
} }
if ( attributeNames != null ) { final boolean[] propertyUpdateability = entityMetamodel.getPropertyUpdateability();
final boolean[] propertyUpdateability = entityMetamodel.getPropertyUpdateability(); for ( String attributeName : attributeNames ) {
for ( String attributeName : attributeNames ) { final Integer index = entityMetamodel.getPropertyIndexOrNull( attributeName );
final Integer index = entityMetamodel.getPropertyIndexOrNull( attributeName ); if ( index != null && propertyUpdateability[index] && !fields.contains( index ) ) {
if ( index != null && propertyUpdateability[index] && !fields.contains( index ) ) { fields.add( index );
fields.add( index );
}
} }
} }
@ -2599,7 +2584,7 @@ public String[] getSubclassPropertyColumnNames(String propertyName) {
protected void initSubclassPropertyAliasesMap(PersistentClass model) throws MappingException { protected void initSubclassPropertyAliasesMap(PersistentClass model) throws MappingException {
// ALIASES // 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' // aliases for identifier ( alias.id ); skip if the entity defines a non-id property named 'id'
if ( !entityMetamodel.hasNonIdentifierPropertyNamedId() ) { if ( !entityMetamodel.hasNonIdentifierPropertyNamedId() ) {
@ -2658,31 +2643,26 @@ protected void initSubclassPropertyAliasesMap(PersistentClass model) throws Mapp
} }
private void internalInitSubclassPropertyAliasesMap(String path, Iterator<Property> propertyIterator) { private void internalInitSubclassPropertyAliasesMap(String path, List<Property> properties) {
while ( propertyIterator.hasNext() ) { for (Property property : properties) {
String name = path == null ? property.getName() : path + "." + property.getName();
Property prop = propertyIterator.next(); if ( property.isComposite() ) {
String propname = path == null ? prop.getName() : path + "." + prop.getName(); Component component = (Component) property.getValue();
if ( prop.isComposite() ) { internalInitSubclassPropertyAliasesMap( name, component.getProperties() );
Component component = (Component) prop.getValue();
Iterator<Property> compProps = component.getPropertyIterator();
internalInitSubclassPropertyAliasesMap( propname, compProps );
} }
else { else {
String[] aliases = new String[prop.getColumnSpan()]; String[] aliases = new String[property.getColumnSpan()];
String[] cols = new String[prop.getColumnSpan()]; String[] cols = new String[property.getColumnSpan()];
Iterator<Selectable> colIter = prop.getColumnIterator();
int l = 0; int l = 0;
while ( colIter.hasNext() ) { for ( Selectable selectable: property.getSelectables() ) {
Selectable thing = colIter.next();
Dialect dialect = getFactory().getJdbcServices().getDialect(); Dialect dialect = getFactory().getJdbcServices().getDialect();
aliases[l] = thing.getAlias( dialect, prop.getValue().getTable() ); aliases[l] = selectable.getAlias( dialect, property.getValue().getTable() );
cols[l] = thing.getText(dialect); // TODO: skip formulas? cols[l] = selectable.getText(dialect); // TODO: skip formulas?
l++; l++;
} }
subclassPropertyAliases.put( propname, aliases ); subclassPropertyAliases.put( name, aliases );
subclassPropertyColumnNames.put( propname, cols ); subclassPropertyColumnNames.put( name, cols );
} }
} }
@ -4389,9 +4369,8 @@ public boolean isSubclassPropertyNullable(int i) {
public final boolean[] getPropertiesToUpdate(final int[] dirtyProperties, final boolean hasDirtyCollection) { public final boolean[] getPropertiesToUpdate(final int[] dirtyProperties, final boolean hasDirtyCollection) {
final boolean[] propsToUpdate = new boolean[entityMetamodel.getPropertySpan()]; final boolean[] propsToUpdate = new boolean[entityMetamodel.getPropertySpan()];
final boolean[] updateability = getPropertyUpdateability(); //no need to check laziness, dirty checking handles that final boolean[] updateability = getPropertyUpdateability(); //no need to check laziness, dirty checking handles that
for ( int j = 0; j < dirtyProperties.length; j++ ) { for ( int property: dirtyProperties ) {
int property = dirtyProperties[j]; if (updateability[property]) {
if ( updateability[property] ) {
propsToUpdate[property] = true; propsToUpdate[property] = true;
} }
} }
@ -4490,9 +4469,9 @@ public boolean[] getPropertyUpdateability(Object entity) {
private void logDirtyProperties(int[] props) { private void logDirtyProperties(int[] props) {
if ( LOG.isTraceEnabled() ) { if ( LOG.isTraceEnabled() ) {
for ( int i = 0; i < props.length; i++ ) { for ( int prop : props ) {
String propertyName = entityMetamodel.getProperties()[props[i]].getName(); String propertyName = entityMetamodel.getProperties()[prop].getName();
LOG.trace( StringHelper.qualify( getEntityName(), propertyName ) + " is dirty" ); LOG.trace(StringHelper.qualify(getEntityName(), propertyName) + " is dirty");
} }
} }
} }
@ -5501,6 +5480,7 @@ public void prepareMappingModel(MappingModelCreationProcess creationProcess) {
.getBootModel() .getBootModel()
.getEntityBinding( getEntityName() ); .getEntityBinding( getEntityName() );
EntityMappingType rootEntityDescriptor;
if ( superMappingType != null ) { if ( superMappingType != null ) {
( (InFlightEntityMappingType) superMappingType ).prepareMappingModel( creationProcess ); ( (InFlightEntityMappingType) superMappingType ).prepareMappingModel( creationProcess );
if ( shouldProcessSuperMapping() ) { if ( shouldProcessSuperMapping() ) {
@ -5528,10 +5508,8 @@ public void prepareMappingModel(MappingModelCreationProcess creationProcess) {
final NonIdentifierAttribute runtimeAttrDefinition = properties[i]; final NonIdentifierAttribute runtimeAttrDefinition = properties[i];
final Property bootProperty = bootEntityDescriptor.getProperty( runtimeAttrDefinition.getName() ); final Property bootProperty = bootEntityDescriptor.getProperty( runtimeAttrDefinition.getName() );
if ( superMappingType != null && superMappingType.findAttributeMapping( bootProperty.getName() ) != null ) { if ( superMappingType == null
// its defined on the super-type, skip it here || superMappingType.findAttributeMapping( bootProperty.getName() ) == null ) {
}
else {
declaredAttributeMappings.put( declaredAttributeMappings.put(
runtimeAttrDefinition.getName(), runtimeAttrDefinition.getName(),
generateNonIdAttributeMapping( generateNonIdAttributeMapping(
@ -5542,6 +5520,9 @@ public void prepareMappingModel(MappingModelCreationProcess creationProcess) {
) )
); );
} }
// else {
// its defined on the supertype, skip it here
// }
} }
getAttributeMappings(); getAttributeMappings();
@ -5577,8 +5558,8 @@ public void prepareMappingModel(MappingModelCreationProcess creationProcess) {
} }
); );
boolean needsMultiTableInsert; boolean needsMultiTableInsert = isMultiTable();
if ( needsMultiTableInsert = isMultiTable() ) { if ( needsMultiTableInsert ) {
creationProcess.registerInitializationCallback( creationProcess.registerInitializationCallback(
"Entity(" + getEntityName() + ") `sqmMultiTableMutationStrategy` interpretation", "Entity(" + getEntityName() + ") `sqmMultiTableMutationStrategy` interpretation",
() -> { () -> {
@ -6074,9 +6055,9 @@ private AttributeMapping generateNonIdAttributeMapping(
attrColumnExpression = attrColumnNames[ 0 ]; attrColumnExpression = attrColumnNames[ 0 ];
isAttrColumnExpressionFormula = false; isAttrColumnExpressionFormula = false;
final Iterator<Selectable> selectableIterator = basicBootValue.getColumnIterator(); final List<Selectable> selectables = basicBootValue.getSelectables();
assert selectableIterator.hasNext(); assert !selectables.isEmpty();
final Selectable selectable = selectableIterator.next(); final Selectable selectable = selectables.get(0);
assert attrColumnExpression.equals( selectable.getText(sessionFactory.getJdbcServices().getDialect()) ); assert attrColumnExpression.equals( selectable.getText(sessionFactory.getJdbcServices().getDialect()) );

View File

@ -173,7 +173,7 @@ public JoinedSubclassEntityPersister(
if ( discriminatorMapping != null ) { if ( discriminatorMapping != null ) {
log.debug( "Encountered explicit discriminator mapping for joined inheritance" ); 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 ) { if ( selectable instanceof Formula ) {
throw new MappingException( "Discriminator formulas on joined inheritance hierarchies not supported at this time" ); throw new MappingException( "Discriminator formulas on joined inheritance hierarchies not supported at this time" );
} }
@ -259,12 +259,15 @@ else if ( persistentClass.isDiscriminatorValueNotNull() ) {
String[] keyCols = new String[idColumnSpan]; String[] keyCols = new String[idColumnSpan];
String[] keyColReaders = new String[idColumnSpan]; String[] keyColReaders = new String[idColumnSpan];
String[] keyColReaderTemplates = new String[idColumnSpan]; String[] keyColReaderTemplates = new String[idColumnSpan];
Iterator<Selectable> cItr = key.getColumnIterator(); List<Column> columns = key.getColumns();
for ( int k = 0; k < idColumnSpan; k++ ) { for ( int k = 0; k < idColumnSpan; k++ ) {
Column column = (Column) cItr.next(); Column column = columns.get(k);
keyCols[k] = column.getQuotedName( factory.getJdbcServices().getDialect() ); keyCols[k] = column.getQuotedName( factory.getJdbcServices().getDialect() );
keyColReaders[k] = column.getReadExpr( 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 ); keyColumns.add( keyCols );
keyColumnReaders.add( keyColReaders ); keyColumnReaders.add( keyColReaders );
@ -297,9 +300,9 @@ else if ( persistentClass.isDiscriminatorValueNotNull() ) {
String[] keyColReaders = new String[joinIdColumnSpan]; String[] keyColReaders = new String[joinIdColumnSpan];
String[] keyColReaderTemplates = new String[joinIdColumnSpan]; String[] keyColReaderTemplates = new String[joinIdColumnSpan];
Iterator<Selectable> cItr = key.getColumnIterator(); List<Column> columns = key.getColumns();
for ( int k = 0; k < joinIdColumnSpan; k++ ) { for ( int k = 0; k < joinIdColumnSpan; k++ ) {
Column column = (Column) cItr.next(); Column column = columns.get(k);
keyCols[k] = column.getQuotedName( factory.getJdbcServices().getDialect() ); keyCols[k] = column.getQuotedName( factory.getJdbcServices().getDialect() );
keyColReaders[k] = column.getReadExpr( 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() );
@ -335,9 +338,9 @@ else if ( persistentClass.isDiscriminatorValueNotNull() ) {
final String tableName = determineTableName( tab ); final String tableName = determineTableName( tab );
subclassTableNames.add( tableName ); subclassTableNames.add( tableName );
String[] key = new String[idColumnSpan]; String[] key = new String[idColumnSpan];
Iterator<Column> cItr = tab.getPrimaryKey().getColumnIterator(); List<Column> columns = tab.getPrimaryKey().getColumns();
for ( int k = 0; k < idColumnSpan; k++ ) { 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 ); keyColumns.add( key );
} }
@ -357,9 +360,9 @@ else if ( persistentClass.isDiscriminatorValueNotNull() ) {
String joinTableName = determineTableName( joinTable ); String joinTableName = determineTableName( joinTable );
subclassTableNames.add( joinTableName ); subclassTableNames.add( joinTableName );
String[] key = new String[idColumnSpan]; String[] key = new String[idColumnSpan];
Iterator<Column> citer = joinTable.getPrimaryKey().getColumnIterator(); List<Column> columns = joinTable.getPrimaryKey().getColumns();
for ( int k = 0; k < idColumnSpan; k++ ) { 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 ); keyColumns.add( key );
} }
@ -473,11 +476,9 @@ else if ( persistentClass.isDiscriminatorValueNotNull() ) {
int hydrateSpan = getPropertySpan(); int hydrateSpan = getPropertySpan();
naturalOrderPropertyTableNumbers = new int[hydrateSpan]; naturalOrderPropertyTableNumbers = new int[hydrateSpan];
propertyTableNumbers = new int[hydrateSpan]; propertyTableNumbers = new int[hydrateSpan];
Iterator<Property> iter = persistentClass.getPropertyClosureIterator();
int i = 0; int i = 0;
while ( iter.hasNext() ) { for ( Property property : persistentClass.getPropertyClosure() ) {
Property prop = iter.next(); String tabname = property.getValue().getTable().getQualifiedName(
String tabname = prop.getValue().getTable().getQualifiedName(
factory.getSqlStringGenerationContext() factory.getSqlStringGenerationContext()
); );
propertyTableNumbers[i] = getTableId( tabname, this.tableNames ); propertyTableNumbers[i] = getTableId( tabname, this.tableNames );
@ -493,20 +494,16 @@ else if ( persistentClass.isDiscriminatorValueNotNull() ) {
ArrayList<Integer> formulaTableNumbers = new ArrayList<>(); ArrayList<Integer> formulaTableNumbers = new ArrayList<>();
ArrayList<Integer> propTableNumbers = new ArrayList<>(); ArrayList<Integer> propTableNumbers = new ArrayList<>();
iter = persistentClass.getSubclassPropertyClosureIterator(); for ( Property property : persistentClass.getSubclassPropertyClosure() ) {
while ( iter.hasNext() ) { Table tab = property.getValue().getTable();
Property prop = iter.next();
Table tab = prop.getValue().getTable();
String tabname = tab.getQualifiedName( String tabname = tab.getQualifiedName(
factory.getSqlStringGenerationContext() factory.getSqlStringGenerationContext()
); );
Integer tabnum = getTableId( tabname, subclassTableNameClosure ); Integer tabnum = getTableId( tabname, subclassTableNameClosure );
propTableNumbers.add( tabnum ); propTableNumbers.add( tabnum );
Iterator<Selectable> citer = prop.getColumnIterator(); for ( Selectable selectable : property.getSelectables() ) {
while ( citer.hasNext() ) { if ( selectable.isFormula() ) {
Selectable thing = citer.next();
if ( thing.isFormula() ) {
formulaTableNumbers.add( tabnum ); formulaTableNumbers.add( tabnum );
} }
else { else {

View File

@ -214,11 +214,9 @@ public SingleTableEntityPersister(
? ExecuteUpdateResultCheckStyle.determineDefault( customSQLDelete[j], deleteCallable[j] ) ? ExecuteUpdateResultCheckStyle.determineDefault( customSQLDelete[j], deleteCallable[j] )
: join.getCustomSQLDeleteCheckStyle(); : join.getCustomSQLDeleteCheckStyle();
Iterator<Selectable> iter = join.getKey().getColumnIterator();
keyColumnNames[j] = new String[join.getKey().getColumnSpan()]; keyColumnNames[j] = new String[join.getKey().getColumnSpan()];
int i = 0; int i = 0;
while ( iter.hasNext() ) { for ( Column col : join.getKey().getColumns() ) {
Column col = (Column) iter.next();
keyColumnNames[j][i++] = col.getQuotedName( dialect ); keyColumnNames[j][i++] = col.getQuotedName( dialect );
} }
@ -270,11 +268,9 @@ public SingleTableEntityPersister(
String joinTableName = determineTableName( join.getTable() ); String joinTableName = determineTableName( join.getTable() );
subclassTables.add( joinTableName ); subclassTables.add( joinTableName );
Iterator<Selectable> iter = join.getKey().getColumnIterator();
String[] keyCols = new String[join.getKey().getColumnSpan()]; String[] keyCols = new String[join.getKey().getColumnSpan()];
int i = 0; int i = 0;
while ( iter.hasNext() ) { for ( Column col : join.getKey().getColumns() ) {
Column col = (Column) iter.next();
keyCols[i++] = col.getQuotedName( dialect ); keyCols[i++] = col.getQuotedName( dialect );
} }
joinKeyColumns.add( keyCols ); joinKeyColumns.add( keyCols );
@ -297,7 +293,7 @@ public SingleTableEntityPersister(
throw new MappingException( "discriminator mapping required for single table polymorphic persistence" ); throw new MappingException( "discriminator mapping required for single table polymorphic persistence" );
} }
forceDiscriminator = persistentClass.isForceDiscriminator(); forceDiscriminator = persistentClass.isForceDiscriminator();
Selectable selectable = discrimValue.getColumnIterator().next(); Selectable selectable = discrimValue.getSelectables().get(0);
if ( discrimValue.hasFormula() ) { if ( discrimValue.hasFormula() ) {
Formula formula = (Formula) selectable; Formula formula = (Formula) selectable;
discriminatorFormula = formula.getFormula(); discriminatorFormula = formula.getFormula();
@ -371,12 +367,9 @@ else if ( persistentClass.isDiscriminatorValueNotNull() ) {
// PROPERTIES // PROPERTIES
propertyTableNumbers = new int[getPropertySpan()]; propertyTableNumbers = new int[getPropertySpan()];
Iterator<Property> props = persistentClass.getPropertyClosureIterator();
int i = 0; int i = 0;
while ( props.hasNext() ) { for ( Property property : persistentClass.getPropertyClosure() ) {
Property prop = props.next(); propertyTableNumbers[i++] = persistentClass.getJoinNumber( property );
propertyTableNumbers[i++] = persistentClass.getJoinNumber( prop );
} }
//TODO: code duplication with JoinedSubclassEntityPersister //TODO: code duplication with JoinedSubclassEntityPersister
@ -388,22 +381,18 @@ else if ( persistentClass.isDiscriminatorValueNotNull() ) {
final HashMap<String, Integer> propertyTableNumbersByNameAndSubclassLocal = new HashMap<>(); final HashMap<String, Integer> propertyTableNumbersByNameAndSubclassLocal = new HashMap<>();
final Map<Object, String> subclassesByDiscriminatorValueLocal = new HashMap<>(); final Map<Object, String> subclassesByDiscriminatorValueLocal = new HashMap<>();
Iterator<Property> iter = persistentClass.getSubclassPropertyClosureIterator(); for ( Property property : persistentClass.getSubclassPropertyClosure() ) {
while ( iter.hasNext() ) { Integer join = persistentClass.getJoinNumber( property );
Property prop = iter.next();
Integer join = persistentClass.getJoinNumber( prop );
propertyJoinNumbers.add( join ); propertyJoinNumbers.add( join );
//propertyTableNumbersByName.put( prop.getName(), join ); //propertyTableNumbersByName.put( prop.getName(), join );
propertyTableNumbersByNameAndSubclassLocal.put( propertyTableNumbersByNameAndSubclassLocal.put(
prop.getPersistentClass().getEntityName() + '.' + prop.getName(), property.getPersistentClass().getEntityName() + '.' + property.getName(),
join join
); );
Iterator<Selectable> citer = prop.getColumnIterator(); for ( Selectable selectable : property.getSelectables() ) {
while ( citer.hasNext() ) { if ( selectable.isFormula() ) {
Selectable thing = citer.next();
if ( thing.isFormula() ) {
formulaJoinedNumbers.add( join ); formulaJoinedNumbers.add( join );
} }
else { else {

View File

@ -217,9 +217,9 @@ public UnionSubclassEntityPersister(
final String tableName = determineTableName( tab ); final String tableName = determineTableName( tab );
tableNames.add( tableName ); tableNames.add( tableName );
String[] key = new String[idColumnSpan]; String[] key = new String[idColumnSpan];
Iterator<Column> citer = tab.getPrimaryKey().getColumnIterator(); List<Column> columns = tab.getPrimaryKey().getColumns();
for ( int k = 0; k < idColumnSpan; k++ ) { 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 ); keyColumns.add( key );
} }
@ -473,9 +473,8 @@ protected String generateSubquery(PersistentClass model, Mapping mapping) {
while ( titer.hasNext() ) { while ( titer.hasNext() ) {
Table table = titer.next(); Table table = titer.next();
if ( !table.isAbstractUnionTable() ) { if ( !table.isAbstractUnionTable() ) {
Iterator<Column> citer = table.getColumnIterator(); for ( Column column : table.getColumns() ) {
while ( citer.hasNext() ) { columns.add( column );
columns.add( citer.next() );
} }
} }
} }
@ -483,7 +482,6 @@ protected String generateSubquery(PersistentClass model, Mapping mapping) {
StringBuilder buf = new StringBuilder() StringBuilder buf = new StringBuilder()
.append( "( " ); .append( "( " );
@SuppressWarnings("unchecked")
Iterator<PersistentClass> siter = new JoinedIterator<>( Iterator<PersistentClass> siter = new JoinedIterator<>(
new SingletonIterator<>( model ), new SingletonIterator<>( model ),
model.getSubclassIterator() model.getSubclassIterator()

View File

@ -70,10 +70,8 @@ public static Set<Class<?>> extractProxyInterfaces(final PersistentClass persist
} }
public static void validateProxyability(final PersistentClass persistentClass) { public static void validateProxyability(final PersistentClass persistentClass) {
Iterator<?> properties = persistentClass.getPropertyIterator();
Class<?> clazz = persistentClass.getMappedClass(); Class<?> clazz = persistentClass.getMappedClass();
while ( properties.hasNext() ) { for ( Property property : persistentClass.getProperties() ) {
Property property = (Property) properties.next();
validateGetterSetterMethodProxyability( "Getter", property.getGetter( clazz ).getMethod() ); validateGetterSetterMethodProxyability( "Getter", property.getGetter( clazz ).getMethod() );
validateGetterSetterMethodProxyability( "Setter", property.getSetter( clazz ).getMethod() ); validateGetterSetterMethodProxyability( "Setter", property.getSetter( clazz ).getMethod() );
} }

View File

@ -90,10 +90,10 @@ private String columnNameOrFormula(Property property) {
if ( property.getColumnSpan()!=1 ) { if ( property.getColumnSpan()!=1 ) {
throw new MappingException("@TenantId attribute must be mapped to a single column or formula"); throw new MappingException("@TenantId attribute must be mapped to a single column or formula");
} }
Selectable column = property.getColumnIterator().next(); Selectable selectable = property.getSelectables().get(0);
return column.isFormula() return selectable.isFormula()
? ((Formula) column).getFormula() ? ((Formula) selectable).getFormula()
: ((Column) column).getName(); : ((Column) selectable).getName();
} }
} }

View File

@ -154,9 +154,8 @@ public EntityMetamodel(
if ( identifierMapperComponent != null ) { if ( identifierMapperComponent != null ) {
nonAggregatedCidMapper = (CompositeType) identifierMapperComponent.getType(); nonAggregatedCidMapper = (CompositeType) identifierMapperComponent.getType();
idAttributeNames = new HashSet<>( ); idAttributeNames = new HashSet<>( );
final Iterator<Property> propertyItr = identifierMapperComponent.getPropertyIterator(); for ( Property property : identifierMapperComponent.getProperties() ) {
while ( propertyItr.hasNext() ) { idAttributeNames.add( property.getName() );
idAttributeNames.add( propertyItr.next().getName() );
} }
} }
else { else {
@ -463,10 +462,8 @@ private static void interpretPartialCompositeValueGeneration(
SessionFactoryImplementor sessionFactory, SessionFactoryImplementor sessionFactory,
Component composite, Component composite,
CompositeGenerationStrategyPairBuilder builder) { CompositeGenerationStrategyPairBuilder builder) {
Iterator<?> subProperties = composite.getPropertyIterator(); for ( Property property : composite.getProperties() ) {
while ( subProperties.hasNext() ) { builder.addPair( buildGenerationStrategyPair( sessionFactory, property ) );
final Property subProperty = (Property) subProperties.next();
builder.addPair( buildGenerationStrategyPair( sessionFactory, subProperty ) );
} }
} }
@ -616,10 +613,8 @@ else if ( hadInDatabaseGeneration ) {
// start building the aggregate values // start building the aggregate values
int propertyIndex = -1; int propertyIndex = -1;
int columnIndex = 0; int columnIndex = 0;
Iterator<?> subProperties = composite.getPropertyIterator(); for ( Property property : composite.getProperties() ) {
while ( subProperties.hasNext() ) {
propertyIndex++; propertyIndex++;
final Property subProperty = (Property) subProperties.next();
final InDatabaseValueGenerationStrategy subStrategy = inDatabaseStrategies.get( propertyIndex ); final InDatabaseValueGenerationStrategy subStrategy = inDatabaseStrategies.get( propertyIndex );
if ( subStrategy.getGenerationTiming() == GenerationTiming.ALWAYS ) { if ( subStrategy.getGenerationTiming() == GenerationTiming.ALWAYS ) {
@ -632,11 +627,11 @@ else if ( hadInDatabaseGeneration ) {
referenceColumns = true; referenceColumns = true;
} }
if ( subStrategy.getReferencedColumnValues() != null ) { if ( subStrategy.getReferencedColumnValues() != null ) {
if ( subStrategy.getReferencedColumnValues().length != subProperty.getColumnSpan() ) { if ( subStrategy.getReferencedColumnValues().length != property.getColumnSpan() ) {
throw new ValueGenerationStrategyException( throw new ValueGenerationStrategyException(
"Internal error : mismatch between number of collected 'referenced column values'" + "Internal error : mismatch between number of collected 'referenced column values'" +
" and number of columns for composite attribute : " + mappingProperty.getName() + " and number of columns for composite attribute : " + mappingProperty.getName() +
'.' + subProperty.getName() '.' + property.getName()
); );
} }
System.arraycopy( System.arraycopy(
@ -644,7 +639,7 @@ else if ( hadInDatabaseGeneration ) {
0, 0,
columnValues, columnValues,
columnIndex, columnIndex,
subProperty.getColumnSpan() property.getColumnSpan()
); );
} }
} }
@ -760,9 +755,8 @@ public String[] getReferencedColumnValues() {
private void mapPropertyToIndex(Property prop, int i) { private void mapPropertyToIndex(Property prop, int i) {
propertyIndexes.put( prop.getName(), i ); propertyIndexes.put( prop.getName(), i );
if ( prop.getValue() instanceof Component ) { if ( prop.getValue() instanceof Component ) {
Iterator<?> iter = ( (Component) prop.getValue() ).getPropertyIterator(); Component composite = (Component) prop.getValue();
while ( iter.hasNext() ) { for ( Property subprop : composite.getProperties() ) {
Property subprop = (Property) iter.next();
propertyIndexes.put( propertyIndexes.put(
prop.getName() + '.' + subprop.getName(), prop.getName() + '.' + subprop.getName(),
i i

View File

@ -82,10 +82,8 @@ public ComponentType(Component component, int[] originalPropertyOrder, MetadataB
this.cascade = new CascadeStyle[propertySpan]; this.cascade = new CascadeStyle[propertySpan];
this.joinedFetch = new FetchMode[propertySpan]; this.joinedFetch = new FetchMode[propertySpan];
final Iterator<Property> itr = component.getPropertyIterator();
int i = 0; int i = 0;
while ( itr.hasNext() ) { for ( Property property : component.getProperties() ) {
final Property property = itr.next();
// todo (6.0) : see if we really need to create these // todo (6.0) : see if we really need to create these
final StandardProperty prop = PropertyFactory.buildStandardProperty( property, false ); final StandardProperty prop = PropertyFactory.buildStandardProperty( property, false );
this.propertyNames[i] = prop.getName(); this.propertyNames[i] = prop.getName();

View File

@ -118,7 +118,7 @@ public void setParameterValues(Properties parameters) {
// the `reader != null` block handles annotations, while the `else` block // the `reader != null` block handles annotations, while the `else` block
// handles hbm.xml // handles hbm.xml
if ( reader != null ) { if ( reader != null ) {
enumClass = reader.getReturnedClass().asSubclass( Enum.class ); enumClass = (Class<T>) reader.getReturnedClass().asSubclass( Enum.class );
final Long columnLength = reader.getColumnLengths()[0]; final Long columnLength = reader.getColumnLengths()[0];

View File

@ -73,7 +73,7 @@ public void setParameterValues(Properties parameters) {
ParameterType reader = (ParameterType) parameters.get( PARAMETER_TYPE ); ParameterType reader = (ParameterType) parameters.get( PARAMETER_TYPE );
if ( reader != null ) { if ( reader != null ) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Class<T> returnedClass = reader.getReturnedClass(); Class<T> returnedClass = (Class<T>) reader.getReturnedClass();
setJavaTypeDescriptor( new SerializableJavaType<>(returnedClass) ); setJavaTypeDescriptor( new SerializableJavaType<>(returnedClass) );
} }
else { else {

View File

@ -32,7 +32,7 @@ public interface DynamicParameterizedType extends ParameterizedType {
interface ParameterType { interface ParameterType {
Class getReturnedClass(); Class<?> getReturnedClass();
Annotation[] getAnnotationsMethod(); Annotation[] getAnnotationsMethod();

View File

@ -32,11 +32,10 @@
* *
* @author Hardy Ferentschik * @author Hardy Ferentschik
*/ */
@SuppressWarnings("unchecked")
public class ImmutableTest extends BaseCoreFunctionalTestCase { public class ImmutableTest extends BaseCoreFunctionalTestCase {
@Test @Test
public void testImmutableEntity() throws Exception { public void testImmutableEntity() {
Session s = openSession(); Session s = openSession();
Transaction tx = s.beginTransaction(); Transaction tx = s.beginTransaction();
Country country = new Country(); Country country = new Country();
@ -48,7 +47,7 @@ public void testImmutableEntity() throws Exception {
// try changing the entity // try changing the entity
s = openSession(); s = openSession();
tx = s.beginTransaction(); tx = s.beginTransaction();
Country germany = (Country) s.get(Country.class, country.getId()); Country germany = s.get(Country.class, country.getId());
assertNotNull(germany); assertNotNull(germany);
germany.setName("France"); germany.setName("France");
assertEquals("Local name can be changed", "France", germany.getName()); assertEquals("Local name can be changed", "France", germany.getName());
@ -59,7 +58,7 @@ public void testImmutableEntity() throws Exception {
// retrieving the country again - it should be unmodified // retrieving the country again - it should be unmodified
s = openSession(); s = openSession();
tx = s.beginTransaction(); tx = s.beginTransaction();
germany = (Country) s.get(Country.class, country.getId()); germany = s.get(Country.class, country.getId());
assertNotNull(germany); assertNotNull(germany);
assertEquals("Name should not have changed", "Germany", germany.getName()); assertEquals("Name should not have changed", "Germany", germany.getName());
tx.commit(); tx.commit();
@ -70,7 +69,7 @@ public void testImmutableEntity() throws Exception {
public void testImmutableCollection() { public void testImmutableCollection() {
Country country = new Country(); Country country = new Country();
country.setName("Germany"); country.setName("Germany");
List states = new ArrayList<State>(); List<State> states = new ArrayList<>();
State bayern = new State(); State bayern = new State();
bayern.setName("Bayern"); bayern.setName("Bayern");
State hessen = new State(); State hessen = new State();
@ -90,7 +89,7 @@ public void testImmutableCollection() {
s = openSession(); s = openSession();
tx = s.beginTransaction(); tx = s.beginTransaction();
Country germany = (Country) s.get(Country.class, country.getId()); Country germany = s.get(Country.class, country.getId());
assertNotNull(germany); assertNotNull(germany);
assertEquals("Wrong number of states", 3, germany.getStates().size()); assertEquals("Wrong number of states", 3, germany.getStates().size());
@ -112,7 +111,7 @@ public void testImmutableCollection() {
s = openSession(); s = openSession();
tx = s.beginTransaction(); tx = s.beginTransaction();
germany = (Country) s.get(Country.class, country.getId()); germany = s.get(Country.class, country.getId());
assertNotNull(germany); assertNotNull(germany);
assertEquals("Wrong number of states", 3, germany.getStates().size()); assertEquals("Wrong number of states", 3, germany.getStates().size());
@ -129,7 +128,7 @@ public void testImmutableCollection() {
s = openSession(); s = openSession();
tx = s.beginTransaction(); tx = s.beginTransaction();
germany = (Country) s.get(Country.class, country.getId()); germany = s.get(Country.class, country.getId());
assertNotNull(germany); assertNotNull(germany);
assertEquals("Wrong number of states", 3, germany.getStates().size()); assertEquals("Wrong number of states", 3, germany.getStates().size());
tx.commit(); tx.commit();

View File

@ -22,7 +22,6 @@
import jakarta.persistence.OneToOne; import jakarta.persistence.OneToOne;
import jakarta.persistence.Table; import jakarta.persistence.Table;
import org.hibernate.Hibernate;
import org.hibernate.annotations.LazyGroup; import org.hibernate.annotations.LazyGroup;
import org.hibernate.boot.MetadataSources; import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.SessionFactoryBuilder; import org.hibernate.boot.SessionFactoryBuilder;

View File

@ -108,7 +108,7 @@
@RequiresDialectFeature(DialectChecks.SupportsTemporaryTable.class) @RequiresDialectFeature(DialectChecks.SupportsTemporaryTable.class)
public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase { public class ASTParserLoadingTest extends BaseCoreFunctionalTestCase {
private List<Long> createdAnimalIds = new ArrayList<>(); private final List<Long> createdAnimalIds = new ArrayList<>();
@After @After
public void cleanUpTestData() { public void cleanUpTestData() {

View File

@ -34,7 +34,7 @@ public String[] getMappings() {
} }
@Test @Test
public void testSellCar() throws Exception { public void testSellCar() {
prepareData(); prepareData();
Session session = openSession(); Session session = openSession();
Transaction tx = session.beginTransaction(); Transaction tx = session.beginTransaction();
@ -54,7 +54,6 @@ private void prepareData() {
session.close(); session.close();
} }
@SuppressWarnings( {"unchecked"})
private Object createData() { private Object createData() {
Seller stliu = new Seller(); Seller stliu = new Seller();
stliu.setId( createID( "stliu" ) ); stliu.setId( createID( "stliu" ) );
@ -69,7 +68,7 @@ private Object createData() {
private PersonID createID( String name ) { private PersonID createID( String name ) {
PersonID id = new PersonID(); PersonID id = new PersonID();
id.setName( name ); id.setName( name );
id.setNum( Long.valueOf( 100 ) ); id.setNum(100L);
return id; return id;
} }
} }