diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractDiscriminatorMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractDiscriminatorMapping.java index ff37b60512b1..451b1f45099f 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractDiscriminatorMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractDiscriminatorMapping.java @@ -19,7 +19,6 @@ import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.spi.NavigablePath; import org.hibernate.sql.ast.spi.SqlAstCreationState; -import org.hibernate.sql.ast.spi.SqlExpressionResolver; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.from.TableGroup; import org.hibernate.sql.results.graph.DomainResult; @@ -49,10 +48,8 @@ public AbstractDiscriminatorMapping( BasicType underlyingJdbcMapping) { this.underlyingJdbcMapping = underlyingJdbcMapping; this.mappingType = mappingType; - - this.role = mappingType.getNavigableRole().append( DISCRIMINATOR_ROLE_NAME ); - this.discriminatorType = discriminatorType; + this.role = mappingType.getNavigableRole().append( DISCRIMINATOR_ROLE_NAME ); } public EntityMappingType getEntityDescriptor() { @@ -106,7 +103,7 @@ public DomainResult createDomainResult( String resultVariable, DomainResultCreationState creationState) { // create a SqlSelection based on the underlying JdbcMapping - final SqlSelection sqlSelection = resolveSqlSelection( + final var sqlSelection = resolveSqlSelection( navigablePath, underlyingJdbcMapping, tableGroup, @@ -132,8 +129,7 @@ private SqlSelection resolveSqlSelection( TableGroup tableGroup, FetchParent fetchParent, SqlAstCreationState creationState) { - final SqlExpressionResolver expressionResolver = creationState.getSqlExpressionResolver(); - return expressionResolver.resolveSqlSelection( + return creationState.getSqlExpressionResolver().resolveSqlSelection( resolveSqlExpression( navigablePath, jdbcMappingToUse, tableGroup, creationState ), jdbcMappingToUse.getJdbcJavaType(), fetchParent, @@ -149,15 +145,13 @@ public BasicFetch generateFetch( boolean selected, String resultVariable, DomainResultCreationState creationState) { - final SqlAstCreationState sqlAstCreationState = creationState.getSqlAstCreationState(); - final TableGroup tableGroup = sqlAstCreationState.getFromClauseAccess().getTableGroup( - fetchParent.getNavigablePath() - ); - + final var tableGroup = + creationState.getSqlAstCreationState().getFromClauseAccess() + .getTableGroup( fetchParent.getNavigablePath() ); assert tableGroup != null; // create a SqlSelection based on the underlying JdbcMapping - final SqlSelection sqlSelection = resolveSqlSelection( + final var sqlSelection = resolveSqlSelection( fetchablePath, underlyingJdbcMapping, tableGroup, diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractDomainPath.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractDomainPath.java index b065d3e29d5c..be1ce030c509 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractDomainPath.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractDomainPath.java @@ -8,7 +8,6 @@ import java.util.List; import jakarta.persistence.criteria.Nulls; -import org.hibernate.metamodel.mapping.BasicValuedModelPart; import org.hibernate.metamodel.mapping.EmbeddableValuedModelPart; import org.hibernate.metamodel.mapping.EntityValuedModelPart; import org.hibernate.metamodel.mapping.ForeignKeyDescriptor; @@ -18,17 +17,14 @@ import org.hibernate.metamodel.mapping.ordering.ast.OrderingExpression; import org.hibernate.query.SortDirection; import org.hibernate.sql.ast.spi.SqlAstCreationState; -import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.SqlAstNode; import org.hibernate.sql.ast.tree.expression.ColumnReference; import org.hibernate.sql.ast.tree.expression.Expression; import org.hibernate.sql.ast.tree.expression.SqlTuple; import org.hibernate.sql.ast.tree.from.TableGroup; -import org.hibernate.sql.ast.tree.from.TableReference; import org.hibernate.sql.ast.tree.select.QuerySpec; import org.hibernate.sql.ast.tree.select.SelectClause; import org.hibernate.sql.ast.tree.select.SortSpecification; -import org.hibernate.sql.results.graph.Fetchable; import org.hibernate.sql.results.internal.SqlSelectionImpl; import static org.hibernate.internal.util.NullnessUtil.castNonNull; @@ -61,9 +57,9 @@ public Expression resolve( TableGroup tableGroup, String modelPartName, SqlAstCreationState creationState) { - final BasicValuedModelPart selection = referenceModelPart.asBasicValuedModelPart(); + final var selection = referenceModelPart.asBasicValuedModelPart(); if ( selection != null ) { - final TableReference tableReference = tableGroup.resolveTableReference( + final var tableReference = tableGroup.resolveTableReference( null, selection, selection.getContainingTableExpression() @@ -81,7 +77,7 @@ public Expression resolve( ); } else if ( referenceModelPart instanceof EntityValuedModelPart entityValuedModelPart ) { - final ModelPart subPart = + final var subPart = ELEMENT_TOKEN.equals( modelPartName ) ? entityValuedModelPart.getEntityMappingType().getIdentifierMapping() : entityValuedModelPart.findSubPart( modelPartName ); @@ -93,13 +89,13 @@ else if ( referenceModelPart instanceof EmbeddableValuedModelPart embeddableValu final int size = embeddableValuedModelPart.getNumberOfFetchables(); final List expressions = new ArrayList<>( size ); for ( int i = 0; i < size; i++ ) { - final Fetchable fetchable = embeddableValuedModelPart.getFetchable( i ); + final var fetchable = embeddableValuedModelPart.getFetchable( i ); expressions.add( resolve( fetchable, ast, tableGroup, modelPartName, creationState ) ); } return new SqlTuple( expressions, embeddableValuedModelPart ); } else { - ModelPart subPart = embeddableValuedModelPart.findSubPart( modelPartName, null ); + final var subPart = embeddableValuedModelPart.findSubPart( modelPartName, null ); assert subPart.asBasicValuedModelPart() != null; return resolve( subPart, ast, tableGroup, modelPartName, creationState ); } @@ -140,7 +136,7 @@ private void apply( SortDirection sortOrder, Nulls nullPrecedence, SqlAstCreationState creationState) { - final BasicValuedModelPart basicPart = referenceModelPart.asBasicValuedModelPart(); + final var basicPart = referenceModelPart.asBasicValuedModelPart(); if ( basicPart != null ) { addSortSpecification( basicPart, @@ -153,10 +149,11 @@ private void apply( ); } else if ( referenceModelPart instanceof EntityValuedModelPart entityValuedModelPart ) { - final ModelPart subPart = ELEMENT_TOKEN.equals( modelPartName ) - ? entityValuedModelPart.getEntityMappingType().getIdentifierMapping() - // Default to using the foreign key of an entity valued model part - : entityValuedModelPart.findSubPart( ForeignKeyDescriptor.PART_NAME ); + final var subPart = + ELEMENT_TOKEN.equals( modelPartName ) + ? entityValuedModelPart.getEntityMappingType().getIdentifierMapping() + // Default to using the foreign key of an entity valued model part + : entityValuedModelPart.findSubPart( ForeignKeyDescriptor.PART_NAME ); apply( subPart, ast, @@ -195,8 +192,8 @@ private void addSortSpecification( SortDirection sortOrder, Nulls nullPrecedence, SqlAstCreationState creationState) { - if ( embeddableValuedModelPart.getFetchableName() - .equals( modelPartName ) || ELEMENT_TOKEN.equals( modelPartName ) ) { + if ( embeddableValuedModelPart.getFetchableName().equals( modelPartName ) + || ELEMENT_TOKEN.equals( modelPartName ) ) { embeddableValuedModelPart.forEachSelectable( (columnIndex, selection) -> { addSortSpecification( @@ -212,7 +209,7 @@ private void addSortSpecification( ); } else { - ModelPart subPart = embeddableValuedModelPart.findSubPart( modelPartName, null ); + final var subPart = embeddableValuedModelPart.findSubPart( modelPartName, null ); addSortSpecification( castNonNull( subPart.asBasicValuedModelPart() ), ast, @@ -233,49 +230,43 @@ private void addSortSpecification( SortDirection sortOrder, Nulls nullPrecedence, SqlAstCreationState creationState) { - final TableReference tableReference = tableGroup.resolveTableReference( null, selection.getContainingTableExpression() ); - final Expression expression = creationState.getSqlExpressionResolver().resolveSqlExpression( - createColumnReferenceKey( - tableReference, - selection.getSelectionExpression(), - selection.getJdbcMapping() - ), - processingState -> new ColumnReference( - tableReference, - selection - ) - ); + final var tableReference = + tableGroup.resolveTableReference( null, + selection.getContainingTableExpression() ); + final var expression = + creationState.getSqlExpressionResolver() + .resolveSqlExpression( + createColumnReferenceKey( + tableReference, + selection.getSelectionExpression(), + selection.getJdbcMapping() + ), + processingState -> new ColumnReference( tableReference, selection ) + ); // It makes no sense to order by an expression multiple times // SQL Server even reports a query error in this case if ( ast.hasSortSpecifications() ) { - for ( SortSpecification sortSpecification : ast.getSortSpecifications() ) { + for ( var sortSpecification : ast.getSortSpecifications() ) { if ( sortSpecification.getSortExpression() == expression ) { return; } } } - final SelectClause selectClause = ast.getSelectClause(); - - if ( selectClause.isDistinct() && selectClauseDoesNotContainOrderExpression( expression, selectClause ) ) { + final var selectClause = ast.getSelectClause(); + if ( selectClause.isDistinct() + && selectClauseDoesNotContainOrderExpression( expression, selectClause ) ) { final int valuesArrayPosition = selectClause.getSqlSelections().size(); - SqlSelection sqlSelection = new SqlSelectionImpl( - valuesArrayPosition, - expression - ); - selectClause.addSqlSelection( sqlSelection ); + selectClause.addSqlSelection( new SqlSelectionImpl( valuesArrayPosition, expression ) ); } - final Expression sortExpression = OrderingExpression.applyCollation( - expression, - collation, - creationState - ); + final var sortExpression = + OrderingExpression.applyCollation( expression, collation, creationState ); ast.addSortSpecification( new SortSpecification( sortExpression, sortOrder, nullPrecedence ) ); } private static boolean selectClauseDoesNotContainOrderExpression(Expression expression, SelectClause selectClause) { - for ( SqlSelection sqlSelection : selectClause.getSqlSelections() ) { + for ( var sqlSelection : selectClause.getSqlSelections() ) { if ( sqlSelection.getExpression().equals( expression ) ) { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractEmbeddableMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractEmbeddableMapping.java index 7294fc0a1c7a..006d8e2d04a4 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractEmbeddableMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractEmbeddableMapping.java @@ -13,13 +13,9 @@ import org.hibernate.MappingException; import org.hibernate.SharedSessionContract; -import org.hibernate.bytecode.spi.ReflectionOptimizer; import org.hibernate.cache.MutableCacheKeyBuilder; -import org.hibernate.dialect.Dialect; import org.hibernate.engine.FetchTiming; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; -import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.engine.spi.CascadeStyle; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.internal.util.IndexedConsumer; import org.hibernate.internal.util.collections.CollectionHelper; @@ -27,9 +23,7 @@ import org.hibernate.mapping.BasicValue; import org.hibernate.mapping.Column; import org.hibernate.mapping.Component; -import org.hibernate.mapping.Property; import org.hibernate.mapping.Selectable; -import org.hibernate.mapping.Value; import org.hibernate.metamodel.UnsupportedMappingException; import org.hibernate.metamodel.mapping.AttributeMapping; import org.hibernate.metamodel.mapping.AttributeMappingsList; @@ -37,7 +31,6 @@ import org.hibernate.metamodel.mapping.EmbeddableMappingType; import org.hibernate.metamodel.mapping.EmbeddableValuedModelPart; import org.hibernate.metamodel.mapping.EntityMappingType; -import org.hibernate.metamodel.mapping.ForeignKeyDescriptor; import org.hibernate.metamodel.mapping.JdbcMapping; import org.hibernate.metamodel.mapping.ManagedMappingType; import org.hibernate.metamodel.mapping.ModelPart; @@ -49,7 +42,6 @@ import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.metamodel.spi.EmbeddableInstantiator; import org.hibernate.metamodel.spi.EmbeddableRepresentationStrategy; -import org.hibernate.persister.entity.EntityPersister; import org.hibernate.property.access.internal.PropertyAccessStrategyBackRefImpl; import org.hibernate.property.access.spi.Getter; import org.hibernate.property.access.spi.PropertyAccess; @@ -65,7 +57,6 @@ import org.hibernate.type.descriptor.java.ImmutableMutabilityPlan; import org.hibernate.type.descriptor.java.JavaType; import org.hibernate.type.descriptor.java.MutabilityPlan; -import org.hibernate.type.spi.TypeConfiguration; /** * Base support for EmbeddableMappingType implementations @@ -132,7 +123,7 @@ public Object[] getValues(Object compositeInstance) { return new Object[getNumberOfAttributeMappings()]; } - final ReflectionOptimizer optimizer = getRepresentationStrategy().getReflectionOptimizer(); + final var optimizer = getRepresentationStrategy().getReflectionOptimizer(); if ( optimizer != null && optimizer.getAccessOptimizer() != null ) { return optimizer.getAccessOptimizer().getPropertyValues( compositeInstance ); } @@ -150,7 +141,7 @@ protected Object[] getAttributeValues(Object compositeInstance) { @Override public void setValues(Object component, Object[] values) { - final ReflectionOptimizer optimizer = getRepresentationStrategy().getReflectionOptimizer(); + final var optimizer = getRepresentationStrategy().getReflectionOptimizer(); if ( optimizer != null && optimizer.getAccessOptimizer() != null ) { optimizer.getAccessOptimizer().setPropertyValues( component, values ); } @@ -202,9 +193,9 @@ protected boolean inverseInitializeCallback( int currentIndex = 0; // We copy the attributes from the inverse mappings and replace the selection mappings for ( int j = 0; j < size; j++ ) { - AttributeMapping attributeMapping = inverseMappingType.getAttributeMapping( j ); + var attributeMapping = inverseMappingType.getAttributeMapping( j ); if ( attributeMapping instanceof BasicAttributeMapping original ) { - final SelectableMapping selectableMapping = selectableMappings.getSelectable( currentIndex ); + final var selectableMapping = selectableMappings.getSelectable( currentIndex ); attributeMapping = BasicAttributeMapping.withSelectableMapping( declaringType, original, @@ -216,7 +207,7 @@ protected boolean inverseInitializeCallback( currentIndex++; } else if ( attributeMapping instanceof ToOneAttributeMapping original ) { - ForeignKeyDescriptor foreignKeyDescriptor = original.getForeignKeyDescriptor(); + final var foreignKeyDescriptor = original.getForeignKeyDescriptor(); if ( foreignKeyDescriptor == null ) { // This is expected to happen when processing a // PostInitCallbackEntry because the callbacks @@ -225,10 +216,7 @@ else if ( attributeMapping instanceof ToOneAttributeMapping original ) { // and the callback is re-queued. throw new IllegalStateException( "Not yet ready: " + original ); } - final ToOneAttributeMapping toOne = original.copy( - declaringType, - declaringTableGroupProducer - ); + final var toOne = original.copy( declaringType, declaringTableGroupProducer ); final int offset = currentIndex; toOne.setIdentifyingColumnsTableExpression( selectableMappings.getSelectable( offset ).getContainingTableExpression() @@ -247,7 +235,7 @@ else if ( attributeMapping instanceof ToOneAttributeMapping original ) { currentIndex += attributeMapping.getJdbcTypeCount(); } else if ( attributeMapping instanceof EmbeddableValuedModelPart embeddableValuedModelPart ) { - final SelectableMapping[] subMappings = new SelectableMapping[attributeMapping.getJdbcTypeCount()]; + final var subMappings = new SelectableMapping[attributeMapping.getJdbcTypeCount()]; for ( int i = 0; i < subMappings.length; i++ ) { subMappings[i] = selectableMappings.getSelectable( currentIndex++ ); } @@ -282,25 +270,26 @@ protected boolean finishInitialization( Consumer attributeConsumer, SuccessfulCompletionCallback completionCallback, MappingModelCreationProcess creationProcess) { - final TypeConfiguration typeConfiguration = creationProcess.getCreationContext().getTypeConfiguration(); - final JdbcServices jdbcServices = creationProcess.getCreationContext().getJdbcServices(); - final JdbcEnvironment jdbcEnvironment = jdbcServices.getJdbcEnvironment(); - final Dialect dialect = jdbcEnvironment.getDialect(); + final var creationContext = creationProcess.getCreationContext(); + final var typeConfiguration = creationContext.getTypeConfiguration(); + final var jdbcServices = creationContext.getJdbcServices(); + final var jdbcEnvironment = jdbcServices.getJdbcEnvironment(); + final var dialect = jdbcEnvironment.getDialect(); - final Type[] subtypes = compositeType.getSubtypes(); + final var subtypes = compositeType.getSubtypes(); int attributeIndex = 0; int columnPosition = 0; - for ( Property bootPropertyDescriptor : bootDescriptor.getProperties() ) { - final Type subtype = subtypes[ attributeIndex ]; + for ( var bootPropertyDescriptor : bootDescriptor.getProperties() ) { + final var subtype = subtypes[ attributeIndex ]; attributeTypeValidator.check( bootPropertyDescriptor.getName(), subtype ); - final PropertyAccess propertyAccess = representationStrategy.resolvePropertyAccess( bootPropertyDescriptor ); + final var propertyAccess = representationStrategy.resolvePropertyAccess( bootPropertyDescriptor ); final AttributeMapping attributeMapping; - final Value value = bootPropertyDescriptor.getValue(); + final var value = bootPropertyDescriptor.getValue(); if ( subtype instanceof BasicType ) { final BasicValue basicValue = (BasicValue) value; final Selectable selectable = basicValue.getColumn(); @@ -310,7 +299,7 @@ protected boolean finishInitialization( if ( selectable.isFormula() ) { columnExpression = selectable.getTemplate( dialect, - creationProcess.getCreationContext().getTypeConfiguration() + creationContext.getTypeConfiguration() ); } else { @@ -328,7 +317,7 @@ protected boolean finishInitialization( containingTableExpression = rootTableExpression; columnExpression = rootTableKeyColumnNames[ columnPosition ]; } - final NavigableRole role = navigableRole.append( bootPropertyDescriptor.getName() ); + final var role = navigableRole.append( bootPropertyDescriptor.getName() ); final SelectablePath selectablePath; final String columnDefinition; final Long length; @@ -346,7 +335,7 @@ protected boolean finishInitialization( scale = column.getScale(); temporalPrecision = column.getTemporalPrecision(); nullable = column.isNullable(); - isLob = column.isSqlTypeLob( creationProcess.getCreationContext().getMetadata() ); + isLob = column.isSqlTypeLob( creationContext.getMetadata() ); selectablePath = basicValue.createSelectablePath( column.getQuotedName( dialect ) ); MappingModelCreationHelper.resolveAggregateColumnBasicType( creationProcess, role, column ); } @@ -378,7 +367,7 @@ protected boolean finishInitialization( selectable.getWriteExpr( basicValue.getResolution().getJdbcMapping(), dialect, - creationProcess.getCreationContext().getBootModel() + creationContext.getBootModel() ), columnDefinition, length, @@ -398,15 +387,15 @@ protected boolean finishInitialization( columnPosition++; } else if ( subtype instanceof AnyType anyType ) { - final Any bootValueMapping = (Any) value; + final var bootValueMapping = (Any) value; final boolean nullable = bootValueMapping.isNullable(); final boolean insertable = value.isColumnInsertable( 0 ); final boolean updateable = value.isColumnUpdateable( 0 ); final boolean includeInOptimisticLocking = bootPropertyDescriptor.isOptimisticLocked(); - final CascadeStyle cascadeStyle = compositeType.getCascadeStyle( attributeIndex ); + final var cascadeStyle = compositeType.getCascadeStyle( attributeIndex ); - SimpleAttributeMetadata attributeMetadataAccess = new SimpleAttributeMetadata( + final var attributeMetadataAccess = new SimpleAttributeMetadata( propertyAccess, getMutabilityPlan( updateable ), nullable, @@ -433,7 +422,8 @@ else if ( subtype instanceof AnyType anyType ) { ); } else if ( subtype instanceof CompositeType subCompositeType ) { - final int columnSpan = subCompositeType.getColumnSpan( creationProcess.getCreationContext().getMetadata() ); + final int columnSpan = + subCompositeType.getColumnSpan( creationContext.getMetadata() ); final String subTableExpression; final String[] subRootTableKeyColumnNames; if ( rootTableKeyColumnNames == null ) { @@ -476,9 +466,6 @@ else if ( subtype instanceof CollectionType ) { ); } else if ( subtype instanceof EntityType ) { - final EntityPersister entityPersister = - creationProcess.getEntityPersister( bootDescriptor.getOwner().getEntityName() ); - attributeMapping = MappingModelCreationHelper.buildSingularAssociationAttributeMapping( bootPropertyDescriptor.getName(), navigableRole.append( bootPropertyDescriptor.getName() ), @@ -486,7 +473,7 @@ else if ( subtype instanceof EntityType ) { attributeIndex, bootPropertyDescriptor, this, - entityPersister, + creationProcess.getEntityPersister( bootDescriptor.getOwner().getEntityName() ), (EntityType) subtype, representationStrategy.resolvePropertyAccess( bootPropertyDescriptor ), compositeType.getCascadeStyle( attributeIndex ), @@ -515,7 +502,7 @@ else if ( subtype instanceof EntityType ) { } protected String determineEmbeddablePrefix() { - NavigableRole root = getNavigableRole().getParent(); + var root = getNavigableRole().getParent(); while ( !root.isRoot() ) { root = root.getParent(); } @@ -554,11 +541,11 @@ public AttributeMapping getAttributeMapping(int position) { @Override public AttributeMapping findAttributeMapping(String name) { - final AttributeMappingsList attributes = getAttributeMappings(); + final var attributes = getAttributeMappings(); for ( int i = 0; i < attributes.size(); i++ ) { - final AttributeMapping attr = attributes.get( i ); - if ( name.equals( attr.getAttributeName() ) ) { - return attr; + final var attribute = attributes.get( i ); + if ( name.equals( attribute.getAttributeName() ) ) { + return attribute; } } return null; @@ -631,7 +618,7 @@ public ModelPart findSubPart(String name, EntityMappingType treatTargetType) { @Override public void forEachSubPart(IndexedConsumer consumer, EntityMappingType treatTarget) { - final AttributeMappingsList attributes = getAttributeMappings(); + final var attributes = getAttributeMappings(); for ( int i = 0; i < attributes.size(); i++ ) { consumer.accept( i, attributes.get(i) ); } @@ -652,13 +639,13 @@ public int breakDownJdbcValues( int span = 0; if ( domainValue == null ) { for ( int i = 0; i < attributeMappings.size(); i++ ) { - final AttributeMapping attribute = attributeMappings.get( i ); + final var attribute = attributeMappings.get( i ); span += attribute.breakDownJdbcValues( null, offset + span, x, y, valueConsumer, session ); } } else { for ( int i = 0; i < attributeMappings.size(); i++ ) { - final AttributeMapping attribute = attributeMappings.get( i ); + final var attribute = attributeMappings.get( i ); final Object attributeValue = attribute.getValue( domainValue ); span += attribute.breakDownJdbcValues( attributeValue, offset + span, x, y, valueConsumer, session ); } @@ -674,9 +661,9 @@ public Object disassemble(Object value, SharedSessionContractImplementor session final int size = attributeMappings.size(); final Object[] result = new Object[ size ]; for ( int i = 0; i < size; i++ ) { - final AttributeMapping attributeMapping = attributeMappings.get( i ); - final Object o = attributeMapping.getValue( value ); - result[i] = attributeMapping.disassemble( o, session ); + final var attributeMapping = attributeMappings.get( i ); + final Object object = attributeMapping.getValue( value ); + result[i] = attributeMapping.disassemble( object, session ); } return result; @@ -692,7 +679,7 @@ public void addToCacheKey(MutableCacheKeyBuilder cacheKey, Object value, SharedS } else { for ( int i = 0; i < size; i++ ) { - final AttributeMapping attributeMapping = attributeMappings.get( i ); + final var attributeMapping = attributeMappings.get( i ); attributeMapping.addToCacheKey( cacheKey, attributeMapping.getValue( value ), session ); } } @@ -716,14 +703,14 @@ public int forEachDisassembledJdbcValue( int span = 0; if ( value == null ) { for ( int i = 0; i < attributeMappings.size(); i++ ) { - final AttributeMapping mapping = attributeMappings.get( i ); + final var mapping = attributeMappings.get( i ); span += mapping.forEachDisassembledJdbcValue( null, span + offset, x, y, valuesConsumer, session ); } } else { final Object[] values = (Object[]) value; for ( int i = 0; i < attributeMappings.size(); i++ ) { - final AttributeMapping mapping = attributeMappings.get( i ); + final var mapping = attributeMappings.get( i ); span += mapping.forEachDisassembledJdbcValue( values[i], span + offset, x, y, valuesConsumer, session ); } } @@ -741,7 +728,7 @@ public int forEachJdbcValue( int span = 0; if ( value == null ) { for ( int i = 0; i < attributeMappings.size(); i++ ) { - final AttributeMapping attributeMapping = attributeMappings.get( i ); + final var attributeMapping = attributeMappings.get( i ); if ( !(attributeMapping instanceof PluralAttributeMapping) ) { span += attributeMapping.forEachJdbcValue( null, span + offset, x, y, valuesConsumer, session ); } @@ -749,7 +736,7 @@ public int forEachJdbcValue( } else { for ( int i = 0; i < attributeMappings.size(); i++ ) { - final AttributeMapping attributeMapping = attributeMappings.get( i ); + final var attributeMapping = attributeMappings.get( i ); if ( !(attributeMapping instanceof PluralAttributeMapping) ) { span += attributeMapping.forEachJdbcValue( getValue( value, i ), span + offset, x, y, valuesConsumer, session ); } @@ -761,7 +748,7 @@ public int forEachJdbcValue( protected void addAttribute(AttributeMapping attributeMapping) { // check if we've already seen this attribute... for ( int i = 0; i < attributeMappings.size(); i++ ) { - final AttributeMapping previous = attributeMappings.get( i ); + final var previous = attributeMappings.get( i ); if ( attributeMapping.getAttributeName().equals( previous.getAttributeName() ) ) { attributeMappings.setAttributeMapping( i, attributeMapping ); return; diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractEntityCollectionPart.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractEntityCollectionPart.java index 47948a4a0ba1..e7418e75dd38 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractEntityCollectionPart.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractEntityCollectionPart.java @@ -15,7 +15,6 @@ import org.hibernate.mapping.Collection; import org.hibernate.mapping.IndexedCollection; import org.hibernate.mapping.OneToMany; -import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.ToOne; import org.hibernate.mapping.Value; import org.hibernate.metamodel.mapping.AssociationKey; @@ -27,13 +26,11 @@ import org.hibernate.spi.NavigablePath; import org.hibernate.sql.ast.spi.FromClauseAccess; import org.hibernate.sql.ast.spi.SqlAliasBase; -import org.hibernate.sql.ast.spi.SqlAstCreationContext; import org.hibernate.sql.ast.spi.SqlAstCreationState; import org.hibernate.sql.ast.tree.from.PluralTableGroup; import org.hibernate.sql.ast.tree.from.StandardTableGroup; import org.hibernate.sql.ast.tree.from.TableGroup; import org.hibernate.sql.ast.tree.from.TableGroupProducer; -import org.hibernate.sql.ast.tree.from.TableReference; import org.hibernate.sql.results.graph.DomainResult; import org.hibernate.sql.results.graph.DomainResultCreationState; import org.hibernate.sql.results.graph.FetchOptions; @@ -214,11 +211,11 @@ public EntityFetch generateFetch( boolean selected, String resultVariable, DomainResultCreationState creationState) { - final AssociationKey associationKey = resolveFetchAssociationKey(); + final var associationKey = resolveFetchAssociationKey(); final boolean added = creationState.registerVisitedAssociationKey( associationKey ); - final TableGroup partTableGroup = resolveTableGroup( fetchablePath, creationState ); - final EntityFetch fetch = buildEntityFetchJoined( + final var partTableGroup = resolveTableGroup( fetchablePath, creationState ); + final var fetch = buildEntityFetchJoined( fetchParent, this, partTableGroup, @@ -273,19 +270,15 @@ protected EntityFetch buildEntityFetchJoined( protected abstract AssociationKey resolveFetchAssociationKey(); private TableGroup resolveTableGroup(NavigablePath fetchablePath, DomainResultCreationState creationState) { - final FromClauseAccess fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess(); + final var fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess(); return fromClauseAccess.resolveTableGroup( fetchablePath, (np) -> { - final PluralTableGroup parentTableGroup = (PluralTableGroup) fromClauseAccess.getTableGroup( np.getParent() ); - switch ( nature ) { - case ELEMENT: { - return parentTableGroup.getElementTableGroup(); - } - case INDEX: { - return resolveIndexTableGroup( parentTableGroup, fetchablePath, fromClauseAccess, creationState ); - } - } + final var parentTableGroup = (PluralTableGroup) fromClauseAccess.getTableGroup( np.getParent() ); + return switch ( nature ) { + case ELEMENT -> parentTableGroup.getElementTableGroup(); + case INDEX -> resolveIndexTableGroup( parentTableGroup, fetchablePath, fromClauseAccess, creationState ); + default -> throw new IllegalStateException( "Could not find table group for: " + np ); + }; - throw new IllegalStateException( "Could not find table group for: " + np ); } ); } @@ -318,11 +311,10 @@ public TableGroup createTableGroupInternal( String sourceAlias, final SqlAliasBase sqlAliasBase, SqlAstCreationState creationState) { - final SqlAstCreationContext creationContext = creationState.getCreationContext(); - final TableReference primaryTableReference = getEntityMappingType().createPrimaryTableReference( - sqlAliasBase, - creationState - ); + final var creationContext = creationState.getCreationContext(); + final var primaryTableReference = + getEntityMappingType() + .createPrimaryTableReference( sqlAliasBase, creationState ); final TableGroup tableGroup = new StandardTableGroup( canUseInnerJoins, @@ -334,7 +326,7 @@ public TableGroup createTableGroupInternal( true, sqlAliasBase, getEntityMappingType().getRootEntityDescriptor()::containsTableReference, - (tableExpression, tg) -> getEntityMappingType().createTableReferenceJoin( + (tableExpression, group) -> getEntityMappingType().createTableReferenceJoin( tableExpression, sqlAliasBase, primaryTableReference, @@ -357,19 +349,21 @@ private static Set resolveTargetKeyPropertyNames( Collection collectionBootDescriptor, EntityMappingType elementTypeDescriptor, MappingModelCreationProcess creationProcess) { - final Value bootModelValue = nature == Nature.INDEX - ? ( (IndexedCollection) collectionBootDescriptor ).getIndex() - : collectionBootDescriptor.getElement(); - final PersistentClass entityBinding = + final Value bootModelValue = + nature == Nature.INDEX + ? ( (IndexedCollection) collectionBootDescriptor ).getIndex() + : collectionBootDescriptor.getElement(); + final var entityBinding = creationProcess.getCreationContext().getMetadata() .getEntityBinding( elementTypeDescriptor.getEntityName() ); final String referencedPropertyName; if ( bootModelValue instanceof OneToMany ) { final String mappedByProperty = collectionDescriptor.getMappedByProperty(); - referencedPropertyName = isEmpty( mappedByProperty ) - ? null - : mappedByProperty; + referencedPropertyName = + isEmpty( mappedByProperty ) + ? null + : mappedByProperty; } else if ( bootModelValue instanceof ToOne toOne ) { referencedPropertyName = toOne.getReferencedPropertyName(); diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AnyDiscriminatorPart.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AnyDiscriminatorPart.java index 9cc9a2e09a36..15199d208562 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AnyDiscriminatorPart.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AnyDiscriminatorPart.java @@ -23,13 +23,10 @@ import org.hibernate.metamodel.spi.ImplicitDiscriminatorStrategy; import org.hibernate.metamodel.spi.MappingMetamodelImplementor; import org.hibernate.spi.NavigablePath; -import org.hibernate.sql.ast.spi.FromClauseAccess; import org.hibernate.sql.ast.spi.SqlAstCreationState; -import org.hibernate.sql.ast.spi.SqlExpressionResolver; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.expression.Expression; import org.hibernate.sql.ast.tree.from.TableGroup; -import org.hibernate.sql.ast.tree.from.TableReference; import org.hibernate.sql.results.graph.DomainResult; import org.hibernate.sql.results.graph.DomainResultCreationState; import org.hibernate.sql.results.graph.FetchOptions; @@ -379,17 +376,17 @@ public BasicFetch generateFetch( boolean selected, String resultVariable, DomainResultCreationState creationState) { - final SqlAstCreationState sqlAstCreationState = creationState.getSqlAstCreationState(); - final FromClauseAccess fromClauseAccess = sqlAstCreationState.getFromClauseAccess(); - final SqlExpressionResolver sqlExpressionResolver = sqlAstCreationState.getSqlExpressionResolver(); + final var sqlAstCreationState = creationState.getSqlAstCreationState(); + final var fromClauseAccess = sqlAstCreationState.getFromClauseAccess(); + final var sqlExpressionResolver = sqlAstCreationState.getSqlExpressionResolver(); - final TableGroup tableGroup = fromClauseAccess.getTableGroup( fetchablePath.getParent().getParent() ); - final TableReference tableReference = tableGroup.resolveTableReference( fetchablePath, table ); - final Expression columnReference = sqlExpressionResolver.resolveSqlExpression( + final var tableGroup = fromClauseAccess.getTableGroup( fetchablePath.getParent().getParent() ); + final var tableReference = tableGroup.resolveTableReference( fetchablePath, table ); + final var columnReference = sqlExpressionResolver.resolveSqlExpression( tableReference, this ); - final SqlSelection sqlSelection = sqlExpressionResolver.resolveSqlSelection( + final var sqlSelection = sqlExpressionResolver.resolveSqlSelection( columnReference, jdbcMapping().getJdbcJavaType(), fetchParent, @@ -423,7 +420,7 @@ public DomainResult createDomainResult( TableGroup tableGroup, String resultVariable, DomainResultCreationState creationState) { - final SqlSelection sqlSelection = resolveSqlSelection( navigablePath, tableGroup, creationState ); + final var sqlSelection = resolveSqlSelection( navigablePath, tableGroup, creationState ); return new BasicResult<>( sqlSelection.getValuesArrayPosition(), resultVariable, @@ -440,11 +437,13 @@ public Expression resolveSqlExpression( JdbcMapping jdbcMappingToUse, TableGroup tableGroup, SqlAstCreationState creationState) { - return creationState.getSqlExpressionResolver().resolveSqlExpression( tableGroup.resolveTableReference( + var tableReference = tableGroup.resolveTableReference( navigablePath, this, getContainingTableExpression() - ), this ); + ); + return creationState.getSqlExpressionResolver() + .resolveSqlExpression( tableReference, this ); } @Override @@ -468,7 +467,7 @@ private SqlSelection resolveSqlSelection( NavigablePath navigablePath, TableGroup tableGroup, DomainResultCreationState creationState) { - final SqlAstCreationState sqlAstCreationState = creationState.getSqlAstCreationState(); + final var sqlAstCreationState = creationState.getSqlAstCreationState(); return sqlAstCreationState.getSqlExpressionResolver().resolveSqlSelection( resolveSqlExpression( navigablePath, null, tableGroup, sqlAstCreationState ), jdbcMapping().getJdbcJavaType(), diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AnyKeyPart.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AnyKeyPart.java index 58576a06115d..c5b473ef1665 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AnyKeyPart.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AnyKeyPart.java @@ -19,12 +19,8 @@ import org.hibernate.metamodel.mapping.SelectablePath; import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.spi.NavigablePath; -import org.hibernate.sql.ast.spi.FromClauseAccess; -import org.hibernate.sql.ast.spi.SqlExpressionResolver; import org.hibernate.sql.ast.spi.SqlSelection; -import org.hibernate.sql.ast.tree.expression.Expression; import org.hibernate.sql.ast.tree.from.TableGroup; -import org.hibernate.sql.ast.tree.from.TableReference; import org.hibernate.sql.results.graph.DomainResult; import org.hibernate.sql.results.graph.DomainResultCreationState; import org.hibernate.sql.results.graph.Fetch; @@ -273,26 +269,23 @@ public Fetch generateFetch( boolean selected, String resultVariable, DomainResultCreationState creationState) { - final FromClauseAccess fromClauseAccess = creationState - .getSqlAstCreationState() - .getFromClauseAccess(); - final SqlExpressionResolver sqlExpressionResolver = creationState - .getSqlAstCreationState() - .getSqlExpressionResolver(); + final var sqlAstCreationState = creationState.getSqlAstCreationState(); + final var fromClauseAccess = sqlAstCreationState.getFromClauseAccess(); + final var sqlExpressionResolver = sqlAstCreationState.getSqlExpressionResolver(); - final TableGroup tableGroup = fromClauseAccess.getTableGroup( fetchParent.getNavigablePath().getParent() ); - final TableReference tableReference = tableGroup.resolveTableReference( fetchablePath, table ); + final var tableGroup = fromClauseAccess.getTableGroup( fetchParent.getNavigablePath().getParent() ); + final var tableReference = tableGroup.resolveTableReference( fetchablePath, table ); - final Expression columnReference = sqlExpressionResolver.resolveSqlExpression( + final var columnReference = sqlExpressionResolver.resolveSqlExpression( tableReference, this ); - final SqlSelection sqlSelection = sqlExpressionResolver.resolveSqlSelection( + final var sqlSelection = sqlExpressionResolver.resolveSqlSelection( columnReference, jdbcMapping.getJdbcJavaType(), fetchParent, - creationState.getSqlAstCreationState().getCreationContext().getTypeConfiguration() + sqlAstCreationState.getCreationContext().getTypeConfiguration() ); return new BasicFetch<>( @@ -382,7 +375,7 @@ public DomainResult createDomainResult( TableGroup tableGroup, String resultVariable, DomainResultCreationState creationState) { - final SqlSelection sqlSelection = resolveSqlSelection( navigablePath, tableGroup, creationState ); + final var sqlSelection = resolveSqlSelection( navigablePath, tableGroup, creationState ); return new BasicResult<>( sqlSelection.getValuesArrayPosition(), resultVariable, @@ -414,13 +407,13 @@ private SqlSelection resolveSqlSelection( NavigablePath navigablePath, TableGroup tableGroup, DomainResultCreationState creationState) { - final TableReference tableReference = tableGroup.resolveTableReference( + final var tableReference = tableGroup.resolveTableReference( navigablePath, this, getContainingTableExpression() ); - final SqlExpressionResolver expressionResolver = creationState.getSqlAstCreationState() - .getSqlExpressionResolver(); + final var sqlAstCreationState = creationState.getSqlAstCreationState(); + final var expressionResolver = sqlAstCreationState.getSqlExpressionResolver(); return expressionResolver.resolveSqlSelection( expressionResolver.resolveSqlExpression( tableReference, @@ -428,7 +421,7 @@ private SqlSelection resolveSqlSelection( ), jdbcMapping.getJdbcJavaType(), null, - creationState.getSqlAstCreationState().getCreationContext().getTypeConfiguration() + sqlAstCreationState.getCreationContext().getTypeConfiguration() ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicAttributeMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicAttributeMapping.java index 8d670e8ad22a..de0e545e9543 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicAttributeMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicAttributeMapping.java @@ -23,11 +23,8 @@ import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.property.access.spi.PropertyAccess; import org.hibernate.spi.NavigablePath; -import org.hibernate.sql.ast.spi.SqlAstCreationState; -import org.hibernate.sql.ast.spi.SqlExpressionResolver; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.from.TableGroup; -import org.hibernate.sql.ast.tree.from.TableReference; import org.hibernate.sql.results.graph.DomainResult; import org.hibernate.sql.results.graph.DomainResultCreationState; import org.hibernate.sql.results.graph.Fetch; @@ -193,11 +190,12 @@ public BasicAttributeMapping( else { this.customWriteExpression = customWriteExpression; } - this.isLazy = navigableRole.getParent().getParent() == null && declaringType.findContainingEntityMapping() - .getEntityPersister() - .getBytecodeEnhancementMetadata() - .getLazyAttributesMetadata() - .isLazyAttribute( attributeName ); + this.isLazy = navigableRole.getParent().getParent() == null + && declaringType.findContainingEntityMapping() + .getEntityPersister() + .getBytecodeEnhancementMetadata() + .getLazyAttributesMetadata() + .isLazyAttribute( attributeName ); } public static BasicAttributeMapping withSelectableMapping( @@ -409,21 +407,19 @@ private SqlSelection resolveSqlSelection( TableGroup tableGroup, FetchParent fetchParent, DomainResultCreationState creationState) { - final SqlExpressionResolver expressionResolver = creationState.getSqlAstCreationState().getSqlExpressionResolver(); - final TableReference tableReference = tableGroup.resolveTableReference( + final var sqlAstCreationState = creationState.getSqlAstCreationState(); + final var expressionResolver = sqlAstCreationState.getSqlExpressionResolver(); + final var tableReference = tableGroup.resolveTableReference( navigablePath, this, getContainingTableExpression() ); return expressionResolver.resolveSqlSelection( - expressionResolver.resolveSqlExpression( - tableReference, - this - ), + expressionResolver.resolveSqlExpression( tableReference, this ), jdbcMapping.getJdbcJavaType(), fetchParent, - creationState.getSqlAstCreationState().getCreationContext().getTypeConfiguration() + sqlAstCreationState.getCreationContext().getTypeConfiguration() ); } @@ -441,7 +437,8 @@ public void applySqlSelections( TableGroup tableGroup, DomainResultCreationState creationState, BiConsumer selectionConsumer) { - selectionConsumer.accept( resolveSqlSelection( navigablePath, tableGroup, null, creationState ), getJdbcMapping() ); + selectionConsumer.accept( resolveSqlSelection( navigablePath, tableGroup, null, creationState ), + getJdbcMapping() ); } @Override @@ -462,11 +459,10 @@ public Fetch generateFetch( sqlSelection = null; } else { - final SqlAstCreationState sqlAstCreationState = creationState.getSqlAstCreationState(); - final TableGroup tableGroup = sqlAstCreationState.getFromClauseAccess().getTableGroup( - fetchParent.getNavigablePath() - ); - + final var sqlAstCreationState = creationState.getSqlAstCreationState(); + final var tableGroup = + sqlAstCreationState.getFromClauseAccess() + .getTableGroup( fetchParent.getNavigablePath() ); assert tableGroup != null; sqlSelection = resolveSqlSelection( diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicEntityIdentifierMappingImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicEntityIdentifierMappingImpl.java index 501cc728f676..6b28e756d836 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicEntityIdentifierMappingImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicEntityIdentifierMappingImpl.java @@ -17,21 +17,16 @@ import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.internal.util.IndexedConsumer; -import org.hibernate.mapping.PersistentClass; import org.hibernate.metamodel.mapping.BasicEntityIdentifierMapping; import org.hibernate.metamodel.mapping.EntityIdentifierMapping; import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.metamodel.mapping.JdbcMapping; -import org.hibernate.metamodel.mapping.JdbcMappingContainer; import org.hibernate.metamodel.mapping.MappingType; import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.property.access.spi.PropertyAccess; import org.hibernate.proxy.HibernateProxy; -import org.hibernate.proxy.LazyInitializer; import org.hibernate.spi.NavigablePath; -import org.hibernate.sql.ast.spi.SqlAstCreationState; -import org.hibernate.sql.ast.spi.SqlExpressionResolver; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.expression.Expression; import org.hibernate.sql.ast.tree.from.TableGroup; @@ -140,9 +135,9 @@ public BasicEntityIdentifierMappingImpl( this.idType = (BasicType) idType; this.entityPersister = entityPersister; - final PersistentClass bootEntityDescriptor = creationProcess.getCreationContext() - .getBootModel() - .getEntityBinding( entityPersister.getEntityName() ); + final var bootEntityDescriptor = + creationProcess.getCreationContext().getBootModel() + .getEntityBinding( entityPersister.getEntityName() ); propertyAccess = entityPersister.getRepresentationStrategy() .resolvePropertyAccess( bootEntityDescriptor.getIdentifierProperty() ); @@ -185,7 +180,7 @@ public IdentifierValue getUnsavedStrategy() { @Override public Object getIdentifier(Object entity) { - final LazyInitializer lazyInitializer = HibernateProxy.extractLazyInitializer( entity ); + final var lazyInitializer = HibernateProxy.extractLazyInitializer( entity ); if ( lazyInitializer != null ) { return lazyInitializer.getInternalIdentifier(); } @@ -251,8 +246,7 @@ public DomainResult createDomainResult( TableGroup tableGroup, String resultVariable, DomainResultCreationState creationState) { - final SqlSelection sqlSelection = resolveSqlSelection( navigablePath, tableGroup, null, creationState ); - + final var sqlSelection = resolveSqlSelection( navigablePath, tableGroup, null, creationState ); return new BasicResult<>( sqlSelection.getValuesArrayPosition(), resultVariable, @@ -288,8 +282,7 @@ private SqlSelection resolveSqlSelection( TableGroup tableGroup, FetchParent fetchParent, DomainResultCreationState creationState) { - final SqlExpressionResolver expressionResolver = creationState.getSqlAstCreationState() - .getSqlExpressionResolver(); + final var expressionResolver = creationState.getSqlAstCreationState().getSqlExpressionResolver(); final TableReference rootTableReference; try { rootTableReference = tableGroup.resolveTableReference( navigablePath, rootTable ); @@ -444,15 +437,14 @@ public Fetch generateFetch( boolean selected, String resultVariable, DomainResultCreationState creationState) { - final SqlAstCreationState sqlAstCreationState = creationState.getSqlAstCreationState(); - final TableGroup tableGroup = sqlAstCreationState.getFromClauseAccess().getTableGroup( - fetchParent.getNavigablePath() - ); - + final var sqlAstCreationState = creationState.getSqlAstCreationState(); + final var tableGroup = + sqlAstCreationState.getFromClauseAccess() + .getTableGroup( fetchParent.getNavigablePath() ); assert tableGroup != null; - final SqlSelection sqlSelection = resolveSqlSelection( fetchablePath, tableGroup, fetchParent, creationState ); - final JdbcMappingContainer selectionType = sqlSelection.getExpressionType(); + final var sqlSelection = resolveSqlSelection( fetchablePath, tableGroup, fetchParent, creationState ); + final var selectionType = sqlSelection.getExpressionType(); return new BasicFetch<>( sqlSelection.getValuesArrayPosition(), fetchParent, @@ -463,7 +455,8 @@ public Fetch generateFetch( true, creationState, // if the expression type is different that the expected type coerce the value - selectionType != null && selectionType.getSingleJdbcMapping().getJdbcJavaType() != getJdbcMapping().getJdbcJavaType(), + selectionType != null + && selectionType.getSingleJdbcMapping().getJdbcJavaType() != getJdbcMapping().getJdbcJavaType(), !sqlSelection.isVirtual() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicValuedCollectionPart.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicValuedCollectionPart.java index e8a08f331165..ace237b91190 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicValuedCollectionPart.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/BasicValuedCollectionPart.java @@ -23,11 +23,9 @@ import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.spi.EntityIdentifierNavigablePath; import org.hibernate.spi.NavigablePath; -import org.hibernate.sql.ast.spi.SqlExpressionResolver; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.from.PluralTableGroup; import org.hibernate.sql.ast.tree.from.TableGroup; -import org.hibernate.sql.ast.tree.from.TableReference; import org.hibernate.sql.results.ResultsLogger; import org.hibernate.sql.results.graph.DomainResult; import org.hibernate.sql.results.graph.DomainResultCreationState; @@ -172,8 +170,7 @@ public DomainResult createDomainResult( TableGroup tableGroup, String resultVariable, DomainResultCreationState creationState) { - final SqlSelection sqlSelection = resolveSqlSelection( navigablePath, tableGroup, null, creationState ); - + final var sqlSelection = resolveSqlSelection( navigablePath, tableGroup, null, creationState ); return new BasicResult<>( sqlSelection.getValuesArrayPosition(), resultVariable, @@ -189,7 +186,7 @@ private SqlSelection resolveSqlSelection( TableGroup tableGroup, FetchParent fetchParent, DomainResultCreationState creationState) { - final SqlExpressionResolver exprResolver = creationState.getSqlAstCreationState().getSqlExpressionResolver(); + final var exprResolver = creationState.getSqlAstCreationState().getSqlExpressionResolver(); final TableGroup targetTableGroup; // If the index is part of the element table group, we must use that explicitly here because the index is basic // and thus there is no index table group registered. The logic in the PluralTableGroup prevents from looking @@ -201,10 +198,8 @@ private SqlSelection resolveSqlSelection( else { targetTableGroup = tableGroup; } - final TableReference tableReference = targetTableGroup.resolveTableReference( - navigablePath, - getContainingTableExpression() - ); + final var tableReference = + targetTableGroup.resolveTableReference( navigablePath, getContainingTableExpression() ); return exprResolver.resolveSqlSelection( exprResolver.resolveSqlExpression( tableReference, selectableMapping ), getJdbcMapping().getJdbcJavaType(), @@ -279,10 +274,10 @@ public Fetch generateFetch( parentNavigablePath = parentNavigablePath.getParent(); } - final TableGroup tableGroup = + final var tableGroup = creationState.getSqlAstCreationState().getFromClauseAccess() .findTableGroup( parentNavigablePath ); - final SqlSelection sqlSelection = resolveSqlSelection( fetchablePath, tableGroup, fetchParent, creationState ); + final var sqlSelection = resolveSqlSelection( fetchablePath, tableGroup, fetchParent, creationState ); return new BasicFetch<>( sqlSelection.getValuesArrayPosition(), diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CaseStatementDiscriminatorMappingImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CaseStatementDiscriminatorMappingImpl.java index 1ef1b8025572..a4ca7680880b 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CaseStatementDiscriminatorMappingImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CaseStatementDiscriminatorMappingImpl.java @@ -20,7 +20,6 @@ import org.hibernate.sql.ast.SqlAstTranslator; import org.hibernate.sql.ast.spi.SqlAppender; import org.hibernate.sql.ast.spi.SqlAstCreationState; -import org.hibernate.sql.ast.spi.SqlExpressionResolver; import org.hibernate.sql.ast.tree.expression.CaseSearchedExpression; import org.hibernate.sql.ast.tree.expression.ColumnReference; import org.hibernate.sql.ast.tree.expression.Expression; @@ -99,19 +98,19 @@ public BasicFetch generateFetch( boolean selected, String resultVariable, DomainResultCreationState creationState) { - final SqlAstCreationState sqlAstCreationState = creationState.getSqlAstCreationState(); - final TableGroup tableGroup = sqlAstCreationState.getFromClauseAccess().getTableGroup( - fetchParent.getNavigablePath() - ); + final var sqlAstCreationState = creationState.getSqlAstCreationState(); + final var tableGroup = + sqlAstCreationState.getFromClauseAccess() + .getTableGroup( fetchParent.getNavigablePath() ); resolveSubTypeTableReferences( tableGroup, fetchablePath ); return super.generateFetch( fetchParent, fetchablePath, fetchTiming, selected, resultVariable, creationState ); } private void resolveSubTypeTableReferences(TableGroup tableGroup, NavigablePath navigablePath) { - final EntityMappingType entityDescriptor = (EntityMappingType) tableGroup.getModelPart().getPartMappingType(); + final var entityDescriptor = (EntityMappingType) tableGroup.getModelPart().getPartMappingType(); // Since the expression is lazy, based on the available table reference joins, // we need to force the initialization in case this is selected - for ( EntityMappingType subMappingType : entityDescriptor.getSubMappingTypes() ) { + for ( var subMappingType : entityDescriptor.getSubMappingTypes() ) { tableGroup.getTableReference( navigablePath, subMappingType.getMappedTableDetails().getTableName(), @@ -126,7 +125,7 @@ public Expression resolveSqlExpression( JdbcMapping jdbcMappingToUse, TableGroup tableGroup, SqlAstCreationState creationState) { - final SqlExpressionResolver expressionResolver = creationState.getSqlExpressionResolver(); + final var expressionResolver = creationState.getSqlExpressionResolver(); return expressionResolver.resolveSqlExpression( createColumnReferenceKey( tableGroup.getPrimaryTableReference(), @@ -267,7 +266,7 @@ public List getUsedTableReferences() { final ArrayList usedTableReferences = new ArrayList<>( tableDiscriminatorDetailsMap.size() ); tableDiscriminatorDetailsMap.forEach( (tableName, tableDiscriminatorDetails) -> { - final TableReference tableReference = entityTableGroup.getTableReference( + final var tableReference = entityTableGroup.getTableReference( entityTableGroup.getNavigablePath(), tableName, false @@ -291,7 +290,7 @@ public void renderToSql( caseSearchedExpression = new CaseSearchedExpression( CaseStatementDiscriminatorMappingImpl.this ); tableDiscriminatorDetailsMap.forEach( (tableName, tableDiscriminatorDetails) -> { - final TableReference tableReference = entityTableGroup.getTableReference( + final var tableReference = entityTableGroup.getTableReference( entityTableGroup.getNavigablePath(), tableName, false diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CollectionIdentifierDescriptorImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CollectionIdentifierDescriptorImpl.java index 631da553a63d..9bb5843f01d9 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CollectionIdentifierDescriptorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CollectionIdentifierDescriptorImpl.java @@ -20,10 +20,6 @@ import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.spi.NavigablePath; -import org.hibernate.sql.ast.spi.FromClauseAccess; -import org.hibernate.sql.ast.spi.SqlAstCreationContext; -import org.hibernate.sql.ast.spi.SqlAstCreationState; -import org.hibernate.sql.ast.spi.SqlExpressionResolver; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.from.TableGroup; import org.hibernate.sql.results.graph.DomainResult; @@ -256,13 +252,13 @@ public Fetch generateFetch( String resultVariable, DomainResultCreationState creationState) { // get the collection TableGroup - final FromClauseAccess fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess(); - final TableGroup tableGroup = fromClauseAccess.getTableGroup( fetchablePath.getParent() ); + final var fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess(); + final var tableGroup = fromClauseAccess.getTableGroup( fetchablePath.getParent() ); - final SqlAstCreationState astCreationState = creationState.getSqlAstCreationState(); - final SqlExpressionResolver sqlExpressionResolver = astCreationState.getSqlExpressionResolver(); + final var astCreationState = creationState.getSqlAstCreationState(); + final var sqlExpressionResolver = astCreationState.getSqlExpressionResolver(); - final SqlSelection sqlSelection = sqlExpressionResolver.resolveSqlSelection( + final var sqlSelection = sqlExpressionResolver.resolveSqlSelection( sqlExpressionResolver.resolveSqlExpression( tableGroup.getPrimaryTableReference(), this @@ -287,11 +283,11 @@ public DomainResult createDomainResult( NavigablePath collectionPath, TableGroup tableGroup, DomainResultCreationState creationState) { - final SqlAstCreationState astCreationState = creationState.getSqlAstCreationState(); - final SqlAstCreationContext astCreationContext = astCreationState.getCreationContext(); - final SqlExpressionResolver sqlExpressionResolver = astCreationState.getSqlExpressionResolver(); + final var astCreationState = creationState.getSqlAstCreationState(); + final var astCreationContext = astCreationState.getCreationContext(); + final var sqlExpressionResolver = astCreationState.getSqlExpressionResolver(); - final SqlSelection sqlSelection = sqlExpressionResolver.resolveSqlSelection( + final var sqlSelection = sqlExpressionResolver.resolveSqlSelection( sqlExpressionResolver.resolveSqlExpression( tableGroup.getPrimaryTableReference(), this diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CompoundNaturalIdMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CompoundNaturalIdMapping.java index 671fbe182419..21a2e8f67359 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CompoundNaturalIdMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/CompoundNaturalIdMapping.java @@ -13,7 +13,6 @@ import org.hibernate.AssertionFailure; import org.hibernate.HibernateException; import org.hibernate.cache.MutableCacheKeyBuilder; -import org.hibernate.engine.spi.PersistenceContext; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.internal.util.IndexedConsumer; import org.hibernate.loader.ast.internal.CompoundNaturalIdLoader; @@ -21,7 +20,6 @@ import org.hibernate.loader.ast.spi.MultiNaturalIdLoader; import org.hibernate.loader.ast.spi.NaturalIdLoader; import org.hibernate.metamodel.UnsupportedMappingException; -import org.hibernate.metamodel.mapping.AttributeMapping; import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.metamodel.mapping.JdbcMapping; import org.hibernate.metamodel.mapping.MappingType; @@ -29,7 +27,6 @@ import org.hibernate.metamodel.mapping.NaturalIdMapping; import org.hibernate.metamodel.mapping.SelectableConsumer; import org.hibernate.metamodel.mapping.SingularAttributeMapping; -import org.hibernate.persister.entity.EntityPersister; import org.hibernate.spi.NavigablePath; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.from.TableGroup; @@ -71,7 +68,7 @@ public CompoundNaturalIdMapping( this.attributes = attributes; int maxIndex = 0; - for ( SingularAttributeMapping attribute : attributes ) { + for ( var attribute : attributes ) { if ( attribute.getFetchableKey() > maxIndex ) { maxIndex = attribute.getFetchableKey(); } @@ -113,7 +110,7 @@ else if ( state.length == attributes.size() ) { else { final Object[] values = new Object[attributes.size()]; for ( int i = 0; i <= attributes.size() - 1; i++ ) { - final SingularAttributeMapping attributeMapping = attributes.get( i ); + final var attributeMapping = attributes.get( i ); values[i] = state[attributeMapping.getStateArrayPosition()]; } return values; @@ -135,7 +132,7 @@ public Object[] normalizeInput(Object incoming) { return array; } else if ( incoming instanceof Map valueMap ) { - final List attributes = getNaturalIdAttributes(); + final var attributes = getNaturalIdAttributes(); final Object[] values = new Object[ attributes.size() ]; for ( int i = 0; i < attributes.size(); i++ ) { values[ i ] = valueMap.get( attributes.get( i ).getAttributeName() ); @@ -188,8 +185,8 @@ public int calculateHashCode(Object value) { @Override public void verifyFlushState(Object id, Object[] currentState, Object[] loadedState, SharedSessionContractImplementor session) { if ( !isMutable() ) { - final PersistenceContext persistenceContext = session.getPersistenceContextInternal(); - final EntityPersister persister = getDeclaringType().getEntityPersister(); + final var persistenceContext = session.getPersistenceContextInternal(); + final var persister = getDeclaringType().getEntityPersister(); final Object[] naturalId = extractNaturalIdFromEntityState( currentState ); final Object snapshot = loadedState == null @@ -200,7 +197,7 @@ public void verifyFlushState(Object id, Object[] currentState, Object[] loadedSt assert previousNaturalId.length == naturalId.length; for ( int i = 0; i < getNaturalIdAttributes().size(); i++ ) { - final SingularAttributeMapping attributeMapping = getNaturalIdAttributes().get( i ); + final var attributeMapping = getNaturalIdAttributes().get( i ); final boolean updatable = attributeMapping.getAttributeMetadata().isUpdatable(); if ( !updatable ) { final Object currentValue = naturalId[i]; @@ -227,7 +224,7 @@ public void verifyFlushState(Object id, Object[] currentState, Object[] loadedSt public boolean areEqual(Object one, Object other, SharedSessionContractImplementor session) { final Object[] oneArray = (Object[]) one; final Object[] otherArray = (Object[]) other; - final List naturalIdAttributes = getNaturalIdAttributes(); + final var naturalIdAttributes = getNaturalIdAttributes(); for ( int i = 0; i < naturalIdAttributes.size(); i++ ) { if ( !naturalIdAttributes.get( i ).areEqual( oneArray[i], otherArray[i], session ) ) { return false; @@ -269,7 +266,7 @@ public JavaType getMappedJavaType() { @Override public boolean hasPartitionedSelectionMapping() { - for ( AttributeMapping attributeMapping : attributes ) { + for ( var attributeMapping : attributes ) { if ( attributeMapping.hasPartitionedSelectionMapping() ) { return true; } @@ -430,7 +427,7 @@ public int forEachDisassembledJdbcValue( int span = 0; if ( value == null ) { for ( int i = 0; i < attributes.size(); i++ ) { - final SingularAttributeMapping attribute = attributes.get( i ); + final var attribute = attributes.get( i ); span += attribute.forEachDisassembledJdbcValue( null, span + offset, @@ -444,7 +441,7 @@ public int forEachDisassembledJdbcValue( else if ( value instanceof Object[] incoming ) { assert incoming.length == attributes.size(); for ( int i = 0; i < attributes.size(); i++ ) { - final SingularAttributeMapping attribute = attributes.get( i ); + final var attribute = attributes.get( i ); span += attribute.forEachDisassembledJdbcValue( incoming[i], span + offset, @@ -472,14 +469,14 @@ public int forEachJdbcValue( int span = 0; if ( value == null ) { for ( int i = 0; i < attributes.size(); i++ ) { - final SingularAttributeMapping attribute = attributes.get( i ); + final var attribute = attributes.get( i ); span += attribute.forEachJdbcValue( null, span + offset, x, y, valuesConsumer, session ); } } else if ( value instanceof Object[] incoming ) { assert incoming.length == attributes.size(); for ( int i = 0; i < attributes.size(); i++ ) { - final SingularAttributeMapping attribute = attributes.get( i ); + final var attribute = attributes.get( i ); span += attribute.forEachJdbcValue( incoming[i], span + offset, x, y, valuesConsumer, session ); } } @@ -649,8 +646,8 @@ public void resolveState(RowProcessingState rowProcessingState) { @Override public void forEachResultAssembler(BiConsumer, X> consumer, X arg) { - for ( DomainResultAssembler subAssembler : subAssemblers ) { - final Initializer initializer = subAssembler.getInitializer(); + for ( var subAssembler : subAssemblers ) { + final var initializer = subAssembler.getInitializer(); // In case of natural id mapping selection every initializer is a "result initializer", // regardless of what Initializer#isResultInitializer reports if ( initializer != null ) { diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/DiscriminatedAssociationAttributeMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/DiscriminatedAssociationAttributeMapping.java index 73872925cff2..d41eb996823a 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/DiscriminatedAssociationAttributeMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/DiscriminatedAssociationAttributeMapping.java @@ -22,7 +22,6 @@ import org.hibernate.metamodel.mapping.BasicValuedModelPart; import org.hibernate.metamodel.mapping.DiscriminatedAssociationModelPart; import org.hibernate.metamodel.mapping.DiscriminatorMapping; -import org.hibernate.metamodel.mapping.EntityIdentifierMapping; import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.metamodel.mapping.JdbcMapping; import org.hibernate.metamodel.mapping.ManagedMappingType; @@ -188,15 +187,19 @@ public int getNumberOfFetchables() { @Override public Fetchable getFetchable(int position) { - switch ( position ) { - case 0: - assert getDiscriminatorPart().getFetchableKey() == 0; - return getDiscriminatorPart(); - case 1: - assert getKeyPart().getFetchableKey() == 1; - return getKeyPart(); - } - throw new IndexOutOfBoundsException(position); + return switch ( position ) { + case 0 -> { + final var discriminatorPart = getDiscriminatorPart(); + assert discriminatorPart.getFetchableKey() == 0; + yield discriminatorPart; + } + case 1 -> { + final var keyPart = getKeyPart(); + assert keyPart.getFetchableKey() == 1; + yield keyPart; + } + default -> throw new IndexOutOfBoundsException( position ); + }; } @Override @@ -211,12 +214,11 @@ public int getJdbcTypeCount() { @Override public JdbcMapping getJdbcMapping(final int index) { - switch (index) { - case 0 : return discriminatorMapping.getDiscriminatorPart().getJdbcMapping(); - case 1 : return discriminatorMapping.getKeyPart().getJdbcMapping(); - default: - throw new IndexOutOfBoundsException( index ); - } + return switch ( index ) { + case 0 -> discriminatorMapping.getDiscriminatorPart().getJdbcMapping(); + case 1 -> discriminatorMapping.getKeyPart().getJdbcMapping(); + default -> throw new IndexOutOfBoundsException( index ); + }; } @Override @@ -233,12 +235,12 @@ public Object disassemble(Object value, SharedSessionContractImplementor session return null; } - final EntityMappingType concreteMappingType = determineConcreteType( value, session ); - final EntityIdentifierMapping identifierMapping = concreteMappingType.getIdentifierMapping(); + final var concreteMappingType = determineConcreteType( value, session ); + final var identifierMapping = concreteMappingType.getIdentifierMapping(); - final Object discriminator = discriminatorMapping - .getModelPart() - .resolveDiscriminatorForEntityType( concreteMappingType ); + final Object discriminator = + discriminatorMapping.getModelPart() + .resolveDiscriminatorForEntityType( concreteMappingType ); final Object identifier = identifierMapping.getIdentifier( value ); return new Object[] { @@ -254,22 +256,23 @@ public void addToCacheKey(MutableCacheKeyBuilder cacheKey, Object value, SharedS cacheKey.addHashCode( 0 ); } else { - final EntityMappingType concreteMappingType = determineConcreteType( value, session ); + final var concreteMappingType = determineConcreteType( value, session ); - final Object discriminator = discriminatorMapping - .getModelPart() - .resolveDiscriminatorForEntityType( concreteMappingType ); + final Object discriminator = + discriminatorMapping.getModelPart() + .resolveDiscriminatorForEntityType( concreteMappingType ); discriminatorMapping.getDiscriminatorPart().addToCacheKey( cacheKey, discriminator, session ); - final EntityIdentifierMapping identifierMapping = concreteMappingType.getIdentifierMapping(); + final var identifierMapping = concreteMappingType.getIdentifierMapping(); identifierMapping.addToCacheKey( cacheKey, identifierMapping.getIdentifier( value ), session ); } } private EntityMappingType determineConcreteType(Object entity, SharedSessionContractImplementor session) { - final String entityName = session == null - ? sessionFactory.bestGuessEntityName( entity ) - : session.bestGuessEntityName( entity ); + final String entityName = + session == null + ? sessionFactory.bestGuessEntityName( entity ) + : session.bestGuessEntityName( entity ); return sessionFactory.getMappingMetamodel() .getEntityDescriptor( entityName ); } @@ -332,12 +335,13 @@ public int forEachDisassembledJdbcValue( ); } else { - final EntityMappingType concreteMappingType = determineConcreteType( value, session ); + final var concreteMappingType = determineConcreteType( value, session ); - final Object discriminator = discriminatorMapping - .getModelPart() - .resolveDiscriminatorForEntityType( concreteMappingType ); - final Object disassembledDiscriminator = discriminatorMapping.getDiscriminatorPart().disassemble( discriminator, session ); + final Object discriminator = + discriminatorMapping.getModelPart() + .resolveDiscriminatorForEntityType( concreteMappingType ); + final Object disassembledDiscriminator = + discriminatorMapping.getDiscriminatorPart().disassemble( discriminator, session ); valuesConsumer.consume( offset, x, @@ -346,7 +350,7 @@ public int forEachDisassembledJdbcValue( discriminatorMapping.getDiscriminatorPart().getJdbcMapping() ); - final EntityIdentifierMapping identifierMapping = concreteMappingType.getIdentifierMapping(); + final var identifierMapping = concreteMappingType.getIdentifierMapping(); final Object identifier = identifierMapping.getIdentifier( value ); final Object disassembledKey = discriminatorMapping.getKeyPart().disassemble( identifier, session ); valuesConsumer.consume( @@ -422,7 +426,7 @@ public void visitSubParts(Consumer consumer, EntityMappingType treatT @Override public boolean hasPartitionedSelectionMapping() { return discriminatorMapping.getDiscriminatorPart().isPartitioned() - || discriminatorMapping.getKeyPart().isPartitioned(); + || discriminatorMapping.getKeyPart().isPartitioned(); } public static class MutabilityPlanImpl implements MutabilityPlan { @@ -488,8 +492,8 @@ public TableGroupJoin createTableGroupJoin( boolean fetched, boolean addsPredicate, SqlAstCreationState creationState) { - final SqlAstJoinType joinType = Objects.requireNonNullElse( requestedJoinType, SqlAstJoinType.INNER ); - final TableGroup tableGroup = createRootTableGroupJoin( + final var joinType = Objects.requireNonNullElse( requestedJoinType, SqlAstJoinType.INNER ); + final var tableGroup = createRootTableGroupJoin( navigablePath, lhs, explicitSourceAlias, diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/DiscriminatedAssociationMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/DiscriminatedAssociationMapping.java index 6359c245fdcb..d5dbbe343c6a 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/DiscriminatedAssociationMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/DiscriminatedAssociationMapping.java @@ -4,22 +4,18 @@ */ package org.hibernate.metamodel.mapping.internal; -import java.util.Iterator; import java.util.Locale; -import org.hibernate.dialect.Dialect; import org.hibernate.engine.FetchStyle; import org.hibernate.engine.FetchTiming; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.mapping.Any; import org.hibernate.mapping.Column; -import org.hibernate.mapping.Selectable; import org.hibernate.metamodel.mapping.BasicValuedModelPart; import org.hibernate.metamodel.mapping.DiscriminatedAssociationModelPart; import org.hibernate.metamodel.mapping.DiscriminatorMapping; import org.hibernate.metamodel.mapping.DiscriminatorValueDetails; -import org.hibernate.metamodel.mapping.EntityIdentifierMapping; import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.metamodel.mapping.MappingType; import org.hibernate.metamodel.mapping.ModelPart; @@ -39,6 +35,8 @@ import org.hibernate.type.MetaType; import org.hibernate.type.descriptor.java.JavaType; +import static org.hibernate.metamodel.mapping.internal.MappingModelCreationHelper.getSelectablePath; + /** * Represents the "type" of an any-valued mapping * @@ -54,30 +52,31 @@ public static DiscriminatedAssociationMapping from( Any bootValueMapping, MappingModelCreationProcess creationProcess) { - final Dialect dialect = creationProcess.getCreationContext().getDialect(); + final var dialect = creationProcess.getCreationContext().getDialect(); final String tableName = MappingModelCreationHelper.getTableIdentifierExpression( bootValueMapping.getTable(), creationProcess ); assert bootValueMapping.getColumnSpan() == 2; - final Iterator columnIterator = bootValueMapping.getSelectables().iterator(); + final var columnIterator = bootValueMapping.getSelectables().iterator(); assert columnIterator.hasNext(); - final Selectable metaSelectable = columnIterator.next(); + final var metaSelectable = columnIterator.next(); assert columnIterator.hasNext(); - final Selectable keySelectable = columnIterator.next(); + final var keySelectable = columnIterator.next(); assert !columnIterator.hasNext(); assert !metaSelectable.isFormula(); assert !keySelectable.isFormula(); - final Column metaColumn = (Column) metaSelectable; - final Column keyColumn = (Column) keySelectable; - final SelectablePath parentSelectablePath = declaringModelPart.asAttributeMapping() != null - ? MappingModelCreationHelper.getSelectablePath( declaringModelPart.asAttributeMapping().getDeclaringType() ) - : null; - - final MetaType metaType = (MetaType) anyType.getDiscriminatorType(); - final AnyDiscriminatorPart discriminatorPart = new AnyDiscriminatorPart( + final var metaColumn = (Column) metaSelectable; + final var keyColumn = (Column) keySelectable; + final SelectablePath parentSelectablePath = + declaringModelPart.asAttributeMapping() != null + ? getSelectablePath( declaringModelPart.asAttributeMapping().getDeclaringType() ) + : null; + + final var metaType = (MetaType) anyType.getDiscriminatorType(); + final var discriminatorPart = new AnyDiscriminatorPart( containerRole.append( AnyDiscriminatorPart.ROLE_NAME ), declaringModelPart, tableName, @@ -101,8 +100,8 @@ public static DiscriminatedAssociationMapping from( ); - final BasicType keyType = (BasicType) anyType.getIdentifierType(); - final BasicValuedModelPart keyPart = new AnyKeyPart( + final var keyType = (BasicType) anyType.getIdentifierType(); + final var keyPart = new AnyKeyPart( containerRole.append( AnyKeyPart.KEY_NAME ), declaringModelPart, tableName, @@ -179,12 +178,10 @@ public Object resolveDiscriminatorValueToEntityMapping(EntityMappingType entityM } public EntityMappingType resolveDiscriminatorValueToEntityMapping(Object discriminatorValue) { - final DiscriminatorValueDetails details = + final var details = discriminatorPart.getValueConverter(). getDetailsForDiscriminatorValue( discriminatorValue ); - return details != null - ? details.getIndicatedEntity() - : null; + return details == null ? null : details.getIndicatedEntity(); } public int breakDownJdbcValues( @@ -200,13 +197,13 @@ public int breakDownJdbcValues( return getDiscriminatorPart().getJdbcTypeCount() + getKeyPart().getJdbcTypeCount(); } else { - final EntityMappingType concreteMappingType = determineConcreteType( domainValue, session ); + final var concreteMappingType = determineConcreteType( domainValue, session ); final Object discriminator = getModelPart().resolveDiscriminatorForEntityType( concreteMappingType ); final Object disassembledDiscriminator = getDiscriminatorPart().disassemble( discriminator, session ); valueConsumer.consume( offset, x, y, disassembledDiscriminator, getDiscriminatorPart() ); - final EntityIdentifierMapping identifierMapping = concreteMappingType.getIdentifierMapping(); + final var identifierMapping = concreteMappingType.getIdentifierMapping(); final Object identifier = identifierMapping.getIdentifier( domainValue ); final Object disassembledKey = getKeyPart().disassemble( identifier, session ); valueConsumer.consume( offset + 1, x, y, disassembledKey, getKeyPart() ); @@ -226,12 +223,12 @@ public int decompose( valueConsumer.consume( offset + 1, x, y, null, getKeyPart() ); } else { - final EntityMappingType concreteMappingType = determineConcreteType( domainValue, session ); + final var concreteMappingType = determineConcreteType( domainValue, session ); final Object discriminator = getModelPart().resolveDiscriminatorForEntityType( concreteMappingType ); getDiscriminatorPart().decompose( discriminator, offset, x, y, valueConsumer, session ); - final EntityIdentifierMapping identifierMapping = concreteMappingType.getIdentifierMapping(); + final var identifierMapping = concreteMappingType.getIdentifierMapping(); final Object identifier = identifierMapping.getIdentifier( domainValue ); getKeyPart().decompose( identifier, offset + 1, x, y, valueConsumer, session ); } @@ -239,9 +236,10 @@ public int decompose( } private EntityMappingType determineConcreteType(Object entity, SharedSessionContractImplementor session) { - final String entityName = session == null - ? sessionFactory.bestGuessEntityName( entity ) - : session.bestGuessEntityName( entity ); + final String entityName = + session == null + ? sessionFactory.bestGuessEntityName( entity ) + : session.bestGuessEntityName( entity ); return sessionFactory.getMappingMetamodel() .getEntityDescriptor( entityName ); } @@ -264,7 +262,7 @@ public ModelPart findSubPart(String name, EntityMappingType treatTarget) { return discriminatorPart.getValueConverter().fromValueDetails( (detail) -> { try { - final ModelPart subPart = resolveAssociatedSubPart( name, detail.getIndicatedEntity() ); + final var subPart = resolveAssociatedSubPart( name, detail.getIndicatedEntity() ); if ( subPart != null ) { return subPart; } @@ -277,7 +275,7 @@ public ModelPart findSubPart(String name, EntityMappingType treatTarget) { } private ModelPart resolveAssociatedSubPart(String name, EntityMappingType entityMapping) { - final EntityIdentifierMapping identifierMapping = entityMapping.getIdentifierMapping(); + final var identifierMapping = entityMapping.getIdentifierMapping(); if ( identifierMapping.getPartName().equals( name ) ) { return getKeyPart(); @@ -297,18 +295,16 @@ private void ensureMapped(EntityMappingType treatTarget) { assert treatTarget != null; final DiscriminatorValueDetails details = discriminatorPart.getValueConverter().getDetailsForEntityName( treatTarget.getEntityName() ); - if ( details != null ) { - return; + if ( details == null ) { + throw new IllegalArgumentException( + String.format( + Locale.ROOT, + "Treat-target [`%s`] is not not an entity mapped by ANY value : %s", + treatTarget.getEntityName(), + modelPart.getNavigableRole() + ) + ); } - - throw new IllegalArgumentException( - String.format( - Locale.ROOT, - "Treat-target [`%s`] is not not an entity mapped by ANY value : %s", - treatTarget.getEntityName(), - modelPart.getNavigableRole() - ) - ); } public MappingType getPartMappingType() { diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/DiscriminatedCollectionPart.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/DiscriminatedCollectionPart.java index 60a2be1aa6cd..d16c3806ee66 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/DiscriminatedCollectionPart.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/DiscriminatedCollectionPart.java @@ -67,7 +67,6 @@ public DiscriminatedCollectionPart( this.nature = nature; this.partRole = collectionDescriptor.getNavigableRole().append( nature.getName() ); this.collectionDescriptor = collectionDescriptor; - this.associationMapping = DiscriminatedAssociationMapping.from( partRole, baseAssociationJtd, @@ -117,7 +116,6 @@ public Object resolveDiscriminatorForEntityType(EntityMappingType entityMappingT public int forEachSelectable(int offset, SelectableConsumer consumer) { associationMapping.getDiscriminatorPart().forEachSelectable( offset, consumer ); associationMapping.getKeyPart().forEachSelectable( offset + 1, consumer ); - return 2; } @@ -139,7 +137,7 @@ public FetchOptions getMappedFetchOptions() { @Override public boolean hasPartitionedSelectionMapping() { return associationMapping.getDiscriminatorPart().isPartitioned() - || associationMapping.getKeyPart().isPartitioned(); + || associationMapping.getKeyPart().isPartitioned(); } @Override @@ -250,13 +248,11 @@ public int getNumberOfFetchables() { @Override public Fetchable getFetchable(int position) { - switch ( position ) { - case 0: - return getDiscriminatorPart(); - case 1: - return getKeyPart(); - } - throw new IndexOutOfBoundsException(position); + return switch ( position ) { + case 0 -> getDiscriminatorPart(); + case 1 -> getKeyPart(); + default -> throw new IndexOutOfBoundsException( position ); + }; } @Override @@ -272,12 +268,9 @@ public int getJdbcTypeCount() { @Override public JdbcMapping getJdbcMapping(final int index) { final int base = getDiscriminatorPart().getJdbcTypeCount(); - if ( index >= base ) { - return getKeyPart().getJdbcMapping( index - base ); - } - else { - return getDiscriminatorPart().getJdbcMapping( index ); - } + return index >= base + ? getKeyPart().getJdbcMapping( index - base ) + : getDiscriminatorPart().getJdbcMapping( index ); } @Override @@ -351,8 +344,8 @@ public TableGroupJoin createTableGroupJoin( boolean fetched, boolean addsPredicate, SqlAstCreationState creationState) { - final SqlAstJoinType joinType = requireNonNullElse( requestedJoinType, SqlAstJoinType.INNER ); - final TableGroup tableGroup = createRootTableGroupJoin( + final var joinType = requireNonNullElse( requestedJoinType, SqlAstJoinType.INNER ); + final var tableGroup = createRootTableGroupJoin( navigablePath, lhs, explicitSourceAlias, diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddableMappingTypeImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddableMappingTypeImpl.java index bf9f7d845e63..26e929551532 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddableMappingTypeImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddableMappingTypeImpl.java @@ -18,11 +18,9 @@ import org.hibernate.MappingException; import org.hibernate.SharedSessionContract; import org.hibernate.dialect.Dialect; -import org.hibernate.dialect.aggregate.AggregateSupport; import org.hibernate.engine.FetchTiming; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.engine.spi.CascadeStyle; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.mapping.AggregateColumn; import org.hibernate.mapping.Any; @@ -32,7 +30,6 @@ import org.hibernate.mapping.DependantValue; import org.hibernate.mapping.Formula; import org.hibernate.mapping.Property; -import org.hibernate.mapping.Selectable; import org.hibernate.mapping.Value; import org.hibernate.metamodel.mapping.AttributeMapping; import org.hibernate.metamodel.mapping.EmbeddableDiscriminatorMapping; @@ -51,7 +48,6 @@ import org.hibernate.metamodel.spi.EmbeddableInstantiator; import org.hibernate.metamodel.spi.EmbeddableRepresentationStrategy; import org.hibernate.metamodel.spi.RuntimeModelCreationContext; -import org.hibernate.property.access.spi.PropertyAccess; import org.hibernate.spi.NavigablePath; import org.hibernate.sql.ast.tree.from.TableGroup; import org.hibernate.sql.ast.tree.from.TableGroupProducer; @@ -60,7 +56,6 @@ import org.hibernate.sql.results.graph.embeddable.internal.EmbeddableResultImpl; import org.hibernate.type.AnyType; import org.hibernate.type.BasicType; -import org.hibernate.type.BasicTypeRegistry; import org.hibernate.type.CollectionType; import org.hibernate.type.CompositeType; import org.hibernate.type.EntityType; @@ -193,8 +188,8 @@ private EmbeddableMappingTypeImpl( // Sort the entries by embeddable class name to have a somewhat stable subclass id final Set> entries = new TreeSet<>( Map.Entry.comparingByValue() ); entries.addAll( bootDescriptor.getDiscriminatorValues().entrySet() ); - for ( final Map.Entry discriminatorEntry : entries ) { - final ConcreteEmbeddableTypeImpl concreteEmbeddableType = new ConcreteEmbeddableTypeImpl( + for ( final var discriminatorEntry : entries ) { + final var concreteEmbeddableType = new ConcreteEmbeddableTypeImpl( representationStrategy.getInstantiatorForDiscriminator( discriminatorEntry.getKey() ), discriminatorEntry.getKey(), subclassId++ @@ -222,7 +217,8 @@ private EmbeddableMappingTypeImpl( updatable = componentProperty.isUpdatable(); } this.aggregateMapping = SelectableMappingImpl.from( - bootDescriptor.getOwner().getTable().getQualifiedName( creationContext.getSqlStringGenerationContext() ), + bootDescriptor.getOwner().getTable() + .getQualifiedName( creationContext.getSqlStringGenerationContext() ), aggregateColumn, bootDescriptor.getParentAggregateColumn() != null ? bootDescriptor.getParentAggregateColumn().getSelectablePath() @@ -237,7 +233,7 @@ private EmbeddableMappingTypeImpl( creationContext ); final int defaultSqlTypeCode = aggregateMapping.getJdbcMapping().getJdbcType().getDefaultSqlTypeCode(); - final AggregateSupport aggregateSupport = dialect.getAggregateSupport(); + final var aggregateSupport = dialect.getAggregateSupport(); final int sqlTypeCode = defaultSqlTypeCode == ARRAY ? aggregateColumn.getTypeCode() : defaultSqlTypeCode; this.aggregateMappingRequiresColumnWriter = aggregateSupport .requiresAggregateCustomWriteExpressionRenderer( sqlTypeCode ); @@ -261,11 +257,11 @@ private JdbcMapping resolveJdbcMapping(Component bootDescriptor, RuntimeModelCre // when the values of the component properties aren't fully initialized yet. // Both designs would do this as part of the "finishInitialization" phase, // so there is IMO no real win to do it differently - final TypeConfiguration typeConfiguration = creationContext.getTypeConfiguration(); - final BasicTypeRegistry basicTypeRegistry = typeConfiguration.getBasicTypeRegistry(); - final Column aggregateColumn = bootDescriptor.getAggregateColumn(); - final BasicValue basicValue = (BasicValue) aggregateColumn.getValue(); - final BasicValue.Resolution resolution = basicValue.getResolution(); + final var typeConfiguration = creationContext.getTypeConfiguration(); + final var basicTypeRegistry = typeConfiguration.getBasicTypeRegistry(); + final var aggregateColumn = bootDescriptor.getAggregateColumn(); + final var basicValue = (BasicValue) aggregateColumn.getValue(); + final var resolution = basicValue.getResolution(); final int aggregateColumnSqlTypeCode = resolution.getJdbcType().getDefaultSqlTypeCode(); final int aggregateSqlTypeCode; boolean isArray = false; @@ -442,18 +438,17 @@ private boolean finishInitialization( final Type subtype = subtypes[attributeIndex]; final Value value = bootPropertyDescriptor.getValue(); if ( subtype instanceof BasicType ) { - final BasicValue basicValue = (BasicValue) value; - final Selectable selectable = dependantValue != null ? - dependantValue.getColumns().get( dependantColumnIndex + columnPosition ) : - basicValue.getColumn(); + final var basicValue = (BasicValue) value; + final var selectable = + dependantValue != null + ? dependantValue.getColumns().get( dependantColumnIndex + columnPosition ) + : basicValue.getColumn(); final String containingTableExpression; final String columnExpression; if ( rootTableKeyColumnNames == null ) { if ( selectable.isFormula() ) { - columnExpression = selectable.getTemplate( - dialect, - creationProcess.getCreationContext().getTypeConfiguration() - ); + columnExpression = selectable.getTemplate( dialect, + creationProcess.getCreationContext().getTypeConfiguration() ); } else { columnExpression = selectable.getText( dialect ); @@ -472,7 +467,7 @@ private boolean finishInitialization( containingTableExpression = rootTableExpression; columnExpression = rootTableKeyColumnNames[columnPosition]; } - final NavigableRole role = valueMapping.getNavigableRole().append( bootPropertyDescriptor.getName() ); + final var role = valueMapping.getNavigableRole().append( bootPropertyDescriptor.getName() ); final SelectablePath selectablePath; final String columnDefinition; final Long length; @@ -541,14 +536,14 @@ private boolean finishInitialization( columnPosition++; } else if ( subtype instanceof AnyType anyType ) { - final Any bootValueMapping = (Any) value; + final var bootValueMapping = (Any) value; - final PropertyAccess propertyAccess = representationStrategy.resolvePropertyAccess( bootPropertyDescriptor ); + final var propertyAccess = representationStrategy.resolvePropertyAccess( bootPropertyDescriptor ); final boolean nullable = bootValueMapping.isNullable(); final boolean insertable = insertability[columnPosition]; final boolean updateable = updateability[columnPosition]; final boolean includeInOptimisticLocking = bootPropertyDescriptor.isOptimisticLocked(); - final CascadeStyle cascadeStyle = compositeType.getCascadeStyle( attributeIndex ); + final var cascadeStyle = compositeType.getCascadeStyle( attributeIndex ); SimpleAttributeMetadata attributeMetadataAccess = new SimpleAttributeMetadata( propertyAccess, @@ -650,7 +645,7 @@ else if ( subtype instanceof EntityType subentityType ) { if ( isPolymorphic() ) { final String declaringClass = bootDescriptor.getPropertyDeclaringClass( bootPropertyDescriptor ); - for ( Map.Entry entry : concreteEmbeddableBySubclass.entrySet() ) { + for ( var entry : concreteEmbeddableBySubclass.entrySet() ) { if ( isDefinedInClassOrSuperclass( bootDescriptor, declaringClass, entry.getKey() ) ) { entry.getValue().declaredAttributes.set( attributeMapping.getStateArrayPosition() ); } @@ -718,7 +713,7 @@ private EmbeddableDiscriminatorMapping generateDiscriminatorMapping( return null; } - final Selectable selectable = discriminator.getSelectables().get( 0 ); + final var selectable = discriminator.getSelectables().get( 0 ); final String discriminatorColumnExpression; final String columnDefinition; final String name; @@ -754,7 +749,8 @@ private EmbeddableDiscriminatorMapping generateDiscriminatorMapping( return new ExplicitColumnDiscriminatorMappingImpl( this, name, - bootDescriptor.getTable().getQualifiedName( creationContext.getSqlStringGenerationContext() ), + bootDescriptor.getTable() + .getQualifiedName( creationContext.getSqlStringGenerationContext() ), discriminatorColumnExpression, isFormula, !isFormula, @@ -876,12 +872,13 @@ protected Object[] getAttributeValues(Object compositeInstance) { else { final int numberOfAttributes = getNumberOfAttributeMappings(); final Object[] results = new Object[numberOfAttributes + 1]; - final ConcreteEmbeddableType concreteEmbeddableType = findSubtypeBySubclass( compositeInstance.getClass().getName() ); + final var concreteEmbeddableType = findSubtypeBySubclass( compositeInstance.getClass().getName() ); int i = 0; for ( ; i < numberOfAttributes; i++ ) { - results[i] = concreteEmbeddableType.declaresAttribute( i ) - ? getValue( compositeInstance, i ) - : null; + results[i] = + concreteEmbeddableType.declaresAttribute( i ) + ? getValue( compositeInstance, i ) + : null; } results[i] = compositeInstance.getClass(); return results; @@ -895,7 +892,7 @@ protected void setAttributeValues(Object component, Object[] values) { } else { final String compositeClassName = component.getClass().getName(); - final ConcreteEmbeddableType concreteEmbeddableType = findSubtypeBySubclass( compositeClassName ); + final var concreteEmbeddableType = findSubtypeBySubclass( compositeClassName ); for ( int i = 0; i < getNumberOfAttributeMappings(); i++ ) { final AttributeMapping attributeMapping = getAttributeMapping( i ); if ( concreteEmbeddableType.declaresAttribute( attributeMapping ) ) { @@ -933,7 +930,7 @@ public int breakDownJdbcValues( assert values.length == size + ( isPolymorphic() ? 1 : 0 ); int i = 0; for ( ; i < size; i++ ) { - final AttributeMapping attributeMapping = attributeMappings.get( i ); + final var attributeMapping = attributeMappings.get( i ); if ( !attributeMapping.isPluralAttributeMapping() ) { final Object attributeValue = values[i]; span += attributeMapping.breakDownJdbcValues( @@ -951,15 +948,18 @@ public int breakDownJdbcValues( } } else { - final ConcreteEmbeddableType concreteEmbeddableType = domainValue == null - ? null - : findSubtypeBySubclass( domainValue.getClass().getName() ); + final var concreteEmbeddableType = + domainValue == null + ? null + : findSubtypeBySubclass( domainValue.getClass().getName() ); for ( int i = 0; i < size; i++ ) { - final AttributeMapping attributeMapping = attributeMappings.get( i ); + final var attributeMapping = attributeMappings.get( i ); if ( !attributeMapping.isPluralAttributeMapping() ) { - final Object attributeValue = concreteEmbeddableType == null || !concreteEmbeddableType.declaresAttribute( attributeMapping ) - ? null - : getValue( domainValue, i ); + final Object attributeValue = + concreteEmbeddableType == null + || !concreteEmbeddableType.declaresAttribute( attributeMapping ) + ? null + : getValue( domainValue, i ); span += attributeMapping.breakDownJdbcValues( attributeValue, offset + span, @@ -989,7 +989,7 @@ public int forEachJdbcValue( int span = 0; if ( value == null ) { for ( int i = 0; i < attributeMappings.size(); i++ ) { - final AttributeMapping attributeMapping = attributeMappings.get( i ); + final var attributeMapping = attributeMappings.get( i ); if ( !(attributeMapping instanceof PluralAttributeMapping) ) { span += attributeMapping.forEachJdbcValue( null, span + offset, x, y, valuesConsumer, session ); } @@ -999,17 +999,16 @@ public int forEachJdbcValue( } } else { - final ConcreteEmbeddableType concreteEmbeddableType = findSubtypeBySubclass( value.getClass().getName() ); + final var concreteEmbeddableType = findSubtypeBySubclass( value.getClass().getName() ); for ( int i = 0; i < attributeMappings.size(); i++ ) { - final AttributeMapping attributeMapping = attributeMappings.get( i ); + final var attributeMapping = attributeMappings.get( i ); if ( !(attributeMapping instanceof PluralAttributeMapping) ) { final Object attributeValue = concreteEmbeddableType == null || !concreteEmbeddableType.declaresAttribute( attributeMapping ) ? null : getValue( value, i ); - span += attributeMapping.forEachJdbcValue( attributeValue, span + offset, x, y, valuesConsumer, - session ); + span += attributeMapping.forEachJdbcValue( attributeValue, span + offset, x, y, valuesConsumer, session ); } } if ( isPolymorphic() ) { @@ -1038,7 +1037,7 @@ public int decompose( assert values.length == size + ( isPolymorphic() ? 1 : 0 ); int i = 0; for ( ; i < size; i++ ) { - final AttributeMapping attributeMapping = attributeMappings.get( i ); + final var attributeMapping = attributeMappings.get( i ); final Object attributeValue = values[ i ]; span += attributeMapping.decompose( attributeValue, offset + span, x, y, valueConsumer, session ); } @@ -1047,15 +1046,18 @@ public int decompose( } } else { - final ConcreteEmbeddableType concreteEmbeddableType = domainValue == null - ? null - : findSubtypeBySubclass( domainValue.getClass().getName() ); + final var concreteEmbeddableType = + domainValue == null + ? null + : findSubtypeBySubclass( domainValue.getClass().getName() ); for ( int i = 0; i < size; i++ ) { - final AttributeMapping attributeMapping = attributeMappings.get( i ); + final var attributeMapping = attributeMappings.get( i ); if ( !attributeMapping.isPluralAttributeMapping() ) { - final Object attributeValue = concreteEmbeddableType == null || !concreteEmbeddableType.declaresAttribute( attributeMapping ) - ? null - : attributeMapping.getPropertyAccess().getGetter().get( domainValue ); + final Object attributeValue = + concreteEmbeddableType == null + || !concreteEmbeddableType.declaresAttribute( attributeMapping ) + ? null + : attributeMapping.getPropertyAccess().getGetter().get( domainValue ); span += attributeMapping.decompose( attributeValue, offset + span, x, y, valueConsumer, session ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedAttributeMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedAttributeMapping.java index 8d5a04813856..68e0aab1a2f6 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedAttributeMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedAttributeMapping.java @@ -12,15 +12,12 @@ import org.hibernate.AssertionFailure; import org.hibernate.engine.FetchStyle; import org.hibernate.engine.FetchTiming; -import org.hibernate.internal.util.collections.CollectionHelper; -import org.hibernate.metamodel.mapping.AttributeMapping; import org.hibernate.metamodel.mapping.AttributeMetadata; import org.hibernate.metamodel.mapping.EmbeddableMappingType; import org.hibernate.metamodel.mapping.EmbeddableValuedModelPart; import org.hibernate.metamodel.mapping.JdbcMapping; import org.hibernate.metamodel.mapping.ManagedMappingType; import org.hibernate.metamodel.mapping.PropertyBasedMapping; -import org.hibernate.metamodel.mapping.SelectableMapping; import org.hibernate.metamodel.mapping.SelectableMappings; import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.property.access.internal.PropertyAccessStrategyBasicImpl; @@ -33,13 +30,11 @@ import org.hibernate.sql.ast.spi.SqlAstCreationState; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.expression.ColumnReference; -import org.hibernate.sql.ast.tree.expression.Expression; import org.hibernate.sql.ast.tree.expression.SqlTuple; import org.hibernate.sql.ast.tree.from.StandardVirtualTableGroup; import org.hibernate.sql.ast.tree.from.TableGroup; import org.hibernate.sql.ast.tree.from.TableGroupJoin; import org.hibernate.sql.ast.tree.from.TableGroupProducer; -import org.hibernate.sql.ast.tree.from.TableReference; import org.hibernate.sql.ast.tree.predicate.Predicate; import org.hibernate.sql.results.graph.DomainResult; import org.hibernate.sql.results.graph.DomainResultCreationState; @@ -55,6 +50,7 @@ import org.checkerframework.checker.nullness.qual.Nullable; import static java.util.Objects.requireNonNullElse; +import static org.hibernate.internal.util.collections.CollectionHelper.arrayList; /** * @author Steve Ebersole @@ -128,12 +124,9 @@ public EmbeddedAttributeMapping( this.embeddableMappingType = embeddableMappingType; - if ( getAttributeName().equals( NavigablePath.IDENTIFIER_MAPPER_PROPERTY ) ) { - selectable = false; - } - else { - selectable = attributeMetadata.isSelectable(); - } + selectable = + !getAttributeName().equals( NavigablePath.IDENTIFIER_MAPPER_PROPERTY ) + && attributeMetadata.isSelectable(); } // Constructor is only used for creating the inverse attribute mapping @@ -160,28 +153,23 @@ public EmbeddedAttributeMapping( : null ); - this.navigableRole = inverseModelPart.getNavigableRole().getParent().append( inverseModelPart.getFetchableName() ); + navigableRole = inverseModelPart.getNavigableRole().getParent().append( inverseModelPart.getFetchableName() ); - this.tableExpression = selectableMappings.getSelectable( 0 ).getContainingTableExpression(); - this.embeddableMappingType = embeddableTypeDescriptor.createInverseMappingType( + tableExpression = selectableMappings.getSelectable( 0 ).getContainingTableExpression(); + embeddableMappingType = embeddableTypeDescriptor.createInverseMappingType( this, declaringTableGroupProducer, selectableMappings, creationProcess ); - this.parentInjectionAttributePropertyAccess = null; + parentInjectionAttributePropertyAccess = null; if ( getAttributeName().equals( NavigablePath.IDENTIFIER_MAPPER_PROPERTY ) ) { selectable = false; } else { - AttributeMapping attributeMapping = inverseModelPart.asAttributeMapping(); - if ( attributeMapping != null ) { - selectable = attributeMapping.isSelectable(); - } - else { - selectable = true; - } + final var attributeMapping = inverseModelPart.asAttributeMapping(); + selectable = attributeMapping == null || attributeMapping.isSelectable(); } } @@ -284,9 +272,9 @@ public SqlTuple toSqlExpression( SqmToSqlAstConverter walker, SqlAstCreationState sqlAstCreationState) { if ( embeddableMappingType.getAggregateMapping() != null ) { - final SelectableMapping selection = embeddableMappingType.getAggregateMapping(); - final NavigablePath navigablePath = tableGroup.getNavigablePath().append( getNavigableRole().getNavigableName() ); - final TableReference tableReference = tableGroup.resolveTableReference( navigablePath, getContainingTableExpression() ); + final var selection = embeddableMappingType.getAggregateMapping(); + final var navigablePath = tableGroup.getNavigablePath().append( getNavigableRole().getNavigableName() ); + final var tableReference = tableGroup.resolveTableReference( navigablePath, getContainingTableExpression() ); return new SqlTuple( Collections.singletonList( sqlAstCreationState.getSqlExpressionResolver().resolveSqlExpression( @@ -297,18 +285,18 @@ public SqlTuple toSqlExpression( this ); } - final List columnReferences = CollectionHelper.arrayList( embeddableMappingType.getJdbcTypeCount() ); - final NavigablePath navigablePath = tableGroup.getNavigablePath().append( getNavigableRole().getNavigableName() ); - final TableReference defaultTableReference = tableGroup.resolveTableReference( navigablePath, this, getContainingTableExpression() ); + final List columnReferences = arrayList( embeddableMappingType.getJdbcTypeCount() ); + final var navigablePath = tableGroup.getNavigablePath().append( getNavigableRole().getNavigableName() ); + final var defaultTableReference = tableGroup.resolveTableReference( navigablePath, this, getContainingTableExpression() ); getEmbeddableTypeDescriptor().forEachSelectable( (columnIndex, selection) -> { - final TableReference tableReference = getContainingTableExpression().equals( selection.getContainingTableExpression() ) - ? defaultTableReference - : tableGroup.resolveTableReference( navigablePath, this, selection.getContainingTableExpression() ); - final Expression columnReference = sqlAstCreationState.getSqlExpressionResolver().resolveSqlExpression( - tableReference, - selection - ); + final var tableReference = + getContainingTableExpression().equals( selection.getContainingTableExpression() ) + ? defaultTableReference + : tableGroup.resolveTableReference( navigablePath, this, selection.getContainingTableExpression() ); + final var columnReference = + sqlAstCreationState.getSqlExpressionResolver() + .resolveSqlExpression( tableReference, selection ); columnReferences.add( columnReference.getColumnReference() ); } @@ -327,8 +315,8 @@ public TableGroupJoin createTableGroupJoin( boolean fetched, boolean addsPredicate, SqlAstCreationState creationState) { - final SqlAstJoinType joinType = requireNonNullElse( requestedJoinType, SqlAstJoinType.INNER ); - final TableGroup tableGroup = createRootTableGroupJoin( + final var joinType = requireNonNullElse( requestedJoinType, SqlAstJoinType.INNER ); + final var tableGroup = createRootTableGroupJoin( navigablePath, lhs, explicitSourceAlias, @@ -398,7 +386,7 @@ public boolean isSelectable() { @Override public boolean containsTableReference(String tableExpression) { - final ManagedMappingType declaringType = getDeclaringType(); + final var declaringType = getDeclaringType(); final TableGroupProducer producer; if ( declaringType instanceof TableGroupProducer tableGroupProducer ) { producer = tableGroupProducer; diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedCollectionPart.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedCollectionPart.java index daf4b553e4a0..c5d19af063b7 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedCollectionPart.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedCollectionPart.java @@ -26,7 +26,6 @@ import org.hibernate.spi.NavigablePath; import org.hibernate.sql.ast.Clause; import org.hibernate.sql.ast.SqlAstJoinType; -import org.hibernate.sql.ast.spi.FromClauseAccess; import org.hibernate.sql.ast.spi.SqlAliasBase; import org.hibernate.sql.ast.spi.SqlAstCreationState; import org.hibernate.sql.ast.spi.SqlExpressionResolver; @@ -179,19 +178,17 @@ public Fetch generateFetch( } private TableGroup resolveTableGroup(NavigablePath fetchablePath, DomainResultCreationState creationState) { - final FromClauseAccess fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess(); + final var fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess(); return fromClauseAccess.resolveTableGroup( fetchablePath, np -> { - final PluralTableGroup parentTableGroup = (PluralTableGroup) fromClauseAccess.getTableGroup( np.getParent() ); - switch ( nature ) { - case ELEMENT: - return parentTableGroup.getElementTableGroup(); - case INDEX: - return parentTableGroup.getIndexTableGroup(); - } - - throw new IllegalStateException( "Could not find table group for: " + np ); + final var parentTableGroup = (PluralTableGroup) fromClauseAccess.getTableGroup( np.getParent() ); + return switch ( nature ) { + case ELEMENT -> parentTableGroup.getElementTableGroup(); + case INDEX -> parentTableGroup.getIndexTableGroup(); + default -> throw new IllegalStateException( "Could not find table group for: " + np ); + }; + } ); } @@ -324,8 +321,10 @@ public FetchTiming getTiming() { @Override public boolean containsTableReference(String tableExpression) { if ( collectionDescriptor.isOneToMany() ) { - return ( (EntityCollectionPart) collectionDescriptor.getAttributeMapping().getElementDescriptor() ) - .getPartMappingType().containsTableReference( tableExpression ); + final var elementDescriptor = + (EntityCollectionPart) + collectionDescriptor.getAttributeMapping().getElementDescriptor(); + return elementDescriptor.getPartMappingType().containsTableReference( tableExpression ); } return collectionDescriptor.getAttributeMapping().containsTableReference( tableExpression ); } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedForeignKeyDescriptor.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedForeignKeyDescriptor.java index 6735bdfc9139..ba2b89492cc7 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedForeignKeyDescriptor.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedForeignKeyDescriptor.java @@ -14,7 +14,6 @@ import org.hibernate.internal.util.IndexedConsumer; import org.hibernate.internal.util.MutableInteger; import org.hibernate.metamodel.mapping.AssociationKey; -import org.hibernate.metamodel.mapping.AttributeMapping; import org.hibernate.metamodel.mapping.CompositeIdentifierMapping; import org.hibernate.metamodel.mapping.EmbeddableMappingType; import org.hibernate.metamodel.mapping.EmbeddableValuedModelPart; @@ -192,10 +191,10 @@ public boolean isKeyPart(ValuedModelPart modelPart) { return true; } else { - AttributeMapping attributeMapping = modelPart.asAttributeMapping(); + var attributeMapping = modelPart.asAttributeMapping(); while ( attributeMapping != null && attributeMapping.getDeclaringType() instanceof EmbeddableMappingType embeddableMappingType ) { - final EmbeddableValuedModelPart declaringModelPart = embeddableMappingType.getEmbeddedValueMapping(); + final var declaringModelPart = embeddableMappingType.getEmbeddedValueMapping(); if ( declaringModelPart == keyPart ) { return true; } @@ -226,7 +225,7 @@ public ForeignKeyDescriptor withKeySelectionMapping( TableGroupProducer declaringTableGroupProducer, IntFunction selectableMappingAccess, MappingModelCreationProcess creationProcess) { - SelectableMapping[] selectionMappings = new SelectableMapping[keySelectableMappings.getJdbcTypeCount()]; + final var selectionMappings = new SelectableMapping[keySelectableMappings.getJdbcTypeCount()]; for ( int i = 0; i < selectionMappings.length; i++ ) { selectionMappings[i] = selectableMappingAccess.apply( i ); } @@ -426,7 +425,7 @@ public Predicate generateJoinPredicate( TableReference targetSideReference, TableReference keySideReference, SqlAstCreationState creationState) { - final Junction predicate = new Junction( Junction.Nature.CONJUNCTION ); + final var predicate = new Junction( Junction.Nature.CONJUNCTION ); targetSelectableMappings.forEachSelectable( (i, selection) -> { final ComparisonPredicate comparisonPredicate = new ComparisonPredicate( diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmptyAttributeMappingsMap.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmptyAttributeMappingsMap.java index 1279b06c5db5..a63724d200b8 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmptyAttributeMappingsMap.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmptyAttributeMappingsMap.java @@ -4,12 +4,13 @@ */ package org.hibernate.metamodel.mapping.internal; -import java.util.Collections; import java.util.function.Consumer; import org.hibernate.metamodel.mapping.AttributeMapping; import org.hibernate.metamodel.mapping.AttributeMappingsMap; +import static java.util.Collections.emptyList; + public final class EmptyAttributeMappingsMap implements AttributeMappingsMap { public static final EmptyAttributeMappingsMap INSTANCE = new EmptyAttributeMappingsMap(); @@ -31,7 +32,7 @@ public AttributeMapping get(String name) { @Override public Iterable valueIterator() { - return Collections.EMPTY_LIST; + return emptyList(); } } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EntityRowIdMappingImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EntityRowIdMappingImpl.java index cf2e55651144..e71a9dcb4922 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EntityRowIdMappingImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EntityRowIdMappingImpl.java @@ -18,11 +18,8 @@ import org.hibernate.metamodel.mapping.MappingType; import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.spi.NavigablePath; -import org.hibernate.sql.ast.spi.SqlAstCreationState; -import org.hibernate.sql.ast.spi.SqlExpressionResolver; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.from.TableGroup; -import org.hibernate.sql.ast.tree.from.TableReference; import org.hibernate.sql.results.graph.DomainResult; import org.hibernate.sql.results.graph.DomainResultCreationState; import org.hibernate.sql.results.graph.Fetch; @@ -91,12 +88,12 @@ public DomainResult createDomainResult( TableGroup tableGroup, String resultVariable, DomainResultCreationState creationState) { - final SqlAstCreationState sqlAstCreationState = creationState.getSqlAstCreationState(); + final var sqlAstCreationState = creationState.getSqlAstCreationState(); - final SqlExpressionResolver sqlExpressionResolver = sqlAstCreationState.getSqlExpressionResolver(); - final TableReference columnTableReference = tableGroup.resolveTableReference( navigablePath, tableExpression ); + final var sqlExpressionResolver = sqlAstCreationState.getSqlExpressionResolver(); + final var columnTableReference = tableGroup.resolveTableReference( navigablePath, tableExpression ); - final SqlSelection sqlSelection = sqlExpressionResolver.resolveSqlSelection( + final var sqlSelection = sqlExpressionResolver.resolveSqlSelection( sqlExpressionResolver.resolveSqlExpression( columnTableReference, this ), rowIdType.getJdbcJavaType(), null, diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EntityVersionMappingImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EntityVersionMappingImpl.java index 8c5cf1d2feeb..e8f5a3062546 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EntityVersionMappingImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EntityVersionMappingImpl.java @@ -345,10 +345,10 @@ public int breakDownJdbcValues( } private SqlSelection resolveSqlSelection(TableGroup tableGroup, DomainResultCreationState creationState) { - final SqlAstCreationState sqlAstCreationState = creationState.getSqlAstCreationState(); + final var sqlAstCreationState = creationState.getSqlAstCreationState(); - final SqlExpressionResolver sqlExpressionResolver = sqlAstCreationState.getSqlExpressionResolver(); - final TableReference columnTableReference = tableGroup.resolveTableReference( + final var sqlExpressionResolver = sqlAstCreationState.getSqlExpressionResolver(); + final var columnTableReference = tableGroup.resolveTableReference( tableGroup.getNavigablePath() .append( getNavigableRole().getNavigableName() ), columnTableExpression diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ExplicitColumnDiscriminatorMappingImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ExplicitColumnDiscriminatorMappingImpl.java index ff01a75b4c77..4cdafde04d55 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ExplicitColumnDiscriminatorMappingImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ExplicitColumnDiscriminatorMappingImpl.java @@ -12,11 +12,9 @@ import org.hibernate.metamodel.mapping.ManagedMappingType; import org.hibernate.spi.NavigablePath; import org.hibernate.sql.ast.spi.SqlAstCreationState; -import org.hibernate.sql.ast.spi.SqlExpressionResolver; import org.hibernate.sql.ast.tree.expression.ColumnReference; import org.hibernate.sql.ast.tree.expression.Expression; import org.hibernate.sql.ast.tree.from.TableGroup; -import org.hibernate.sql.ast.tree.from.TableReference; import org.hibernate.type.BasicType; import static org.hibernate.sql.ast.spi.SqlExpressionResolver.createColumnReferenceKey; @@ -86,7 +84,9 @@ public ExplicitColumnDiscriminatorMappingImpl( @Nullable Integer scale, DiscriminatorType discriminatorType) { //noinspection unchecked - super( mappingType, (DiscriminatorType) discriminatorType, (BasicType) discriminatorType.getUnderlyingJdbcMapping() ); + super( mappingType, + (DiscriminatorType) discriminatorType, + (BasicType) discriminatorType.getUnderlyingJdbcMapping() ); this.name = name; this.tableExpression = tableExpression; this.isPhysical = isPhysical; @@ -124,9 +124,8 @@ public Expression resolveSqlExpression( JdbcMapping jdbcMappingToUse, TableGroup tableGroup, SqlAstCreationState creationState) { - final SqlExpressionResolver expressionResolver = creationState.getSqlExpressionResolver(); - final TableReference tableReference = tableGroup.resolveTableReference( navigablePath, tableExpression ); - + final var expressionResolver = creationState.getSqlExpressionResolver(); + final var tableReference = tableGroup.resolveTableReference( navigablePath, tableExpression ); return expressionResolver.resolveSqlExpression( createColumnReferenceKey( tableGroup.getPrimaryTableReference(), diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/GeneratedValuesProcessor.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/GeneratedValuesProcessor.java index beb8e5b42279..ddf3246de2aa 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/GeneratedValuesProcessor.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/GeneratedValuesProcessor.java @@ -14,7 +14,6 @@ import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.generator.EventType; -import org.hibernate.generator.Generator; import org.hibernate.generator.OnExecutionGenerator; import org.hibernate.generator.values.GeneratedValues; import org.hibernate.generator.values.GeneratedValuesMutationDelegate; @@ -72,8 +71,7 @@ public GeneratedValuesProcessor( jdbcParameters = null; } else { - final JdbcParametersList.Builder builder = JdbcParametersList.newBuilder(); - + final var builder = JdbcParametersList.newBuilder(); selectStatement = LoaderSelectBuilder.createSelect( entityDescriptor, generatedValuesToSelect, @@ -85,7 +83,8 @@ public GeneratedValuesProcessor( builder::add, sessionFactory ); - jdbcSelect = sessionFactory.getJdbcServices().getJdbcEnvironment().getSqlAstTranslatorFactory() + jdbcSelect = + sessionFactory.getJdbcServices().getJdbcEnvironment().getSqlAstTranslatorFactory() .buildSelectTranslator( sessionFactory, selectStatement ) .translate( JdbcParameterBindings.NO_BINDINGS, QueryOptions.NONE ); jdbcParameters = builder.build(); @@ -95,10 +94,10 @@ public GeneratedValuesProcessor( private boolean needsSubsequentSelect(EventType timing, List generatedAttributes) { if ( timing == EventType.INSERT ) { return entityDescriptor.getInsertDelegate() == null - || !entityDescriptor.getInsertDelegate().supportsArbitraryValues() - // Check if we need to select more properties than what is processed by the identity delegate. - // This can happen for on-execution generated values on non-identifier tables - || generatedAttributes.size() > numberOfGeneratedNonIdentifierProperties( timing ); + || !entityDescriptor.getInsertDelegate().supportsArbitraryValues() + // Check if we need to select more properties than what is processed by the identity delegate. + // This can happen for on-execution generated values on non-identifier tables + || generatedAttributes.size() > numberOfGeneratedNonIdentifierProperties( timing ); } else { return entityDescriptor.getUpdateDelegate() == null; @@ -123,10 +122,10 @@ private int numberOfGeneratedNonIdentifierProperties(EventType timing) { public static List getGeneratedAttributes(EntityMappingType entityDescriptor, EventType timing) { // todo (6.0): For now, we rely on the entity metamodel as composite attributes report // GenerationTiming.NEVER even if they have attributes that would need generation - final Generator[] generators = entityDescriptor.getEntityPersister().getGenerators(); + final var generators = entityDescriptor.getEntityPersister().getGenerators(); final List generatedValuesToSelect = new ArrayList<>(); entityDescriptor.forEachAttributeMapping( mapping -> { - final Generator generator = generators[ mapping.getStateArrayPosition() ]; + final var generator = generators[ mapping.getStateArrayPosition() ]; if ( generator != null && generator.generatedOnExecution() && generator.getEventTypes().contains(timing) ) { @@ -147,20 +146,20 @@ public void processGeneratedValues( SharedSessionContractImplementor session) { if ( hasActualGeneratedValuesToSelect( session, entity ) ) { if ( selectStatement != null ) { - final List results = executeSelect( id, session ); + final var results = executeSelect( id, session ); assert results.size() == 1; setEntityAttributes( entity, state, results.get( 0 ) ); } else if ( generatedValues != null ) { // can be null when an update action resulted in a no-op (e.g. only changes to unowned association) - final List results = generatedValues.getGeneratedValues( generatedValuesToSelect ); + final var results = generatedValues.getGeneratedValues( generatedValuesToSelect ); setEntityAttributes( entity, state, results.toArray( new Object[0] ) ); } } } private boolean hasActualGeneratedValuesToSelect(SharedSessionContractImplementor session, Object entity) { - for ( AttributeMapping attributeMapping : generatedValuesToSelect ) { + for ( var attributeMapping : generatedValuesToSelect ) { if ( attributeMapping.getGenerator().generatedOnExecution( entity, session ) ) { return true; } @@ -169,7 +168,7 @@ private boolean hasActualGeneratedValuesToSelect(SharedSessionContractImplemento } private List executeSelect(Object id, SharedSessionContractImplementor session) { - final JdbcParameterBindings jdbcParamBindings = getJdbcParameterBindings( id, session ); + final var jdbcParamBindings = getJdbcParameterBindings( id, session ); return session.getFactory().getJdbcServices().getJdbcSelectExecutor().list( jdbcSelect, jdbcParamBindings, @@ -182,7 +181,7 @@ private List executeSelect(Object id, SharedSessionContractImplementor } private JdbcParameterBindings getJdbcParameterBindings(Object id, SharedSessionContractImplementor session) { - final JdbcParameterBindings jdbcParamBindings = new JdbcParameterBindingsImpl( jdbcParameters.size() ); + final var jdbcParamBindings = new JdbcParameterBindingsImpl( jdbcParameters.size() ); int offset = jdbcParamBindings.registerParametersForEachJdbcValue( id, entityDescriptor.getIdentifierMapping(), @@ -195,7 +194,7 @@ private JdbcParameterBindings getJdbcParameterBindings(Object id, SharedSessionC private void setEntityAttributes(Object entity, Object[] state, Object[] selectionResults) { for ( int i = 0; i < generatedValuesToSelect.size(); i++ ) { - final AttributeMapping attribute = generatedValuesToSelect.get( i ); + final var attribute = generatedValuesToSelect.get( i ); final Object generatedValue = selectionResults[i]; state[ attribute.getStateArrayPosition() ] = generatedValue; attribute.getAttributeMetadata().getPropertyAccess().getSetter().set( entity, generatedValue ); diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/IdClassEmbeddable.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/IdClassEmbeddable.java index b0b1dd53b70f..7255aa3c04c8 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/IdClassEmbeddable.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/IdClassEmbeddable.java @@ -8,26 +8,19 @@ import org.hibernate.engine.FetchStyle; import org.hibernate.engine.FetchTiming; -import org.hibernate.engine.spi.EntityHolder; -import org.hibernate.engine.spi.EntityKey; -import org.hibernate.engine.spi.PersistenceContext; -import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.mapping.Component; import org.hibernate.mapping.RootClass; import org.hibernate.metamodel.mapping.AttributeMapping; -import org.hibernate.metamodel.mapping.AttributeMetadata; import org.hibernate.metamodel.mapping.EmbeddableMappingType; import org.hibernate.metamodel.mapping.EmbeddableValuedModelPart; import org.hibernate.metamodel.mapping.EntityIdentifierMapping; import org.hibernate.metamodel.mapping.EntityMappingType; -import org.hibernate.metamodel.mapping.ModelPart; import org.hibernate.metamodel.mapping.NonAggregatedIdentifierMapping; import org.hibernate.metamodel.mapping.NonAggregatedIdentifierMapping.IdentifierValueMapper; import org.hibernate.metamodel.mapping.SelectableMappings; import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.metamodel.spi.EmbeddableRepresentationStrategy; -import org.hibernate.persister.entity.EntityPersister; import org.hibernate.property.access.internal.PropertyAccessStrategyMapImpl; import org.hibernate.property.access.spi.PropertyAccess; import org.hibernate.spi.NavigablePath; @@ -64,27 +57,29 @@ public IdClassEmbeddable( MappingModelCreationProcess creationProcess) { super( new MutableAttributeMappingList( idClassSource.getPropertySpan() ) ); - this.navigableRole = idMapping.getNavigableRole().append( NavigablePath.IDENTIFIER_MAPPER_PROPERTY ); this.idMapping = idMapping; this.virtualIdEmbeddable = virtualIdEmbeddable; - this.javaType = creationProcess.getCreationContext().getTypeConfiguration() - .getJavaTypeRegistry() - .resolveManagedTypeDescriptor( idClassSource.getComponentClass() ); + navigableRole = idMapping.getNavigableRole().append( NavigablePath.IDENTIFIER_MAPPER_PROPERTY ); - this.representationStrategy = new IdClassRepresentationStrategy( + javaType = + creationProcess.getCreationContext().getTypeConfiguration().getJavaTypeRegistry() + .resolveManagedTypeDescriptor( idClassSource.getComponentClass() ); + + representationStrategy = new IdClassRepresentationStrategy( this, idClassSource.sortProperties() == null, idClassSource::getPropertyNames ); - final PropertyAccess propertyAccess = PropertyAccessStrategyMapImpl.INSTANCE.buildPropertyAccess( - null, - EntityIdentifierMapping.ID_ROLE_NAME, - true ); - final AttributeMetadata attributeMetadata = MappingModelCreationHelper.getAttributeMetadata( - propertyAccess - ); + final var propertyAccess = + PropertyAccessStrategyMapImpl.INSTANCE.buildPropertyAccess( + null, + EntityIdentifierMapping.ID_ROLE_NAME, + true + ); + final var attributeMetadata = + MappingModelCreationHelper.getAttributeMetadata( propertyAccess ); embedded = new EmbeddedAttributeMapping( NavigablePath.IDENTIFIER_MAPPER_PROPERTY, @@ -103,7 +98,7 @@ public IdClassEmbeddable( propertyAccess ); - final CompositeType idClassType = idClassSource.getType(); + final var idClassType = idClassSource.getType(); ( (CompositeTypeImplementor) idClassType ).injectMappingModelPart( embedded, creationProcess ); creationProcess.registerInitializationCallback( @@ -169,33 +164,31 @@ public Object getIdentifier(Object entity, SharedSessionContractImplementor sess final Object[] propertyValues = new Object[virtualIdEmbeddable.getNumberOfAttributeMappings()]; for ( int i = 0; i < propertyValues.length; i++ ) { - final AttributeMapping attributeMapping = virtualIdEmbeddable.getAttributeMapping( i ); - final Object o = attributeMapping.getValue( entity ); - if ( o == null ) { - final AttributeMapping idClassAttributeMapping = getAttributeMapping( i ); - if ( idClassAttributeMapping.getPropertyAccess().getGetter().getReturnTypeClass().isPrimitive() ) { - propertyValues[i] = idClassAttributeMapping.getExpressibleJavaType().getDefaultValue(); - } - else { - propertyValues[i] = null; - } + final var attributeMapping = virtualIdEmbeddable.getAttributeMapping( i ); + final Object object = attributeMapping.getValue( entity ); + if ( object == null ) { + final var idClassAttributeMapping = getAttributeMapping( i ); + propertyValues[i] = + idClassAttributeMapping.getPropertyAccess().getGetter().getReturnTypeClass().isPrimitive() + ? idClassAttributeMapping.getExpressibleJavaType().getDefaultValue() + : null; } //JPA 2 @MapsId + @IdClass points to the pk of the entity else if ( attributeMapping instanceof ToOneAttributeMapping toOneAttributeMapping && !( getAttributeMapping( i ) instanceof ToOneAttributeMapping ) ) { - final ModelPart targetPart = + final var targetPart = toOneAttributeMapping.getForeignKeyDescriptor() .getPart( toOneAttributeMapping.getSideNature().inverse() ); if ( targetPart.isEntityIdentifierMapping() ) { - propertyValues[i] = ( (EntityIdentifierMapping) targetPart ).getIdentifier( o ); + propertyValues[i] = ( (EntityIdentifierMapping) targetPart ).getIdentifier( object ); } else { - propertyValues[i] = o; + propertyValues[i] = object; assert false; } } else { - propertyValues[i] = o; + propertyValues[i] = object; } } @@ -206,33 +199,32 @@ else if ( attributeMapping instanceof ToOneAttributeMapping toOneAttributeMappin @Override public void setIdentifier(Object entity, Object id, SharedSessionContractImplementor session) { - final SessionFactoryImplementor factory = session.getFactory(); - final EntityPersister entityDescriptor = + final var factory = session.getFactory(); + final var entityDescriptor = factory.getMappingMetamodel() .getEntityDescriptor( entity.getClass() ); final Object[] propertyValues = new Object[attributeMappings.size()]; virtualIdEmbeddable.forEachAttribute( (position, virtualIdAttribute) -> { - final AttributeMapping idClassAttribute = attributeMappings.get( position ); - Object o = idClassAttribute.getValue( id ); + final var idClassAttribute = attributeMappings.get( position ); + Object object = idClassAttribute.getValue( id ); if ( virtualIdAttribute instanceof ToOneAttributeMapping toOneAttributeMapping - && !( idClassAttribute instanceof ToOneAttributeMapping ) ) { - final EntityPersister entityPersister = - toOneAttributeMapping.getEntityMappingType().getEntityPersister(); - final EntityKey entityKey = session.generateEntityKey( o, entityPersister ); - final PersistenceContext persistenceContext = session.getPersistenceContext(); - final EntityHolder holder = persistenceContext.getEntityHolder( entityKey ); + && !( idClassAttribute instanceof ToOneAttributeMapping ) ) { + final var entityPersister = + toOneAttributeMapping.getEntityMappingType() + .getEntityPersister(); + final var entityKey = session.generateEntityKey( object, entityPersister ); + final var persistenceContext = session.getPersistenceContext(); + final var holder = persistenceContext.getEntityHolder( entityKey ); // use the managed object i.e. proxy or initialized entity - o = holder == null ? null : holder.getManagedObject(); - if ( o == null ) { + object = holder == null ? null : holder.getManagedObject(); + if ( object == null ) { // get the association out of the entity itself - o = entityDescriptor.getPropertyValue( - entity, - toOneAttributeMapping.getAttributeName() - ); + object = entityDescriptor.getPropertyValue( entity, + toOneAttributeMapping.getAttributeName() ); } } - propertyValues[position] = o; + propertyValues[position] = object; } ); diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/IdClassRepresentationStrategy.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/IdClassRepresentationStrategy.java index a5f8cb4cd9fc..dfc74356e18c 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/IdClassRepresentationStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/IdClassRepresentationStrategy.java @@ -17,7 +17,6 @@ import org.hibernate.metamodel.spi.EmbeddableInstantiator; import org.hibernate.metamodel.spi.EmbeddableRepresentationStrategy; import org.hibernate.property.access.spi.PropertyAccess; -import org.hibernate.property.access.spi.PropertyAccessStrategy; import org.hibernate.type.descriptor.java.JavaType; import static org.hibernate.internal.util.ReflectHelper.isRecord; @@ -33,21 +32,15 @@ public IdClassRepresentationStrategy( IdClassEmbeddable idClassEmbeddable, boolean simplePropertyOrder, Supplier attributeNamesAccess) { - this.idClassType = idClassEmbeddable.getMappedJavaType(); - final Class javaTypeClass = idClassType.getJavaTypeClass(); + idClassType = idClassEmbeddable.getMappedJavaType(); + final var javaTypeClass = idClassType.getJavaTypeClass(); if ( isRecord( javaTypeClass ) ) { - if ( simplePropertyOrder ) { - this.instantiator = new EmbeddableInstantiatorRecordStandard( javaTypeClass ); - } - else { - this.instantiator = EmbeddableInstantiatorRecordIndirecting.of( - javaTypeClass, - attributeNamesAccess.get() - ); - } + instantiator = simplePropertyOrder + ? new EmbeddableInstantiatorRecordStandard( javaTypeClass ) + : EmbeddableInstantiatorRecordIndirecting.of( javaTypeClass, attributeNamesAccess.get() ); } else { - this.instantiator = new EmbeddableInstantiatorPojoStandard( + instantiator = new EmbeddableInstantiatorPojoStandard( idClassType.getJavaTypeClass(), () -> idClassEmbeddable ); @@ -76,7 +69,7 @@ public JavaType getMappedJavaType() { @Override public PropertyAccess resolvePropertyAccess(Property bootAttributeDescriptor) { - final PropertyAccessStrategy strategy = bootAttributeDescriptor.getPropertyAccessStrategy( idClassType.getJavaTypeClass() ); + final var strategy = bootAttributeDescriptor.getPropertyAccessStrategy( idClassType.getJavaTypeClass() ); if ( strategy == null ) { throw new HibernateException( diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ImmutableAttributeMappingList.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ImmutableAttributeMappingList.java index 494d99cc0e97..8f83b8c25552 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ImmutableAttributeMappingList.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ImmutableAttributeMappingList.java @@ -37,8 +37,8 @@ public AttributeMapping get(final int i) { @Override public void forEach(Consumer attributeMappingConsumer) { - for ( AttributeMapping o : list ) { - attributeMappingConsumer.accept( o ); + for ( var attributeMapping : list ) { + attributeMappingConsumer.accept( attributeMapping ); } } @@ -83,7 +83,7 @@ public AttributeMappingsList build() { public boolean assertFetchableIndexes() { for ( int i = 0; i < builderList.size(); i++ ) { - final AttributeMapping attributeMapping = builderList.get( i ); + final var attributeMapping = builderList.get( i ); assert i == attributeMapping.getFetchableKey(); } return true; diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ImmutableAttributeMappingsMap.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ImmutableAttributeMappingsMap.java index d57578a4df3b..0638d9c81d26 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ImmutableAttributeMappingsMap.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ImmutableAttributeMappingsMap.java @@ -7,7 +7,6 @@ import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; -import java.util.Map; import java.util.function.Consumer; import org.hibernate.metamodel.mapping.AttributeMapping; @@ -27,11 +26,11 @@ public final class ImmutableAttributeMappingsMap implements AttributeMappingsMap public ImmutableAttributeMappingsMap(final LinkedHashMap sortedSource) { final int size = sortedSource.size(); - this.orderedValues = new AttributeMapping[size]; - this.mapStore = new HashMap<>( size ); + orderedValues = new AttributeMapping[size]; + mapStore = new HashMap<>( size ); int idx = 0; //populate both parallel representations - for ( Map.Entry entry : sortedSource.entrySet() ) { + for ( var entry : sortedSource.entrySet() ) { orderedValues[idx] = entry.getValue(); mapStore.put( entry.getKey(), Integer.valueOf( idx ) ); idx++; @@ -40,8 +39,8 @@ public ImmutableAttributeMappingsMap(final LinkedHashMap action) { - for ( AttributeMapping o : orderedValues ) { - action.accept( o ); + for ( var attributeMapping : orderedValues ) { + action.accept( attributeMapping ); } } @@ -51,14 +50,8 @@ public int size() { @Override public AttributeMapping get(final String name) { - final Object o = this.mapStore.get( name ); - if ( o == null ) { - return null; - } - else { - Integer integer = (Integer) o; - return orderedValues[integer.intValue()]; - } + final Integer integer = mapStore.get( name ); + return integer == null ? null : orderedValues[integer]; } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/InverseNonAggregatedIdentifierMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/InverseNonAggregatedIdentifierMapping.java index 9de0aec53b06..bacbb5384744 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/InverseNonAggregatedIdentifierMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/InverseNonAggregatedIdentifierMapping.java @@ -8,38 +8,31 @@ import java.util.function.BiConsumer; import org.hibernate.cache.MutableCacheKeyBuilder; -import org.hibernate.engine.spi.EntityHolder; -import org.hibernate.engine.spi.EntityKey; -import org.hibernate.engine.spi.PersistenceContext; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.event.spi.MergeContext; -import org.hibernate.internal.util.collections.CollectionHelper; -import org.hibernate.metamodel.mapping.AttributeMapping; import org.hibernate.metamodel.mapping.EmbeddableMappingType; import org.hibernate.metamodel.mapping.EntityIdentifierMapping; import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.metamodel.mapping.JdbcMapping; import org.hibernate.metamodel.mapping.ManagedMappingType; -import org.hibernate.metamodel.mapping.ModelPart; import org.hibernate.metamodel.mapping.NonAggregatedIdentifierMapping; import org.hibernate.metamodel.mapping.SelectableMappings; -import org.hibernate.persister.entity.EntityPersister; import org.hibernate.query.sqm.sql.SqmToSqlAstConverter; import org.hibernate.spi.NavigablePath; import org.hibernate.sql.ast.Clause; import org.hibernate.sql.ast.spi.SqlAstCreationState; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.expression.ColumnReference; -import org.hibernate.sql.ast.tree.expression.Expression; import org.hibernate.sql.ast.tree.expression.SqlTuple; import org.hibernate.sql.ast.tree.from.TableGroup; import org.hibernate.sql.ast.tree.from.TableGroupProducer; -import org.hibernate.sql.ast.tree.from.TableReference; import org.hibernate.sql.results.graph.DomainResultCreationState; import org.hibernate.sql.results.graph.Fetchable; import org.checkerframework.checker.nullness.qual.Nullable; +import static org.hibernate.internal.util.collections.CollectionHelper.arrayList; + /** * The inverse part of a "non-aggregated" composite identifier. * @@ -68,19 +61,23 @@ public class InverseNonAggregatedIdentifierMapping extends EmbeddedAttributeMapp creationProcess ); - this.entityDescriptor = inverseModelPart.findContainingEntityMapping(); + entityDescriptor = inverseModelPart.findContainingEntityMapping(); if ( inverseModelPart.getIdClassEmbeddable() == null ) { - this.idClassEmbeddable = null; - this.identifierValueMapper = (NonAggregatedIdentifierMapping.IdentifierValueMapper) super.getEmbeddableTypeDescriptor(); + idClassEmbeddable = null; + identifierValueMapper = + (NonAggregatedIdentifierMapping.IdentifierValueMapper) + super.getEmbeddableTypeDescriptor(); } else { - this.idClassEmbeddable = (IdClassEmbeddable) inverseModelPart.getIdClassEmbeddable().createInverseMappingType( - this, - declaringTableGroupProducer, - selectableMappings, - creationProcess - ); + idClassEmbeddable = + (IdClassEmbeddable) + inverseModelPart.getIdClassEmbeddable().createInverseMappingType( + this, + declaringTableGroupProducer, + selectableMappings, + creationProcess + ); identifierValueMapper = idClassEmbeddable; } } @@ -164,26 +161,22 @@ public SqlTuple toSqlExpression( SqmToSqlAstConverter walker, SqlAstCreationState sqlAstCreationState) { if ( hasContainingClass() ) { - final SelectableMappings selectableMappings = getEmbeddableTypeDescriptor(); - final List columnReferences = CollectionHelper.arrayList( selectableMappings.getJdbcTypeCount() ); - final NavigablePath navigablePath = tableGroup.getNavigablePath() - .append( getNavigableRole().getNavigableName() ); - final TableReference defaultTableReference = tableGroup.resolveTableReference( - navigablePath, - getContainingTableExpression() - ); + final var selectableMappings = getEmbeddableTypeDescriptor(); + final List columnReferences = arrayList( selectableMappings.getJdbcTypeCount() ); + final var navigablePath = tableGroup.getNavigablePath().append( getNavigableRole().getNavigableName() ); + final var defaultTableReference = + tableGroup.resolveTableReference( navigablePath, getContainingTableExpression() ); identifierValueMapper.forEachSelectable( 0, (columnIndex, selection) -> { - final TableReference tableReference = defaultTableReference.resolveTableReference( selection.getContainingTableExpression() ) != null - ? defaultTableReference - : tableGroup.resolveTableReference( - navigablePath, - selection.getContainingTableExpression() - ); - final Expression columnReference = sqlAstCreationState.getSqlExpressionResolver() - .resolveSqlExpression( tableReference, selection ); - + final var tableReference = + defaultTableReference.resolveTableReference( selection.getContainingTableExpression() ) != null + ? defaultTableReference + : tableGroup.resolveTableReference( navigablePath, + selection.getContainingTableExpression() ); + final var columnReference = + sqlAstCreationState.getSqlExpressionResolver() + .resolveSqlExpression( tableReference, selection ); columnReferences.add( (ColumnReference) columnReference ); } ); @@ -202,37 +195,36 @@ public Object getIdentifier(Object entity) { public Object getIdentifier(Object entity, MergeContext mergeContext) { if ( hasContainingClass() ) { final Object id = identifierValueMapper.getRepresentationStrategy().getInstantiator().instantiate( null ); - final EmbeddableMappingType embeddableTypeDescriptor = getEmbeddableTypeDescriptor(); + final var embeddableTypeDescriptor = getEmbeddableTypeDescriptor(); final Object[] propertyValues = new Object[embeddableTypeDescriptor.getNumberOfAttributeMappings()]; for ( int i = 0; i < propertyValues.length; i++ ) { - final AttributeMapping attributeMapping = embeddableTypeDescriptor.getAttributeMapping( i ); - final Object o = attributeMapping.getValue( entity ); - if ( o == null ) { - final AttributeMapping idClassAttributeMapping = identifierValueMapper.getAttributeMapping( i ); - if ( idClassAttributeMapping.getPropertyAccess().getGetter().getReturnTypeClass().isPrimitive() ) { - propertyValues[i] = idClassAttributeMapping.getExpressibleJavaType().getDefaultValue(); - } - else { - propertyValues[i] = null; - } + final var attributeMapping = embeddableTypeDescriptor.getAttributeMapping( i ); + final Object object = attributeMapping.getValue( entity ); + if ( object == null ) { + final var idClassAttributeMapping = identifierValueMapper.getAttributeMapping( i ); + propertyValues[i] = + idClassAttributeMapping.getPropertyAccess().getGetter().getReturnTypeClass().isPrimitive() + ? idClassAttributeMapping.getExpressibleJavaType().getDefaultValue() + : null; } //JPA 2 @MapsId + @IdClass points to the pk of the entity else if ( attributeMapping instanceof ToOneAttributeMapping toOneAttributeMapping && !( identifierValueMapper.getAttributeMapping( i ) instanceof ToOneAttributeMapping ) ) { - final Object toOne = getIfMerged( o, mergeContext ); - final ModelPart targetPart = toOneAttributeMapping.getForeignKeyDescriptor().getPart( - toOneAttributeMapping.getSideNature().inverse() - ); + final Object toOne = getIfMerged( object, mergeContext ); + final var targetPart = + toOneAttributeMapping.getForeignKeyDescriptor() + .getPart( toOneAttributeMapping.getSideNature().inverse() ); if ( targetPart.isEntityIdentifierMapping() ) { - propertyValues[i] = ( (EntityIdentifierMapping) targetPart ) - .getIdentifier( toOne, mergeContext ); + propertyValues[i] = + ( (EntityIdentifierMapping) targetPart ) + .getIdentifier( toOne, mergeContext ); } else { propertyValues[i] = toOne; } } else { - propertyValues[i] = o; + propertyValues[i] = object; } } identifierValueMapper.setValues( id, propertyValues ); @@ -256,26 +248,26 @@ private static Object getIfMerged(Object o, MergeContext mergeContext) { @Override public void setIdentifier(Object entity, Object id, SharedSessionContractImplementor session) { final Object[] propertyValues = new Object[identifierValueMapper.getNumberOfAttributeMappings()]; - final EmbeddableMappingType embeddableTypeDescriptor = getEmbeddableTypeDescriptor(); + final var embeddableTypeDescriptor = getEmbeddableTypeDescriptor(); for ( int position = 0; position < propertyValues.length; position++ ) { - final AttributeMapping attribute = embeddableTypeDescriptor.getAttributeMapping( position ); - final AttributeMapping mappedIdAttributeMapping = identifierValueMapper.getAttributeMapping( position ); - Object o = mappedIdAttributeMapping.getValue( id ); + final var attribute = embeddableTypeDescriptor.getAttributeMapping( position ); + final var mappedIdAttributeMapping = identifierValueMapper.getAttributeMapping( position ); + Object object = mappedIdAttributeMapping.getValue( id ); if ( attribute instanceof ToOneAttributeMapping toOneAttributeMapping && !( mappedIdAttributeMapping instanceof ToOneAttributeMapping ) ) { - final EntityPersister entityPersister = + final var entityPersister = toOneAttributeMapping.getEntityMappingType().getEntityPersister(); - final EntityKey entityKey = session.generateEntityKey( o, entityPersister ); - final PersistenceContext persistenceContext = session.getPersistenceContext(); - final EntityHolder holder = persistenceContext.getEntityHolder( entityKey ); + final var entityKey = session.generateEntityKey( object, entityPersister ); + final var persistenceContext = session.getPersistenceContext(); + final var holder = persistenceContext.getEntityHolder( entityKey ); // use the managed object i.e. proxy or initialized entity - o = holder == null ? null : holder.getManagedObject(); - if ( o == null ) { - o = entityDescriptor.findAttributeMapping( toOneAttributeMapping.getAttributeName() ) + object = holder == null ? null : holder.getManagedObject(); + if ( object == null ) { + object = entityDescriptor.findAttributeMapping( toOneAttributeMapping.getAttributeName() ) .getValue( entity ); } } - propertyValues[position] = o; + propertyValues[position] = object; } embeddableTypeDescriptor.setValues( entity, propertyValues ); } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ManyToManyCollectionPart.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ManyToManyCollectionPart.java index a0403f518e67..6de2d203f13d 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ManyToManyCollectionPart.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ManyToManyCollectionPart.java @@ -11,7 +11,6 @@ import org.hibernate.annotations.NotFoundAction; import org.hibernate.dialect.Dialect; import org.hibernate.engine.spi.SharedSessionContractImplementor; -import org.hibernate.internal.util.StringHelper; import org.hibernate.mapping.Collection; import org.hibernate.mapping.Column; import org.hibernate.mapping.IndexedCollection; @@ -20,7 +19,6 @@ import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.Value; import org.hibernate.metamodel.mapping.AssociationKey; -import org.hibernate.metamodel.mapping.AttributeMapping; import org.hibernate.metamodel.mapping.BasicEntityIdentifierMapping; import org.hibernate.metamodel.mapping.BasicValuedModelPart; import org.hibernate.metamodel.mapping.CompositeIdentifierMapping; @@ -30,12 +28,10 @@ import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.metamodel.mapping.ForeignKeyDescriptor; import org.hibernate.metamodel.mapping.JdbcMapping; -import org.hibernate.metamodel.mapping.ManagedMappingType; import org.hibernate.metamodel.mapping.ModelPart; import org.hibernate.metamodel.mapping.PluralAttributeMapping; import org.hibernate.metamodel.mapping.SelectableConsumer; import org.hibernate.metamodel.mapping.SelectableMapping; -import org.hibernate.metamodel.mapping.SelectableMappings; import org.hibernate.metamodel.mapping.ValuedModelPart; import org.hibernate.metamodel.mapping.VirtualModelPart; import org.hibernate.persister.collection.CollectionPersister; @@ -48,13 +44,13 @@ import org.hibernate.sql.ast.tree.from.TableGroup; import org.hibernate.sql.ast.tree.from.TableGroupJoin; import org.hibernate.sql.ast.tree.from.TableGroupProducer; -import org.hibernate.sql.ast.tree.from.TableReference; import org.hibernate.sql.ast.tree.predicate.Predicate; import org.hibernate.type.EntityType; import org.checkerframework.checker.nullness.qual.Nullable; import static java.util.Objects.requireNonNullElse; +import static org.hibernate.internal.util.StringHelper.isNotEmpty; import static org.hibernate.metamodel.mapping.internal.MappingModelCreationHelper.createInverseModelPart; import static org.hibernate.metamodel.mapping.internal.MappingModelCreationHelper.getPropertyOrder; @@ -124,7 +120,7 @@ public ModelPart findSubPart(String name, EntityMappingType targetType) { // This is not possible for one-to-many associations because we need to create the target table group eagerly, // to preserve the cardinality. Also, the OneToManyTableGroup has no reference to the parent table group if ( foreignKey != null && getTargetKeyPropertyNames().contains( name ) ) { - final ModelPart keyPart = foreignKey.getKeyPart(); + final var keyPart = foreignKey.getKeyPart(); return keyPart instanceof EmbeddableValuedModelPart embeddableValuedModelPart && keyPart instanceof VirtualModelPart ? embeddableValuedModelPart.findSubPart( name, targetType ) @@ -258,8 +254,8 @@ public TableGroupJoin createTableGroupJoin( boolean fetched, boolean addsPredicate, SqlAstCreationState creationState) { - final SqlAstJoinType joinType = requireNonNullElse( requestedJoinType, SqlAstJoinType.INNER ); - final LazyTableGroup lazyTableGroup = createRootTableGroupJoin( + final var joinType = requireNonNullElse( requestedJoinType, SqlAstJoinType.INNER ); + final var lazyTableGroup = createRootTableGroupJoin( navigablePath, lhs, explicitSourceAlias, @@ -270,7 +266,7 @@ public TableGroupJoin createTableGroupJoin( creationState ); - final TableGroupJoin join = new TableGroupJoin( + final var join = new TableGroupJoin( navigablePath, joinType, lazyTableGroup, @@ -301,16 +297,16 @@ public LazyTableGroup createRootTableGroupJoin( boolean fetched, @Nullable Consumer predicateConsumer, SqlAstCreationState creationState) { - final SqlAstJoinType joinType = requireNonNullElse( requestedJoinType, SqlAstJoinType.INNER ); + final var joinType = requireNonNullElse( requestedJoinType, SqlAstJoinType.INNER ); final boolean canUseInnerJoin = joinType == SqlAstJoinType.INNER || lhs.canUseInnerJoins(); - final SqlAliasBase sqlAliasBase = SqlAliasBase.from( + final var sqlAliasBase = SqlAliasBase.from( explicitSqlAliasBase, explicitSourceAlias, this, creationState.getSqlAliasBaseGenerator() ); - final LazyTableGroup lazyTableGroup = new LazyTableGroup( + final var lazyTableGroup = new LazyTableGroup( canUseInnerJoin, navigablePath, fetched, @@ -331,11 +327,8 @@ public LazyTableGroup createRootTableGroupJoin( ); if ( predicateConsumer != null ) { - final TableReference keySideTableReference = lhs.resolveTableReference( - navigablePath, - foreignKey.getKeyTable() - ); - + final var keySideTableReference = + lhs.resolveTableReference( navigablePath, foreignKey.getKeyTable() ); lazyTableGroup.setTableGroupInitializerCallback( tableGroup -> predicateConsumer.accept( foreignKey.generateJoinPredicate( @@ -372,17 +365,18 @@ public boolean finishInitialization( MappingModelCreationProcess creationProcess) { if ( fkTargetModelPartName != null ) { // @OneToMany + @JoinTable w/ @JoinColumn( referencedColumnName="fkTargetModelPartName" ) - fkTargetModelPart = resolveNamedTargetPart( fkTargetModelPartName, getAssociatedEntityMappingType(), collectionDescriptor ); + fkTargetModelPart = + resolveNamedTargetPart( fkTargetModelPartName, getAssociatedEntityMappingType(), collectionDescriptor ); } else if ( getNature() == Nature.INDEX ) { assert bootCollectionDescriptor.isIndexed(); - final PluralAttributeMapping pluralAttribute = collectionDescriptor.getAttributeMapping(); + final var pluralAttribute = collectionDescriptor.getAttributeMapping(); final String mapKeyPropertyName = ( (Map) bootCollectionDescriptor ).getMapKeyPropertyName(); - if ( StringHelper.isNotEmpty( mapKeyPropertyName ) ) { + if ( isNotEmpty( mapKeyPropertyName ) ) { // @MapKey( name="fkTargetModelPartName" ) - final EntityCollectionPart elementDescriptor = (EntityCollectionPart) pluralAttribute.getElementDescriptor(); - final EntityMappingType entityMappingType = elementDescriptor.getEntityMappingType(); + final var elementDescriptor = (EntityCollectionPart) pluralAttribute.getElementDescriptor(); + final var entityMappingType = elementDescriptor.getEntityMappingType(); fkTargetModelPart = resolveNamedTargetPart( mapKeyPropertyName, entityMappingType, collectionDescriptor ); } else { @@ -390,8 +384,8 @@ else if ( getNature() == Nature.INDEX ) { // fkTargetModelPart = getAssociatedEntityMappingType().getIdentifierMapping(); } } - else if ( StringHelper.isNotEmpty( bootCollectionDescriptor.getMappedByProperty() ) ) { - final ModelPart mappedByPart = + else if ( isNotEmpty( bootCollectionDescriptor.getMappedByProperty() ) ) { + final var mappedByPart = resolveNamedTargetPart( bootCollectionDescriptor.getMappedByProperty(), getAssociatedEntityMappingType(), collectionDescriptor ); if ( mappedByPart instanceof ToOneAttributeMapping @@ -419,7 +413,7 @@ else if ( StringHelper.isNotEmpty( bootCollectionDescriptor.getMappedByProperty( // create the foreign-key from the join-table (author_book) to the part table (Book) : // `author_book.book_id -> Book.id` - final ManyToOne elementDescriptor = (ManyToOne) bootCollectionDescriptor.getElement(); + final var elementDescriptor = (ManyToOne) bootCollectionDescriptor.getElement(); assert elementDescriptor.isReferenceToPrimaryKey(); final String collectionTableName = collectionDescriptor.getTableName(); @@ -433,7 +427,7 @@ else if ( StringHelper.isNotEmpty( bootCollectionDescriptor.getMappedByProperty( creationProcess.registerForeignKey( this, foreignKey ); } else { - final PluralAttributeMapping manyToManyInverse = (PluralAttributeMapping) mappedByPart; + final var manyToManyInverse = (PluralAttributeMapping) mappedByPart; if ( manyToManyInverse.getKeyDescriptor() == null ) { // the collection-key is not yet ready, we need to wait return false; @@ -479,8 +473,8 @@ private ForeignKeyDescriptor createJoinTablePartForeignKey( String collectionTableName, ManyToOne elementBootDescriptor, MappingModelCreationProcess creationProcess) { - final EntityMappingType associatedEntityMapping = getAssociatedEntityMappingType(); - final EntityIdentifierMapping associatedIdMapping = associatedEntityMapping.getIdentifierMapping(); + final var associatedEntityMapping = getAssociatedEntityMappingType(); + final var associatedIdMapping = associatedEntityMapping.getIdentifierMapping(); assert associatedIdMapping != null; // NOTE : `elementBootDescriptor` describes the key side of the fk @@ -490,12 +484,12 @@ private ForeignKeyDescriptor createJoinTablePartForeignKey( // and need to create the inverse (key) selectable-mappings and composite model-part if ( associatedIdMapping.getNature() == EntityIdentifierMapping.Nature.SIMPLE ) { - final BasicEntityIdentifierMapping targetModelPart = (BasicEntityIdentifierMapping) associatedIdMapping; + final var targetModelPart = (BasicEntityIdentifierMapping) associatedIdMapping; assert elementBootDescriptor.getColumns().size() == 1; final Column keyColumn = elementBootDescriptor.getColumns().get( 0 ); - final SelectableMapping keySelectableMapping = SelectableMappingImpl.from( + final var keySelectableMapping = SelectableMappingImpl.from( collectionTableName, keyColumn, targetModelPart.getJdbcMapping(), @@ -508,7 +502,7 @@ private ForeignKeyDescriptor createJoinTablePartForeignKey( creationProcess.getCreationContext() ); - final BasicAttributeMapping keyModelPart = BasicAttributeMapping.withSelectableMapping( + final var keyModelPart = BasicAttributeMapping.withSelectableMapping( associatedEntityMapping, targetModelPart, targetModelPart.getPropertyAccess(), @@ -530,9 +524,9 @@ private ForeignKeyDescriptor createJoinTablePartForeignKey( ); } else { - final CompositeIdentifierMapping targetModelPart = (CompositeIdentifierMapping) associatedIdMapping; + final var targetModelPart = (CompositeIdentifierMapping) associatedIdMapping; - final SelectableMappings keySelectableMappings = SelectableMappingsImpl.from( + final var keySelectableMappings = SelectableMappingsImpl.from( collectionTableName, elementBootDescriptor, getPropertyOrder( elementBootDescriptor, creationProcess ), @@ -568,7 +562,7 @@ private static ValuedModelPart resolveNamedTargetPart( String targetPartName, EntityMappingType entityMappingType, CollectionPersister collectionDescriptor) { - final ModelPart namedPart = entityMappingType.findByPath( targetPartName ); + final var namedPart = entityMappingType.findByPath( targetPartName ); if ( namedPart == null ) { // This is expected to happen when processing a // PostInitCallbackEntry because the callbacks @@ -624,7 +618,7 @@ private ForeignKeyDescriptor createForeignKeyDescriptor( ( (CollectionMutationTarget) getCollectionDescriptor() ) .getCollectionTableMapping().getTableName(); - final BasicValuedModelPart basicFkTarget = fkTargetModelPart.asBasicValuedModelPart(); + final var basicFkTarget = fkTargetModelPart.asBasicValuedModelPart(); if ( basicFkTarget != null ) { return createSimpleForeignKeyDescriptor( fkBootDescriptorSource, @@ -660,15 +654,15 @@ private ForeignKeyDescriptor determineForeignKey( Value fkBootDescriptorSource, MappingModelCreationProcess creationProcess) { final int selectableCount = foreignKeyDescriptor.getJdbcTypeCount(); - final ValuedModelPart keyPart = foreignKeyDescriptor.getKeyPart(); + final var keyPart = foreignKeyDescriptor.getKeyPart(); for ( int i = 0; i < selectableCount; i++ ) { - final SelectableMapping selectable = keyPart.getSelectable( i ); + final var selectable = keyPart.getSelectable( i ); if ( selectable.isInsertable() != fkBootDescriptorSource.isColumnInsertable( i ) || selectable.isUpdateable() != fkBootDescriptorSource.isColumnUpdateable( i ) ) { - final AttributeMapping attributeMapping = keyPart.asAttributeMapping(); - final ManagedMappingType declaringType = + final var attributeMapping = keyPart.asAttributeMapping(); + final var declaringType = attributeMapping == null ? null : attributeMapping.getDeclaringType(); - final SelectableMappings selectableMappings = SelectableMappingsImpl.from( + final var selectableMappings = SelectableMappingsImpl.from( keyPart.getContainingTableExpression(), fkBootDescriptorSource, getPropertyOrder( fkBootDescriptorSource, creationProcess ), @@ -710,8 +704,8 @@ private SimpleForeignKeyDescriptor createSimpleForeignKeyDescriptor( columnInsertable = fkBootDescriptorSource.isColumnInsertable( 0 ); columnUpdateable = fkBootDescriptorSource.isColumnUpdateable( 0 ); } - final SimpleValue fkValue = (SimpleValue) fkBootDescriptorSource; - final SelectableMapping keySelectableMapping = SelectableMappingImpl.from( + final var fkValue = (SimpleValue) fkBootDescriptorSource; + final var keySelectableMapping = SelectableMappingImpl.from( fkKeyTableName, fkBootDescriptorSource.getSelectables().get( 0 ), basicFkTargetPart.getJdbcMapping(), diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java index 6cf1d4f71107..212fe6538e8d 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelCreationHelper.java @@ -281,8 +281,9 @@ public static BasicAttributeMapping buildBasicAttributeMapping( final FetchTiming fetchTiming; final FetchStyle fetchStyle; final boolean partitioned; + boolean lazy = bootProperty.isLazy(); if ( declaringType instanceof EmbeddableMappingType embeddableMappingType ) { - if ( bootProperty.isLazy() ) { + if ( lazy) { MAPPING_MODEL_CREATION_MESSAGE_LOGGER.debugf( "Attribute was declared LAZY, but is part of embeddable '%s#%s', LAZY ignored", declaringType.getNavigableRole().getFullPath(), @@ -295,8 +296,8 @@ public static BasicAttributeMapping buildBasicAttributeMapping( && !embeddableMappingType.getEmbeddedValueMapping().isVirtual(); } else { - fetchTiming = bootProperty.isLazy() ? FetchTiming.DELAYED : FetchTiming.IMMEDIATE; - fetchStyle = bootProperty.isLazy() ? FetchStyle.SELECT : FetchStyle.JOIN; + fetchTiming = lazy ? FetchTiming.DELAYED : FetchTiming.IMMEDIATE; + fetchStyle = lazy ? FetchStyle.SELECT : FetchStyle.JOIN; partitioned = value.isPartitionKey(); } @@ -907,7 +908,7 @@ public static boolean interpretToOneKeyDescriptor( attributeMapping.setIdentifyingColumnsTableExpression( tableName ); - final EntityPersister referencedEntityDescriptor = + final var referencedEntityDescriptor = creationProcess.getEntityPersister( bootValueMapping.getReferencedEntityName() ); String referencedPropertyName; @@ -1054,8 +1055,8 @@ else if ( modelPart instanceof EmbeddableValuedModelPart embeddableValuedModelPa creationProcess.registerForeignKey( attributeMapping, foreignKeyDescriptor ); } else if ( fkTarget instanceof EmbeddableValuedModelPart embeddableValuedModelPart ) { - final Value value = bootProperty.getValue(); - final EmbeddedForeignKeyDescriptor embeddedForeignKeyDescriptor = buildEmbeddableForeignKeyDescriptor( + final var value = bootProperty.getValue(); + final var embeddedForeignKeyDescriptor = buildEmbeddableForeignKeyDescriptor( embeddableValuedModelPart, bootValueMapping, attributeMapping.getDeclaringType(), @@ -1169,7 +1170,8 @@ private static EmbeddedForeignKeyDescriptor buildEmbeddableForeignKeyDescriptor( final boolean hasConstraint; final SelectableMappings keySelectableMappings; if ( bootValueMapping instanceof Collection collectionBootValueMapping ) { - hasConstraint = ((SimpleValue) collectionBootValueMapping.getKey()).isConstrained(); + final var key = (SimpleValue) collectionBootValueMapping.getKey(); + hasConstraint = key.isConstrained(); keyTableExpression = keyTableExpression != null ? keyTableExpression : getTableIdentifierExpression( collectionBootValueMapping.getCollectionTable(), creationProcess ); @@ -1377,7 +1379,8 @@ private static CollectionPart interpretMapKey( updatable = false; } else { - insertable = updatable = basicValue.isColumnInsertable( 0 ) + insertable = updatable = + basicValue.isColumnInsertable( 0 ) || basicValue.isColumnUpdateable( 0 ); } final var selectableMapping = SelectableMappingImpl.from( @@ -1527,8 +1530,8 @@ private static CollectionPart interpretElement( } if ( element instanceof OneToMany || element instanceof ToOne ) { - final EntityType elementEntityType = (EntityType) collectionDescriptor.getElementType(); - final EntityPersister associatedEntity = + final var elementEntityType = (EntityType) collectionDescriptor.getElementType(); + final var associatedEntity = creationProcess.getEntityPersister( elementEntityType.getAssociatedEntityName() ); final EntityCollectionPart elementDescriptor; @@ -1888,47 +1891,18 @@ public static ToOneAttributeMapping buildSingularAssociationAttributeMapping( cascadeStyle, creationProcess ); - final var sessionFactory = creationProcess.getCreationContext().getSessionFactory(); + final var factory = creationProcess.getCreationContext().getSessionFactory(); final var type = (AssociationType) bootProperty.getType(); - final FetchStyle fetchStyle = FetchOptionsHelper - .determineFetchStyleByMetadata( + final var fetchStyle = + FetchOptionsHelper.determineFetchStyleByMetadata( bootProperty.getValue().getFetchMode(), type, - sessionFactory + factory ); - final FetchTiming fetchTiming; - final String role = declaringType.getNavigableRole().toString() + "." + bootProperty.getName(); - final boolean lazy = value.isLazy(); - if ( lazy && entityPersister.getBytecodeEnhancementMetadata().isEnhancedForLazyLoading() ) { - if ( value.isUnwrapProxy() ) { - fetchTiming = determineFetchTiming( fetchStyle, type, lazy, role, sessionFactory ); - } - else if ( value instanceof ManyToOne manyToOne && value.isNullable() && manyToOne.isIgnoreNotFound() ) { - fetchTiming = FetchTiming.IMMEDIATE; - } - else { - fetchTiming = determineFetchTiming( fetchStyle, type, lazy, role, sessionFactory ); - } - } - else if ( !lazy - || value instanceof OneToOne && value.isNullable() - || value instanceof ManyToOne manyToOne && value.isNullable() && manyToOne.isIgnoreNotFound() ) { - fetchTiming = FetchTiming.IMMEDIATE; - if ( lazy ) { - if ( MAPPING_MODEL_CREATION_MESSAGE_LOGGER.isTraceEnabled() ) { - MAPPING_MODEL_CREATION_MESSAGE_LOGGER.tracef( - "Forcing FetchTiming.IMMEDIATE for to-one association: %s.%s", - declaringType.getNavigableRole(), - bootProperty.getName() - ); - } - } - } - else { - fetchTiming = determineFetchTiming( fetchStyle, type, lazy, role, sessionFactory ); - } + final var fetchTiming = + fetchTiming( bootProperty, declaringType, value, entityPersister, fetchStyle, type, factory ); final var attributeMapping = mappingConverter.apply( new ToOneAttributeMapping( attrName, @@ -1962,4 +1936,37 @@ else if ( !lazy throw new UnsupportedOperationException( "AnyType support has not yet been implemented" ); } } + + private static FetchTiming fetchTiming(Property bootProperty, ManagedMappingType declaringType, ToOne value, EntityPersister entityPersister, FetchStyle fetchStyle, AssociationType type, SessionFactoryImplementor sessionFactory) { + final String role = declaringType.getNavigableRole().toString() + "." + bootProperty.getName(); + final boolean lazy = value.isLazy(); + if ( lazy && entityPersister.getBytecodeEnhancementMetadata().isEnhancedForLazyLoading() ) { + if ( value.isUnwrapProxy() ) { + return determineFetchTiming( fetchStyle, type, lazy, role, sessionFactory ); + } + else if ( value instanceof ManyToOne manyToOne && value.isNullable() && manyToOne.isIgnoreNotFound() ) { + return FetchTiming.IMMEDIATE; + } + else { + return determineFetchTiming( fetchStyle, type, lazy, role, sessionFactory ); + } + } + else if ( !lazy + || value instanceof OneToOne && value.isNullable() + || value instanceof ManyToOne manyToOne && value.isNullable() && manyToOne.isIgnoreNotFound() ) { + if ( lazy ) { + if ( MAPPING_MODEL_CREATION_MESSAGE_LOGGER.isTraceEnabled() ) { + MAPPING_MODEL_CREATION_MESSAGE_LOGGER.tracef( + "Forcing FetchTiming.IMMEDIATE for to-one association: %s.%s", + declaringType.getNavigableRole(), + bootProperty.getName() + ); + } + } + return FetchTiming.IMMEDIATE; + } + else { + return determineFetchTiming( fetchStyle, type, lazy, role, sessionFactory ); + } + } } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelHelper.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelHelper.java index 2df06ba58bde..8bc7fae80ca5 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/MappingModelHelper.java @@ -5,9 +5,6 @@ package org.hibernate.metamodel.mapping.internal; import org.hibernate.metamodel.mapping.Association; -import org.hibernate.metamodel.mapping.BasicValuedModelPart; -import org.hibernate.metamodel.mapping.CollectionPart; -import org.hibernate.metamodel.mapping.EmbeddableMappingType; import org.hibernate.metamodel.mapping.EmbeddableValuedModelPart; import org.hibernate.metamodel.mapping.ModelPart; import org.hibernate.metamodel.mapping.PluralAttributeMapping; @@ -104,26 +101,26 @@ public static boolean isCompatibleModelPart(ModelPart attribute1, ModelPart attr return false; } if ( attribute1 instanceof Association association1 ) { - final Association association2 = (Association) attribute2; + final var association2 = (Association) attribute2; return association1.getForeignKeyDescriptor().getAssociationKey().equals( association2.getForeignKeyDescriptor().getAssociationKey() ); } else if ( attribute1 instanceof PluralAttributeMapping plural1 ) { - final PluralAttributeMapping plural2 = (PluralAttributeMapping) attribute2; - final CollectionPart element1 = plural1.getElementDescriptor(); - final CollectionPart element2 = plural2.getElementDescriptor(); - final CollectionPart index1 = plural1.getIndexDescriptor(); - final CollectionPart index2 = plural2.getIndexDescriptor(); - return plural1.getKeyDescriptor().getAssociationKey().equals( - plural2.getKeyDescriptor().getAssociationKey() - ) && ( index1 == null && index2 == null || isCompatibleModelPart( index1, index2 ) ) - && isCompatibleModelPart( element1, element2 ); + final var plural2 = (PluralAttributeMapping) attribute2; + final var element1 = plural1.getElementDescriptor(); + final var element2 = plural2.getElementDescriptor(); + final var index1 = plural1.getIndexDescriptor(); + final var index2 = plural2.getIndexDescriptor(); + return plural1.getKeyDescriptor().getAssociationKey() + .equals( plural2.getKeyDescriptor().getAssociationKey() ) + && ( index1 == null && index2 == null || isCompatibleModelPart( index1, index2 ) ) + && isCompatibleModelPart( element1, element2 ); } else if ( attribute1 instanceof EmbeddableValuedModelPart embedded1 ) { - final EmbeddableValuedModelPart embedded2 = (EmbeddableValuedModelPart) attribute2; - final EmbeddableMappingType embeddableTypeDescriptor1 = embedded1.getEmbeddableTypeDescriptor(); - final EmbeddableMappingType embeddableTypeDescriptor2 = embedded2.getEmbeddableTypeDescriptor(); + final var embedded2 = (EmbeddableValuedModelPart) attribute2; + final var embeddableTypeDescriptor1 = embedded1.getEmbeddableTypeDescriptor(); + final var embeddableTypeDescriptor2 = embedded2.getEmbeddableTypeDescriptor(); final int numberOfAttributeMappings = embeddableTypeDescriptor1.getNumberOfAttributeMappings(); if ( numberOfAttributeMappings != embeddableTypeDescriptor2.getNumberOfAttributeMappings() ) { return false; @@ -139,9 +136,9 @@ else if ( attribute1 instanceof EmbeddableValuedModelPart embedded1 ) { return true; } else { - final BasicValuedModelPart basic1 = attribute1.asBasicValuedModelPart(); + final var basic1 = attribute1.asBasicValuedModelPart(); if ( basic1 != null ) { - final BasicValuedModelPart basic2 = castNonNull( attribute2.asBasicValuedModelPart() ); + final var basic2 = castNonNull( attribute2.asBasicValuedModelPart() ); if ( !basic1.getSelectionExpression().equals( basic2.getSelectionExpression() ) ) { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/NonAggregatedIdentifierMappingImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/NonAggregatedIdentifierMappingImpl.java index c6e113f83786..5909d5f91611 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/NonAggregatedIdentifierMappingImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/NonAggregatedIdentifierMappingImpl.java @@ -9,35 +9,25 @@ import org.hibernate.cache.MutableCacheKeyBuilder; import org.hibernate.engine.FetchTiming; -import org.hibernate.engine.spi.EntityHolder; -import org.hibernate.engine.spi.EntityKey; -import org.hibernate.engine.spi.PersistenceContext; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.event.spi.MergeContext; -import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.mapping.Component; import org.hibernate.mapping.RootClass; import org.hibernate.metamodel.internal.AbstractCompositeIdentifierMapping; -import org.hibernate.metamodel.mapping.AttributeMapping; import org.hibernate.metamodel.mapping.EmbeddableMappingType; import org.hibernate.metamodel.mapping.EntityIdentifierMapping; import org.hibernate.metamodel.mapping.JdbcMapping; -import org.hibernate.metamodel.mapping.ModelPart; import org.hibernate.metamodel.mapping.NonAggregatedIdentifierMapping; -import org.hibernate.metamodel.mapping.SelectableMappings; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.proxy.HibernateProxy; -import org.hibernate.proxy.LazyInitializer; import org.hibernate.query.sqm.sql.SqmToSqlAstConverter; import org.hibernate.spi.NavigablePath; import org.hibernate.sql.ast.Clause; import org.hibernate.sql.ast.spi.SqlAstCreationState; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.expression.ColumnReference; -import org.hibernate.sql.ast.tree.expression.Expression; import org.hibernate.sql.ast.tree.expression.SqlTuple; import org.hibernate.sql.ast.tree.from.TableGroup; -import org.hibernate.sql.ast.tree.from.TableReference; import org.hibernate.sql.results.graph.DomainResult; import org.hibernate.sql.results.graph.DomainResultCreationState; import org.hibernate.sql.results.graph.Fetch; @@ -48,6 +38,8 @@ import org.checkerframework.checker.nullness.qual.Nullable; +import static org.hibernate.internal.util.collections.CollectionHelper.arrayList; + /** * A "non-aggregated" composite identifier. * @@ -93,8 +85,8 @@ public NonAggregatedIdentifierMappingImpl( else { // cid = getIdentifierMapper // idClass = getIdentifier - final Component virtualIdSource = bootEntityDescriptor.getIdentifierMapper(); - final Component idClassSource = (Component) bootEntityDescriptor.getIdentifier(); + final var virtualIdSource = bootEntityDescriptor.getIdentifierMapper(); + final var idClassSource = (Component) bootEntityDescriptor.getIdentifier(); virtualIdEmbeddable = new VirtualIdEmbeddable( virtualIdSource, @@ -195,26 +187,22 @@ public SqlTuple toSqlExpression( SqmToSqlAstConverter walker, SqlAstCreationState sqlAstCreationState) { if ( hasContainingClass() ) { - final SelectableMappings selectableMappings = getEmbeddableTypeDescriptor(); - final List columnReferences = CollectionHelper.arrayList( selectableMappings.getJdbcTypeCount() ); - final NavigablePath navigablePath = tableGroup.getNavigablePath() - .append( getNavigableRole().getNavigableName() ); - final TableReference defaultTableReference = tableGroup.resolveTableReference( - navigablePath, - getContainingTableExpression() - ); + final var selectableMappings = getEmbeddableTypeDescriptor(); + final List columnReferences = arrayList( selectableMappings.getJdbcTypeCount() ); + final var navigablePath = tableGroup.getNavigablePath().append( getNavigableRole().getNavigableName() ); + final var defaultTableReference = + tableGroup.resolveTableReference( navigablePath, getContainingTableExpression() ); identifierValueMapper.forEachSelectable( 0, (columnIndex, selection) -> { - final TableReference tableReference = defaultTableReference.resolveTableReference( selection.getContainingTableExpression() ) != null - ? defaultTableReference - : tableGroup.resolveTableReference( - navigablePath, - selection.getContainingTableExpression() - ); - final Expression columnReference = sqlAstCreationState.getSqlExpressionResolver() - .resolveSqlExpression( tableReference, selection ); - + final var tableReference = + defaultTableReference.resolveTableReference( selection.getContainingTableExpression() ) != null + ? defaultTableReference + : tableGroup.resolveTableReference( navigablePath, + selection.getContainingTableExpression() ); + final var columnReference = + sqlAstCreationState.getSqlExpressionResolver() + .resolveSqlExpression( tableReference, selection ); columnReferences.add( (ColumnReference) columnReference ); } ); @@ -242,29 +230,27 @@ public Object getIdentifier(Object entity) { @Override public Object getIdentifier(Object entity, MergeContext mergeContext) { if ( hasContainingClass() ) { - final LazyInitializer lazyInitializer = HibernateProxy.extractLazyInitializer( entity ); + final var lazyInitializer = HibernateProxy.extractLazyInitializer( entity ); if ( lazyInitializer != null ) { return lazyInitializer.getInternalIdentifier(); } - final EmbeddableMappingType embeddableTypeDescriptor = getEmbeddableTypeDescriptor(); + final var embeddableTypeDescriptor = getEmbeddableTypeDescriptor(); final Object[] propertyValues = new Object[embeddableTypeDescriptor.getNumberOfAttributeMappings()]; for ( int i = 0; i < propertyValues.length; i++ ) { - final AttributeMapping attributeMapping = embeddableTypeDescriptor.getAttributeMapping( i ); + final var attributeMapping = embeddableTypeDescriptor.getAttributeMapping( i ); final Object o = attributeMapping.getValue( entity ); if ( o == null ) { - final AttributeMapping idClassAttributeMapping = identifierValueMapper.getAttributeMapping( i ); - if ( idClassAttributeMapping.getPropertyAccess().getGetter().getReturnTypeClass().isPrimitive() ) { - propertyValues[i] = idClassAttributeMapping.getExpressibleJavaType().getDefaultValue(); - } - else { - propertyValues[i] = null; - } + final var idClassAttributeMapping = identifierValueMapper.getAttributeMapping( i ); + propertyValues[i] = + idClassAttributeMapping.getPropertyAccess().getGetter().getReturnTypeClass().isPrimitive() + ? idClassAttributeMapping.getExpressibleJavaType().getDefaultValue() + : null; } //JPA 2 @MapsId + @IdClass points to the pk of the entity else if ( attributeMapping instanceof ToOneAttributeMapping toOneAttributeMapping && !( identifierValueMapper.getAttributeMapping( i ) instanceof ToOneAttributeMapping ) ) { final Object toOne = getIfMerged( o, mergeContext ); - final ModelPart targetPart = + final var targetPart = toOneAttributeMapping.getForeignKeyDescriptor() .getPart( toOneAttributeMapping.getSideNature().inverse() ); propertyValues[i] = @@ -296,31 +282,31 @@ private static Object getIfMerged(Object o, MergeContext mergeContext) { @Override public void setIdentifier(Object entity, Object id, SharedSessionContractImplementor session) { final Object[] propertyValues = new Object[identifierValueMapper.getNumberOfAttributeMappings()]; - final EmbeddableMappingType embeddableTypeDescriptor = getEmbeddableTypeDescriptor(); + final var embeddableTypeDescriptor = getEmbeddableTypeDescriptor(); for ( int i = 0; i < propertyValues.length; i++ ) { - final AttributeMapping attribute = embeddableTypeDescriptor.getAttributeMapping( i ); - final AttributeMapping mappedIdAttributeMapping = identifierValueMapper.getAttributeMapping( i ); - Object o = mappedIdAttributeMapping.getValue( id ); + final var attribute = embeddableTypeDescriptor.getAttributeMapping( i ); + final var mappedIdAttributeMapping = identifierValueMapper.getAttributeMapping( i ); + Object object = mappedIdAttributeMapping.getValue( id ); if ( attribute instanceof ToOneAttributeMapping toOneAttributeMapping && !( mappedIdAttributeMapping instanceof ToOneAttributeMapping ) ) { - final EntityPersister entityPersister = toOneAttributeMapping.getEntityMappingType().getEntityPersister(); - final EntityKey entityKey = session.generateEntityKey( o, entityPersister ); - final PersistenceContext persistenceContext = session.getPersistenceContext(); - final EntityHolder holder = persistenceContext.getEntityHolder( entityKey ); + final var entityPersister = toOneAttributeMapping.getEntityMappingType().getEntityPersister(); + final var entityKey = session.generateEntityKey( object, entityPersister ); + final var persistenceContext = session.getPersistenceContext(); + final var holder = persistenceContext.getEntityHolder( entityKey ); // use the managed object i.e. proxy or initialized entity - o = holder == null ? null : holder.getManagedObject(); - if ( o == null ) { + object = holder == null ? null : holder.getManagedObject(); + if ( object == null ) { // get the association out of the entity itself - o = entityDescriptor.getPropertyValue( + object = entityDescriptor.getPropertyValue( entity, toOneAttributeMapping.getAttributeName() ); - if ( o == null ) { + if ( object == null ) { if ( holder != null && holder.isEventuallyInitialized() ) { - o = holder.getEntity(); + object = holder.getEntity(); } else { - o = session.internalLoad( + object = session.internalLoad( entityPersister.getEntityName(), entityKey.getIdentifier(), true, @@ -330,7 +316,7 @@ public void setIdentifier(Object entity, Object id, SharedSessionContractImpleme } } } - propertyValues[i] = o; + propertyValues[i] = object; } embeddableTypeDescriptor.setValues( entity, propertyValues ); } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/OneToManyCollectionPart.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/OneToManyCollectionPart.java index 795af4c011dc..0630e9ff28c0 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/OneToManyCollectionPart.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/OneToManyCollectionPart.java @@ -14,7 +14,6 @@ import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.metamodel.mapping.ForeignKeyDescriptor; import org.hibernate.metamodel.mapping.JdbcMapping; -import org.hibernate.metamodel.mapping.PluralAttributeMapping; import org.hibernate.metamodel.mapping.SelectableConsumer; import org.hibernate.metamodel.mapping.SelectableMapping; import org.hibernate.persister.collection.CollectionPersister; @@ -64,7 +63,6 @@ public OneToManyCollectionPart( NotFoundAction notFoundAction, MappingModelCreationProcess creationProcess) { super( nature, bootCollectionDescriptor, collectionDescriptor, elementTypeDescriptor, notFoundAction, creationProcess ); - mapKeyPropertyName = nature == Nature.INDEX && bootCollectionDescriptor instanceof Map map ? map.getMapKeyPropertyName() @@ -103,19 +101,23 @@ public int breakDownJdbcValues( ); } + private ForeignKeyDescriptor getKeyDescriptor() { + return getCollectionDescriptor().getAttributeMapping().getKeyDescriptor(); + } + @Override public String getContainingTableExpression() { - return getCollectionDescriptor().getAttributeMapping().getKeyDescriptor().getContainingTableExpression(); + return getKeyDescriptor().getContainingTableExpression(); } @Override public SelectableMapping getSelectable(int columnIndex) { - return getCollectionDescriptor().getAttributeMapping().getKeyDescriptor().getSelectable( columnIndex ); + return getKeyDescriptor().getSelectable( columnIndex ); } @Override public int forEachSelectable(int offset, SelectableConsumer consumer) { - return getCollectionDescriptor().getAttributeMapping().getKeyDescriptor().getKeyPart().forEachSelectable( offset, consumer ); + return getKeyDescriptor().getKeyPart().forEachSelectable( offset, consumer ); } @Override @@ -138,7 +140,7 @@ public SqlAstJoinType getDefaultSqlAstJoinType(TableGroup parentTableGroup) { @Override public boolean isSimpleJoinPredicate(Predicate predicate) { - return getCollectionDescriptor().getAttributeMapping().getKeyDescriptor().isSimpleJoinPredicate( predicate ); + return getKeyDescriptor().isSimpleJoinPredicate( predicate ); } @Override @@ -151,18 +153,18 @@ public TableGroupJoin createTableGroupJoin( boolean fetched, boolean addsPredicate, SqlAstCreationState creationState) { - final SqlAstJoinType joinType = requireNonNullElse( requestedJoinType, SqlAstJoinType.INNER ); - final TableGroup elementTableGroup = ( (OneToManyTableGroup) lhs ).getElementTableGroup(); + final var joinType = requireNonNullElse( requestedJoinType, SqlAstJoinType.INNER ); + final var elementTableGroup = ( (OneToManyTableGroup) lhs ).getElementTableGroup(); // INDEX is implied if mapKeyPropertyName is not null if ( mapKeyPropertyName != null ) { - final EntityCollectionPart elementPart = + final var elementPart = (EntityCollectionPart) getCollectionDescriptor().getAttributeMapping().getElementDescriptor(); if ( elementPart.getAssociatedEntityMappingType().findAttributeMapping( mapKeyPropertyName ) instanceof ToOneAttributeMapping toOne ) { - final NavigablePath mapKeyPropertyPath = navigablePath.append( mapKeyPropertyName ); - final TableGroupJoin tableGroupJoin = toOne.createTableGroupJoin( + final var mapKeyPropertyPath = navigablePath.append( mapKeyPropertyName ); + final var tableGroupJoin = toOne.createTableGroupJoin( mapKeyPropertyPath, elementTableGroup, null, @@ -228,12 +230,12 @@ public boolean finishInitialization( Collection bootValueMapping, String fkTargetModelPartName, MappingModelCreationProcess creationProcess) { - final PluralAttributeMapping pluralAttribute = getCollectionDescriptor().getAttributeMapping(); + final var pluralAttribute = getCollectionDescriptor().getAttributeMapping(); if ( pluralAttribute == null ) { return false; } - final ForeignKeyDescriptor foreignKey = pluralAttribute.getKeyDescriptor(); + final var foreignKey = pluralAttribute.getKeyDescriptor(); if ( foreignKey == null ) { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/PluralAttributeMappingImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/PluralAttributeMappingImpl.java index dbb0c052da59..cb7a241a87bf 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/PluralAttributeMappingImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/PluralAttributeMappingImpl.java @@ -42,7 +42,6 @@ import org.hibernate.spi.NavigablePath; import org.hibernate.sql.ast.SqlAstJoinType; import org.hibernate.sql.ast.internal.TableGroupJoinHelper; -import org.hibernate.sql.ast.spi.FromClauseAccess; import org.hibernate.sql.ast.spi.SqlAliasBase; import org.hibernate.sql.ast.spi.SqlAliasStemHelper; import org.hibernate.sql.ast.spi.SqlAstCreationState; @@ -53,7 +52,6 @@ import org.hibernate.sql.ast.tree.from.TableGroup; import org.hibernate.sql.ast.tree.from.TableGroupJoin; import org.hibernate.sql.ast.tree.from.TableGroupJoinProducer; -import org.hibernate.sql.ast.tree.from.TableReference; import org.hibernate.sql.ast.tree.predicate.Predicate; import org.hibernate.sql.ast.tree.predicate.PredicateCollector; import org.hibernate.sql.results.graph.DomainResult; @@ -226,12 +224,12 @@ private static void injectAttributeMapping( @Override public boolean isBidirectionalAttributeName(NavigablePath fetchablePath, ToOneAttributeMapping modelPart) { - if ( bidirectionalAttributeName == null ) { - // If the FK-target of the to-one mapping is the same as the FK-target of this plural mapping, - // then we say this is bidirectional, given that this is only invoked for model parts of the collection elements - return fkDescriptor.getTargetPart() == modelPart.getForeignKeyDescriptor().getTargetPart(); - } - return fetchablePath.getLocalName().endsWith( bidirectionalAttributeName ); + return bidirectionalAttributeName == null + // If the FK-target of the to-one mapping is the same as the FK-target of this plural mapping, + // then we say this is bidirectional, given that this is only invoked for model parts of the + // collection elements + ? fkDescriptor.getTargetPart() == modelPart.getForeignKeyDescriptor().getTargetPart() + : fetchablePath.getLocalName().endsWith( bidirectionalAttributeName ); } public void finishInitialization( @@ -377,9 +375,9 @@ public void applySoftDeleteRestrictions(TableGroup tableGroup, PredicateConsumer if ( softDeleteMapping != null ) { final String primaryTableName = associatedEntityDescriptor.getSoftDeleteTableDetails().getTableName(); - final TableReference primaryTableReference = + final var primaryTableReference = tableGroup.resolveTableReference( primaryTableName ); - final Predicate softDeleteRestriction = + final var softDeleteRestriction = softDeleteMapping.createNonDeletedRestriction( primaryTableReference ); predicateConsumer.applyPredicate( softDeleteRestriction ); } @@ -388,9 +386,9 @@ public void applySoftDeleteRestrictions(TableGroup tableGroup, PredicateConsumer // apply the collection's soft-delete mapping, if one final var softDeleteMapping = getSoftDeleteMapping(); if ( softDeleteMapping != null ) { - final TableReference primaryTableReference = + final var primaryTableReference = tableGroup.resolveTableReference( getSoftDeleteTableDetails().getTableName() ); - final Predicate softDeleteRestriction = + final var softDeleteRestriction = softDeleteMapping.createNonDeletedRestriction( primaryTableReference ); predicateConsumer.applyPredicate( softDeleteRestriction ); } @@ -403,7 +401,7 @@ public DomainResult createDomainResult( TableGroup tableGroup, String resultVariable, DomainResultCreationState creationState) { - final TableGroup collectionTableGroup = + final var collectionTableGroup = creationState.getSqlAstCreationState().getFromClauseAccess() .getTableGroup( navigablePath ); @@ -432,13 +430,12 @@ public Fetch generateFetch( try { if ( fetchTiming == FetchTiming.IMMEDIATE ) { if ( selected ) { - final TableGroup collectionTableGroup = resolveCollectionTableGroup( + final var collectionTableGroup = resolveCollectionTableGroup( fetchParent, fetchablePath, creationState, sqlAstCreationState ); - return buildEagerCollectionFetch( fetchablePath, this, @@ -551,7 +548,8 @@ private Fetch createSelectEagerCollectionFetch( if ( referencedPropertyName != null ) { collectionKeyDomainResult = getKeyDescriptor().createTargetDomainResult( fetchablePath, - sqlAstCreationState.getFromClauseAccess().getTableGroup( fetchParent.getNavigablePath() ), + sqlAstCreationState.getFromClauseAccess() + .getTableGroup( fetchParent.getNavigablePath() ), fetchParent, creationState ); @@ -567,12 +565,12 @@ private TableGroup resolveCollectionTableGroup( NavigablePath fetchablePath, DomainResultCreationState creationState, SqlAstCreationState sqlAstCreationState) { - final FromClauseAccess fromClauseAccess = sqlAstCreationState.getFromClauseAccess(); + final var fromClauseAccess = sqlAstCreationState.getFromClauseAccess(); return fromClauseAccess.resolveTableGroup( fetchablePath, p -> { - final TableGroup lhsTableGroup = fromClauseAccess.getTableGroup( fetchParent.getNavigablePath() ); - final TableGroupJoin tableGroupJoin = createTableGroupJoin( + final var lhsTableGroup = fromClauseAccess.getTableGroup( fetchParent.getNavigablePath() ); + final var tableGroupJoin = createTableGroupJoin( fetchablePath, lhsTableGroup, null, @@ -596,7 +594,7 @@ private Fetch createDelayedCollectionFetch( final DomainResult collectionKeyDomainResult; // Lazy property. A null foreign key domain result will lead to // returning a domain result assembler that returns LazyPropertyInitializer.UNFETCHED_PROPERTY - final EntityMappingType containingEntityMapping = findContainingEntityMapping(); + final var containingEntityMapping = findContainingEntityMapping(); final boolean unfetched; if ( fetchParent.getReferencedModePart() == containingEntityMapping && containingEntityMapping.getEntityPersister().getPropertyLaziness()[getStateArrayPosition()] ) { @@ -651,8 +649,8 @@ public TableGroupJoin createTableGroupJoin( boolean fetched, boolean addsPredicate, SqlAstCreationState creationState) { - final PredicateCollector collectionPredicateCollector = new PredicateCollector(); - final TableGroup tableGroup = createRootTableGroupJoin( + final var collectionPredicateCollector = new PredicateCollector(); + final var tableGroup = createRootTableGroupJoin( navigablePath, lhs, explicitSourceAlias, @@ -663,14 +661,11 @@ public TableGroupJoin createTableGroupJoin( collectionPredicateCollector::applyPredicate, creationState ); - final PredicateCollector predicateCollector; - if ( tableGroup.getNestedTableGroupJoins().isEmpty() ) { - // No nested table group joins means that the predicate has to be pushed to the last join - predicateCollector = new PredicateCollector(); - } - else { - predicateCollector = collectionPredicateCollector; - } + final var predicateCollector = + tableGroup.getNestedTableGroupJoins().isEmpty() + // No nested table group joins means that the predicate has to be pushed to the last join + ? new PredicateCollector() + : collectionPredicateCollector; getCollectionDescriptor().applyBaseRestrictions( predicateCollector::applyPredicate, @@ -707,14 +702,14 @@ public TableGroupJoin createTableGroupJoin( } } - final TableGroupJoin tableGroupJoin = new TableGroupJoin( + final var tableGroupJoin = new TableGroupJoin( navigablePath, determineSqlJoinType( lhs, requestedJoinType, fetched ), tableGroup, collectionPredicateCollector.getPredicate() ); if ( predicateCollector != collectionPredicateCollector ) { - final TableGroupJoin joinForPredicate = TableGroupJoinHelper.determineJoinForPredicateApply( tableGroupJoin ); + final var joinForPredicate = TableGroupJoinHelper.determineJoinForPredicateApply( tableGroupJoin ); joinForPredicate.applyPredicate( predicateCollector.getPredicate() ); } return tableGroupJoin; @@ -738,10 +733,10 @@ private void applySoftDeleteRestriction( SqlAstCreationState creationState) { if ( hasSoftDelete() ) { if ( getElementDescriptor() instanceof EntityCollectionPart entityCollectionPart ) { - final EntityMappingType entityMappingType = entityCollectionPart.getAssociatedEntityMappingType(); - final SoftDeleteMapping softDeleteMapping = entityMappingType.getSoftDeleteMapping(); + final var entityMappingType = entityCollectionPart.getAssociatedEntityMappingType(); + final var softDeleteMapping = entityMappingType.getSoftDeleteMapping(); if ( softDeleteMapping != null ) { - final TableDetails softDeleteTable = entityMappingType.getSoftDeleteTableDetails(); + final var softDeleteTable = entityMappingType.getSoftDeleteTableDetails(); predicateConsumer.accept( softDeleteMapping.createNonDeletedRestriction( tableGroup.resolveTableReference( softDeleteTable.getTableName() ), creationState.getSqlExpressionResolver() @@ -749,9 +744,9 @@ private void applySoftDeleteRestriction( } } - final SoftDeleteMapping softDeleteMapping = getSoftDeleteMapping(); + final var softDeleteMapping = getSoftDeleteMapping(); if ( softDeleteMapping != null ) { - final TableDetails softDeleteTable = getSoftDeleteTableDetails(); + final var softDeleteTable = getSoftDeleteTableDetails(); predicateConsumer.accept( softDeleteMapping.createNonDeletedRestriction( tableGroup.resolveTableReference( softDeleteTable.getTableName() ), creationState.getSqlExpressionResolver() @@ -764,8 +759,7 @@ public SqlAstJoinType determineSqlJoinType(TableGroup lhs, @Nullable SqlAstJoinT if ( hasSoftDelete() ) { return SqlAstJoinType.LEFT; } - - if ( requestedJoinType == null ) { + else if ( requestedJoinType == null ) { if ( fetched ) { return getDefaultSqlAstJoinType( lhs ); } @@ -863,13 +857,14 @@ private TableGroup createOneToManyTableGroup( String sourceAlias, SqlAliasBase explicitSqlAliasBase, SqlAstCreationState creationState) { - final SqlAliasBase sqlAliasBase = SqlAliasBase.from( + final var sqlAliasBase = SqlAliasBase.from( explicitSqlAliasBase, sourceAlias, this, creationState.getSqlAliasBaseGenerator() ); - final TableGroup elementTableGroup = ( (OneToManyCollectionPart) elementDescriptor ).createAssociatedTableGroup( + final var oneToManyCollectionPart = (OneToManyCollectionPart) elementDescriptor; + final var elementTableGroup = oneToManyCollectionPart.createAssociatedTableGroup( canUseInnerJoins, navigablePath.append( CollectionPart.Nature.ELEMENT.getName() ), fetched, @@ -877,7 +872,7 @@ private TableGroup createOneToManyTableGroup( sqlAliasBase, creationState ); - final OneToManyTableGroup tableGroup = new OneToManyTableGroup( + final var tableGroup = new OneToManyTableGroup( this, elementTableGroup, creationState.getCreationContext().getSessionFactory() @@ -890,7 +885,7 @@ private TableGroup createOneToManyTableGroup( || collectionDescriptor.hasWhereRestrictions() ); if ( indexDescriptor instanceof TableGroupJoinProducer tableGroupJoinProducer ) { - final TableGroupJoin tableGroupJoin = tableGroupJoinProducer.createTableGroupJoin( + final var tableGroupJoin = tableGroupJoinProducer.createTableGroupJoin( navigablePath.append( CollectionPart.Nature.INDEX.getName() ), tableGroup, null, @@ -916,20 +911,20 @@ private TableGroup createCollectionTableGroup( SqlAliasBase explicitSqlAliasBase, SqlAstCreationState creationState) { assert !getCollectionDescriptor().isOneToMany(); - final SqlAliasBase sqlAliasBase = SqlAliasBase.from( + final var sqlAliasBase = SqlAliasBase.from( explicitSqlAliasBase, sourceAlias, this, creationState.getSqlAliasBaseGenerator() ); final String collectionTableName = collectionDescriptor.getTableName(); - final TableReference collectionTableReference = new NamedTableReference( + final var collectionTableReference = new NamedTableReference( collectionTableName, sqlAliasBase.generateNewAlias(), true ); - final CollectionTableGroup tableGroup = new CollectionTableGroup( + final var tableGroup = new CollectionTableGroup( canUseInnerJoins, navigablePath, this, @@ -950,7 +945,7 @@ private TableGroup createCollectionTableGroup( || collectionDescriptor.hasWhereRestrictions() ); if ( elementDescriptor instanceof TableGroupJoinProducer tableGroupJoinProducer ) { - final TableGroupJoin tableGroupJoin = tableGroupJoinProducer.createTableGroupJoin( + final var tableGroupJoin = tableGroupJoinProducer.createTableGroupJoin( navigablePath.append( CollectionPart.Nature.ELEMENT.getName() ), tableGroup, null, @@ -964,7 +959,7 @@ private TableGroup createCollectionTableGroup( } if ( indexDescriptor instanceof TableGroupJoinProducer tableGroupJoinProducer ) { - final TableGroupJoin tableGroupJoin = tableGroupJoinProducer.createTableGroupJoin( + final var tableGroupJoin = tableGroupJoinProducer.createTableGroupJoin( navigablePath.append( CollectionPart.Nature.INDEX.getName() ), tableGroup, null, @@ -1048,12 +1043,12 @@ public String getRootPathName() { @Override public ModelPart findSubPart(String name, EntityMappingType treatTargetType) { if ( elementDescriptor instanceof ModelPartContainer modelPartContainer ) { - final ModelPart subPart = modelPartContainer.findSubPart( name, null ); + final var subPart = modelPartContainer.findSubPart( name, null ); if ( subPart != null ) { return subPart; } } - final CollectionPart.Nature nature = CollectionPart.Nature.fromName( name ); + final var nature = CollectionPart.Nature.fromName( name ); if ( nature != null ) { return switch ( nature ) { case ELEMENT -> elementDescriptor; diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SelectableMappingImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SelectableMappingImpl.java index 97e1d3b1bd93..9447d92c4838 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SelectableMappingImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SelectableMappingImpl.java @@ -227,7 +227,7 @@ public static SelectableMapping from( selectableName = selectable.getText(); } else { - Column column = (Column) selectable; + var column = (Column) selectable; columnExpression = selectable.getText( dialect ); columnDefinition = column.getSqlType(); length = column.getLength(); diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SelectableMappingsImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SelectableMappingsImpl.java index b6bdfb07955e..7c0871166ad1 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SelectableMappingsImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SelectableMappingsImpl.java @@ -9,8 +9,6 @@ import org.checkerframework.checker.nullness.qual.Nullable; import org.hibernate.dialect.Dialect; -import org.hibernate.internal.util.collections.CollectionHelper; -import org.hibernate.mapping.Selectable; import org.hibernate.mapping.Value; import org.hibernate.metamodel.mapping.EmbeddableMappingType; import org.hibernate.metamodel.mapping.JdbcMapping; @@ -26,6 +24,8 @@ import org.hibernate.type.MappingContext; import org.hibernate.type.spi.TypeConfiguration; +import static org.hibernate.internal.util.collections.CollectionHelper.arrayList; + /** * @author Christian Beikov */ @@ -43,8 +43,7 @@ private static void resolveJdbcMappings(List jdbcMappings, MappingC ? entityType.getIdentifierOrUniqueKeyType( mapping ) : valueType; if ( keyType instanceof CompositeType compositeType ) { - Type[] subtypes = compositeType.getSubtypes(); - for ( Type subtype : subtypes ) { + for ( Type subtype : compositeType.getSubtypes() ) { resolveJdbcMappings( jdbcMappings, mapping, subtype ); } } @@ -94,9 +93,8 @@ public static SelectableMappings from( final List jdbcMappings = new ArrayList<>(); resolveJdbcMappings( jdbcMappings, mappingContext, value.getType() ); - final List selectables = value.getVirtualSelectables(); - - final SelectableMapping[] selectableMappings = new SelectableMapping[jdbcMappings.size()]; + final var selectables = value.getVirtualSelectables(); + final var selectableMappings = new SelectableMapping[jdbcMappings.size()]; for ( int i = 0; i < selectables.size(); i++ ) { selectableMappings[propertyOrder[i]] = SelectableMappingImpl.from( containingTableExpression, @@ -118,14 +116,12 @@ public static SelectableMappings from( public static SelectableMappings from(EmbeddableMappingType embeddableMappingType) { final int propertySpan = embeddableMappingType.getNumberOfAttributeMappings(); - final List selectableMappings = CollectionHelper.arrayList( propertySpan ); - + final List selectableMappings = arrayList( propertySpan ); embeddableMappingType.forEachAttributeMapping( (index, attributeMapping) -> attributeMapping.forEachSelectable( (columnIndex, selection) -> selectableMappings.add( selection ) ) ); - return new SelectableMappingsImpl( selectableMappings.toArray( new SelectableMapping[0] ) ); } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SimpleForeignKeyDescriptor.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SimpleForeignKeyDescriptor.java index c71899048fb3..aed1ace3cc83 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SimpleForeignKeyDescriptor.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SimpleForeignKeyDescriptor.java @@ -17,7 +17,6 @@ import org.hibernate.engine.FetchStyle; import org.hibernate.engine.FetchTiming; import org.hibernate.engine.internal.CacheHelper; -import org.hibernate.engine.spi.PersistentAttributeInterceptor; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.internal.util.IndexedConsumer; import org.hibernate.metamodel.mapping.AssociationKey; @@ -26,24 +25,19 @@ import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.metamodel.mapping.ForeignKeyDescriptor; import org.hibernate.metamodel.mapping.JdbcMapping; -import org.hibernate.metamodel.mapping.JdbcMappingContainer; import org.hibernate.metamodel.mapping.ManagedMappingType; import org.hibernate.metamodel.mapping.MappingType; -import org.hibernate.metamodel.mapping.ModelPart; import org.hibernate.metamodel.mapping.PropertyBasedMapping; import org.hibernate.metamodel.mapping.SelectableConsumer; import org.hibernate.metamodel.mapping.SelectableMapping; import org.hibernate.metamodel.mapping.ValuedModelPart; import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.property.access.spi.PropertyAccess; -import org.hibernate.proxy.LazyInitializer; import org.hibernate.query.sqm.ComparisonOperator; import org.hibernate.spi.NavigablePath; import org.hibernate.sql.ast.spi.SqlAstCreationState; -import org.hibernate.sql.ast.spi.SqlExpressionResolver; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.expression.ColumnReference; -import org.hibernate.sql.ast.tree.expression.Expression; import org.hibernate.sql.ast.tree.from.OneToManyTableGroup; import org.hibernate.sql.ast.tree.from.TableGroup; import org.hibernate.sql.ast.tree.from.TableGroupProducer; @@ -110,12 +104,12 @@ public SimpleForeignKeyDescriptor( assert targetModelPart != null; if ( swapDirection ) { - this.keySide = new SimpleForeignKeyDescriptorSide( Nature.KEY, targetModelPart ); - this.targetSide = new SimpleForeignKeyDescriptorSide( Nature.TARGET, keyModelPart ); + keySide = new SimpleForeignKeyDescriptorSide( Nature.KEY, targetModelPart ); + targetSide = new SimpleForeignKeyDescriptorSide( Nature.TARGET, keyModelPart ); } else { - this.keySide = new SimpleForeignKeyDescriptorSide( Nature.KEY, keyModelPart ); - this.targetSide = new SimpleForeignKeyDescriptorSide( Nature.TARGET, targetModelPart ); + keySide = new SimpleForeignKeyDescriptorSide( Nature.KEY, keyModelPart ); + targetSide = new SimpleForeignKeyDescriptorSide( Nature.TARGET, targetModelPart ); } this.refersToPrimaryKey = refersToPrimaryKey; @@ -225,7 +219,7 @@ public ForeignKeyDescriptor withKeySelectionMapping( TableGroupProducer declaringTableGroupProducer, IntFunction selectableMappingAccess, MappingModelCreationProcess creationProcess) { - final SelectableMapping selectableMapping = selectableMappingAccess.apply( 0 ); + final var selectableMapping = selectableMappingAccess.apply( 0 ); return new SimpleForeignKeyDescriptor( declaringType, keySide.getModelPart(), @@ -319,7 +313,7 @@ public DomainResult createDomainResult( private boolean isTargetTableGroup(TableGroup tableGroup) { tableGroup = getUnderlyingTableGroup( tableGroup ); - final TableGroupProducer tableGroupProducer = + final var tableGroupProducer = tableGroup instanceof OneToManyTableGroup oneToManyTableGroup ? (TableGroupProducer) oneToManyTableGroup.getElementTableGroup().getModelPart() : (TableGroupProducer) tableGroup.getModelPart(); @@ -356,8 +350,8 @@ private DomainResult createDomainResult( BasicValuedModelPart selectableMapping, FetchParent fetchParent, DomainResultCreationState creationState) { - final SqlAstCreationState sqlAstCreationState = creationState.getSqlAstCreationState(); - final SqlExpressionResolver sqlExpressionResolver = sqlAstCreationState.getSqlExpressionResolver(); + final var sqlAstCreationState = creationState.getSqlAstCreationState(); + final var sqlExpressionResolver = sqlAstCreationState.getSqlExpressionResolver(); final TableReference tableReference; try { tableReference = tableGroup.resolveTableReference( @@ -378,15 +372,15 @@ private DomainResult createDomainResult( ); } - final JavaType javaType = selectableMapping.getJdbcMapping().getJdbcJavaType(); - final SqlSelection sqlSelection = sqlExpressionResolver.resolveSqlSelection( + final var javaType = selectableMapping.getJdbcMapping().getJdbcJavaType(); + final var sqlSelection = sqlExpressionResolver.resolveSqlSelection( sqlExpressionResolver.resolveSqlExpression( tableReference, selectableMapping ), javaType, fetchParent, sqlAstCreationState.getCreationContext().getTypeConfiguration() ); - final JdbcMappingContainer selectionType = sqlSelection.getExpressionType(); + final var selectionType = sqlSelection.getExpressionType(); return new BasicResult<>( sqlSelection.getValuesArrayPosition(), null, @@ -415,11 +409,11 @@ public Predicate generateJoinPredicate( TableGroup targetSideTableGroup, TableGroup keySideTableGroup, SqlAstCreationState creationState) { - final TableReference lhsTableReference = targetSideTableGroup.resolveTableReference( + final var lhsTableReference = targetSideTableGroup.resolveTableReference( targetSideTableGroup.getNavigablePath(), targetSide.getModelPart().getContainingTableExpression() ); - final TableReference rhsTableKeyReference = keySideTableGroup.resolveTableReference( + final var rhsTableKeyReference = keySideTableGroup.resolveTableReference( null, keySide.getModelPart().getContainingTableExpression() ); @@ -435,8 +429,8 @@ public boolean isSimpleJoinPredicate(Predicate predicate) { if ( comparisonPredicate.getOperator() != ComparisonOperator.EQUAL ) { return false; } - final Expression lhsExpr = comparisonPredicate.getLeftHandExpression(); - final Expression rhsExpr = comparisonPredicate.getRightHandExpression(); + final var lhsExpr = comparisonPredicate.getLeftHandExpression(); + final var rhsExpr = comparisonPredicate.getRightHandExpression(); if ( lhsExpr instanceof ColumnReference lhsColumnRef && rhsExpr instanceof ColumnReference rhsColumnRef ) { final String lhs = lhsColumnRef.getColumnExpression(); @@ -495,7 +489,7 @@ public Object getAssociationKeyFromSide( if ( targetObject == null ) { return null; } - final LazyInitializer lazyInitializer = extractLazyInitializer( targetObject ); + final var lazyInitializer = extractLazyInitializer( targetObject ); if ( lazyInitializer != null ) { if ( refersToPrimaryKey ) { return lazyInitializer.getInternalIdentifier(); @@ -504,15 +498,14 @@ public Object getAssociationKeyFromSide( targetObject = lazyInitializer.getImplementation(); } } - final ModelPart modelPart = side.getModelPart(); + final var modelPart = side.getModelPart(); if ( modelPart.isEntityIdentifierMapping() ) { return ( (EntityIdentifierMapping) modelPart ).getIdentifierIfNotUnsaved( targetObject, session ); } if ( lazyInitializer == null && isPersistentAttributeInterceptable( targetObject ) ) { - final PersistentAttributeInterceptor interceptor = - asPersistentAttributeInterceptable( targetObject ).$$_hibernate_getInterceptor(); - if ( interceptor instanceof EnhancementAsProxyLazinessInterceptor lazinessInterceptor + if ( asPersistentAttributeInterceptable( targetObject ).$$_hibernate_getInterceptor() + instanceof EnhancementAsProxyLazinessInterceptor lazinessInterceptor && !lazinessInterceptor.isInitialized() ) { Hibernate.initialize( targetObject ); } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SimpleNaturalIdMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SimpleNaturalIdMapping.java index 46b75a2c46d5..e68641444fd6 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SimpleNaturalIdMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SimpleNaturalIdMapping.java @@ -28,7 +28,6 @@ import org.hibernate.metamodel.mapping.MappingType; import org.hibernate.metamodel.mapping.SelectableConsumer; import org.hibernate.metamodel.mapping.SingularAttributeMapping; -import org.hibernate.persister.entity.EntityPersister; import org.hibernate.spi.NavigablePath; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.from.TableGroup; @@ -69,11 +68,12 @@ public void verifyFlushState( Object[] loadedState, SharedSessionContractImplementor session) { if ( !isMutable() ) { - final EntityPersister persister = getDeclaringType().getEntityPersister(); + final var persister = getDeclaringType().getEntityPersister(); final Object naturalId = extractNaturalIdFromEntityState( currentState ); - final Object snapshot = loadedState == null - ? session.getPersistenceContextInternal().getNaturalIdSnapshot( id, persister ) - : persister.getNaturalIdMapping().extractNaturalIdFromEntityState( loadedState ); + final Object snapshot = + loadedState == null + ? session.getPersistenceContextInternal().getNaturalIdSnapshot( id, persister ) + : persister.getNaturalIdMapping().extractNaturalIdFromEntityState( loadedState ); if ( !areEqual( naturalId, snapshot, session ) ) { throw new HibernateException( String.format( @@ -109,7 +109,7 @@ public Object extractNaturalIdFromEntity(Object entity) { @Override public void validateInternalForm(Object naturalIdValue) { if ( naturalIdValue != null ) { - final Class naturalIdValueClass = naturalIdValue.getClass(); + final var naturalIdValueClass = naturalIdValue.getClass(); if ( naturalIdValueClass.isArray() && !naturalIdValueClass.getComponentType().isPrimitive() ) { // be flexible final Object[] values = (Object[]) naturalIdValue; diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SoftDeleteMappingImpl.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SoftDeleteMappingImpl.java index 6a985eec49dd..5bf51bb76520 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SoftDeleteMappingImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/SoftDeleteMappingImpl.java @@ -6,26 +6,22 @@ import org.hibernate.annotations.SoftDeleteType; import org.hibernate.cache.MutableCacheKeyBuilder; -import org.hibernate.dialect.Dialect; import org.hibernate.dialect.function.CurrentFunction; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.internal.util.IndexedConsumer; import org.hibernate.mapping.BasicValue; -import org.hibernate.mapping.Column; import org.hibernate.mapping.SoftDeletable; import org.hibernate.metamodel.mapping.EntityMappingType; import org.hibernate.metamodel.mapping.JdbcMapping; import org.hibernate.metamodel.mapping.MappingType; import org.hibernate.metamodel.mapping.SoftDeletableModelPart; import org.hibernate.metamodel.mapping.SoftDeleteMapping; -import org.hibernate.metamodel.mapping.TableDetails; import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.query.sqm.function.SelfRenderingFunctionSqlAstExpression; import org.hibernate.spi.NavigablePath; import org.hibernate.sql.ast.spi.SqlExpressionResolver; import org.hibernate.sql.ast.spi.SqlSelection; import org.hibernate.sql.ast.tree.expression.ColumnReference; -import org.hibernate.sql.ast.tree.expression.Expression; import org.hibernate.sql.ast.tree.expression.JdbcLiteral; import org.hibernate.sql.ast.tree.from.TableGroup; import org.hibernate.sql.ast.tree.from.TableReference; @@ -38,15 +34,14 @@ import org.hibernate.sql.results.graph.DomainResult; import org.hibernate.sql.results.graph.DomainResultCreationState; import org.hibernate.sql.results.graph.basic.BasicResult; -import org.hibernate.type.BasicType; import org.hibernate.type.descriptor.converter.spi.BasicValueConverter; import org.hibernate.type.descriptor.java.JavaType; import org.hibernate.type.descriptor.jdbc.JdbcLiteralFormatter; import java.time.Instant; -import java.util.Collections; import java.util.function.BiConsumer; +import static java.util.Collections.emptyList; import static org.hibernate.query.sqm.ComparisonOperator.EQUAL; /** @@ -81,50 +76,49 @@ public SoftDeleteMappingImpl( MappingModelCreationProcess modelCreationProcess) { assert bootMapping.getSoftDeleteColumn() != null; - this.navigableRole = softDeletable.getNavigableRole().append( ROLE_NAME ); this.softDeletable = softDeletable; - this.strategy = bootMapping.getSoftDeleteStrategy(); + navigableRole = softDeletable.getNavigableRole().append( ROLE_NAME ); + strategy = bootMapping.getSoftDeleteStrategy(); - final Dialect dialect = modelCreationProcess.getCreationContext().getDialect(); + final var dialect = modelCreationProcess.getCreationContext().getDialect(); - final Column softDeleteColumn = bootMapping.getSoftDeleteColumn(); - final BasicValue columnValue = (BasicValue) softDeleteColumn.getValue(); - final BasicValue.Resolution resolution = columnValue.resolve(); + final var softDeleteColumn = bootMapping.getSoftDeleteColumn(); + final var columnValue = (BasicValue) softDeleteColumn.getValue(); + final var resolution = columnValue.resolve(); - this.columnName = softDeleteColumn.getName(); this.tableName = tableName; - this.jdbcMapping = resolution.getJdbcMapping(); + columnName = softDeleteColumn.getName(); + jdbcMapping = resolution.getJdbcMapping(); if ( bootMapping.getSoftDeleteStrategy() == SoftDeleteType.TIMESTAMP ) { - this.currentTimestampFunctionName = dialect.currentTimestamp(); - final BasicType currentTimestampFunctionType = modelCreationProcess - .getCreationContext() - .getTypeConfiguration() - .getBasicTypeForJavaType( Instant.class ); - final CurrentFunction currentTimestampFunction = new CurrentFunction( + currentTimestampFunctionName = dialect.currentTimestamp(); + final var currentTimestampFunctionType = + modelCreationProcess.getCreationContext().getTypeConfiguration() + .getBasicTypeForJavaType( Instant.class ); + final var currentTimestampFunction = new CurrentFunction( currentTimestampFunctionName, currentTimestampFunctionName, currentTimestampFunctionType ); - this.currentTimestampFunctionExpression = new SelfRenderingFunctionSqlAstExpression<>( + currentTimestampFunctionExpression = new SelfRenderingFunctionSqlAstExpression<>( currentTimestampFunctionName, currentTimestampFunction, - Collections.emptyList(), + emptyList(), currentTimestampFunctionType, softDeletable ); - this.deletionIndicator = currentTimestampFunctionName; + deletionIndicator = currentTimestampFunctionName; - this.deletedLiteralValue = null; - this.deletedLiteralText = null; + deletedLiteralValue = null; + deletedLiteralText = null; - this.nonDeletedLiteralValue = null; - this.nonDeletedLiteralText = null; + nonDeletedLiteralValue = null; + nonDeletedLiteralText = null; } else { //noinspection unchecked - final BasicValueConverter converter = + final var converter = (BasicValueConverter) resolution.getValueConverter(); //noinspection unchecked @@ -132,22 +126,22 @@ public SoftDeleteMappingImpl( resolution.getJdbcMapping().getJdbcLiteralFormatter(); if ( converter == null ) { - // the database column is BIT or BOOLEAN : pass-thru - this.deletedLiteralValue = true; - this.nonDeletedLiteralValue = false; + // the database column is BIT or BOOLEAN: pass-thru + deletedLiteralValue = true; + nonDeletedLiteralValue = false; } else { - this.deletedLiteralValue = converter.toRelationalValue( true ); - this.nonDeletedLiteralValue = converter.toRelationalValue( false ); + deletedLiteralValue = converter.toRelationalValue( true ); + nonDeletedLiteralValue = converter.toRelationalValue( false ); } - this.deletedLiteralText = literalFormatter.toJdbcLiteral( deletedLiteralValue, dialect, null ); - this.nonDeletedLiteralText = literalFormatter.toJdbcLiteral( nonDeletedLiteralValue, dialect, null ); + deletedLiteralText = literalFormatter.toJdbcLiteral( deletedLiteralValue, dialect, null ); + nonDeletedLiteralText = literalFormatter.toJdbcLiteral( nonDeletedLiteralValue, dialect, null ); - this.deletionIndicator = deletedLiteralValue; + deletionIndicator = deletedLiteralValue; - this.currentTimestampFunctionName = null; - this.currentTimestampFunctionExpression = null; + currentTimestampFunctionName = null; + currentTimestampFunctionExpression = null; } } @@ -177,8 +171,8 @@ public Object getDeletionIndicator() { @Override public Assignment createSoftDeleteAssignment(TableReference tableReference) { - final ColumnReference columnReference = new ColumnReference( tableReference, this ); - final Expression valueExpression = + final var columnReference = new ColumnReference( tableReference, this ); + final var valueExpression = strategy == SoftDeleteType.TIMESTAMP ? currentTimestampFunctionExpression : new JdbcLiteral<>( deletedLiteralValue, jdbcMapping ); @@ -187,7 +181,7 @@ public Assignment createSoftDeleteAssignment(TableReference tableReference) { @Override public Predicate createNonDeletedRestriction(TableReference tableReference) { - final ColumnReference softDeleteColumn = new ColumnReference( tableReference, this ); + final var softDeleteColumn = new ColumnReference( tableReference, this ); if ( strategy == SoftDeleteType.TIMESTAMP ) { return new NullnessPredicate( softDeleteColumn, false, jdbcMapping ); } @@ -199,7 +193,7 @@ public Predicate createNonDeletedRestriction(TableReference tableReference) { @Override public Predicate createNonDeletedRestriction(TableReference tableReference, SqlExpressionResolver expressionResolver) { - final Expression softDeleteColumn = expressionResolver.resolveSqlExpression( tableReference, this ); + final var softDeleteColumn = expressionResolver.resolveSqlExpression( tableReference, this ); if ( strategy == SoftDeleteType.TIMESTAMP ) { return new NullnessPredicate( softDeleteColumn, false, jdbcMapping ); } @@ -214,41 +208,19 @@ public Predicate createNonDeletedRestriction(TableReference tableReference, SqlE @Override public ColumnValueBinding createNonDeletedValueBinding(ColumnReference softDeleteColumnReference) { - final ColumnWriteFragment nonDeletedFragment; - if ( strategy == SoftDeleteType.TIMESTAMP ) { - nonDeletedFragment = new ColumnWriteFragment( - null, - Collections.emptyList(), - jdbcMapping - ); - } - else { - nonDeletedFragment = new ColumnWriteFragment( - nonDeletedLiteralText, - Collections.emptyList(), - jdbcMapping - ); - } + final var nonDeletedFragment = + strategy == SoftDeleteType.TIMESTAMP + ? new ColumnWriteFragment( null, emptyList(), jdbcMapping ) + : new ColumnWriteFragment( nonDeletedLiteralText, emptyList(), jdbcMapping ); return new ColumnValueBinding( softDeleteColumnReference, nonDeletedFragment ); } @Override public ColumnValueBinding createDeletedValueBinding(ColumnReference softDeleteColumnReference) { - final ColumnWriteFragment deletedFragment; - if ( strategy == SoftDeleteType.TIMESTAMP ) { - deletedFragment = new ColumnWriteFragment( - currentTimestampFunctionName, - Collections.emptyList(), - getJdbcMapping() - ); - } - else { - deletedFragment = new ColumnWriteFragment( - deletedLiteralText, - Collections.emptyList(), - jdbcMapping - ); - } + final ColumnWriteFragment deletedFragment = + strategy == SoftDeleteType.TIMESTAMP + ? new ColumnWriteFragment( currentTimestampFunctionName, emptyList(), getJdbcMapping() ) + : new ColumnWriteFragment( deletedLiteralText, emptyList(), jdbcMapping ); return new ColumnValueBinding( softDeleteColumnReference, deletedFragment ); } @@ -315,7 +287,7 @@ public DomainResult createDomainResult( TableGroup tableGroup, String resultVariable, DomainResultCreationState creationState) { - final SqlSelection sqlSelection = resolveSqlSelection( navigablePath, tableGroup, creationState ); + final var sqlSelection = resolveSqlSelection( navigablePath, tableGroup, creationState ); return new BasicResult<>( sqlSelection.getValuesArrayPosition(), resultVariable, @@ -330,12 +302,12 @@ private SqlSelection resolveSqlSelection( NavigablePath navigablePath, TableGroup tableGroup, DomainResultCreationState creationState) { - final TableDetails indicatorTable = softDeletable.getSoftDeleteTableDetails(); - final TableReference tableReference = tableGroup.resolveTableReference( + final var indicatorTable = softDeletable.getSoftDeleteTableDetails(); + final var tableReference = tableGroup.resolveTableReference( navigablePath.getRealParent(), indicatorTable.getTableName() ); - final SqlExpressionResolver expressionResolver = creationState.getSqlAstCreationState().getSqlExpressionResolver(); + final var expressionResolver = creationState.getSqlAstCreationState().getSqlExpressionResolver(); return expressionResolver.resolveSqlSelection( expressionResolver.resolveSqlExpression( tableReference, this ), getJavaType(), @@ -358,7 +330,7 @@ public void applySqlSelections( TableGroup tableGroup, DomainResultCreationState creationState, BiConsumer selectionConsumer) { - final SqlSelection sqlSelection = resolveSqlSelection( navigablePath, tableGroup, creationState ); + final var sqlSelection = resolveSqlSelection( navigablePath, tableGroup, creationState ); selectionConsumer.accept( sqlSelection, getJdbcMapping() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java index 0b51e85a1e3e..b2dd2b44219a 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/ToOneAttributeMapping.java @@ -21,14 +21,11 @@ import org.hibernate.mapping.Join; import org.hibernate.mapping.ManyToOne; import org.hibernate.mapping.OneToOne; -import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; -import org.hibernate.mapping.Selectable; import org.hibernate.mapping.ToOne; import org.hibernate.mapping.Value; import org.hibernate.metamodel.UnsupportedMappingException; import org.hibernate.metamodel.mapping.AssociationKey; -import org.hibernate.metamodel.mapping.AttributeMapping; import org.hibernate.metamodel.mapping.AttributeMetadata; import org.hibernate.metamodel.mapping.CollectionPart; import org.hibernate.metamodel.mapping.CompositeIdentifierMapping; @@ -46,7 +43,6 @@ import org.hibernate.metamodel.mapping.SelectableConsumer; import org.hibernate.metamodel.mapping.SelectableMapping; import org.hibernate.metamodel.mapping.SelectablePath; -import org.hibernate.metamodel.mapping.SoftDeleteMapping; import org.hibernate.metamodel.mapping.ValuedModelPart; import org.hibernate.metamodel.mapping.VirtualModelPart; import org.hibernate.metamodel.model.domain.NavigableRole; @@ -56,7 +52,6 @@ import org.hibernate.persister.entity.JoinedSubclassEntityPersister; import org.hibernate.property.access.spi.PropertyAccess; import org.hibernate.proxy.HibernateProxy; -import org.hibernate.proxy.LazyInitializer; import org.hibernate.query.sqm.sql.SqmToSqlAstConverter; import org.hibernate.spi.EntityIdentifierNavigablePath; import org.hibernate.spi.NavigablePath; @@ -87,7 +82,6 @@ import org.hibernate.sql.results.graph.FetchOptions; import org.hibernate.sql.results.graph.FetchParent; import org.hibernate.sql.results.graph.Fetchable; -import org.hibernate.sql.results.graph.FetchableContainer; import org.hibernate.sql.results.graph.InitializerParent; import org.hibernate.sql.results.graph.embeddable.EmbeddableValuedFetchable; import org.hibernate.sql.results.graph.entity.EntityFetch; @@ -107,7 +101,6 @@ import java.util.Arrays; import java.util.BitSet; import java.util.HashSet; -import java.util.List; import java.util.Locale; import java.util.Set; import java.util.function.BiConsumer; @@ -255,33 +248,34 @@ public ToOneAttributeMapping( declaringType, propertyAccess ); - this.sqlAliasStem = SqlAliasStemHelper.INSTANCE.generateStemFromAttributeName( name ); - this.isNullable = bootValue.isNullable(); - this.isLazy = navigableRole.getParent().getParent() == null + sqlAliasStem = SqlAliasStemHelper.INSTANCE.generateStemFromAttributeName( name ); + isNullable = bootValue.isNullable(); + isLazy = navigableRole.getParent().getParent() == null && declaringEntityPersister.getBytecodeEnhancementMetadata() .getLazyAttributesMetadata() .isLazyAttribute( name ); - this.referencedPropertyName = bootValue.getReferencedPropertyName(); - this.unwrapProxy = bootValue.isUnwrapProxy(); + referencedPropertyName = bootValue.getReferencedPropertyName(); + unwrapProxy = bootValue.isUnwrapProxy(); this.entityMappingType = entityMappingType; this.navigableRole = navigableRole; - this.declaringTableGroupProducer = resolveDeclaringTableGroupProducer( + declaringTableGroupProducer = resolveDeclaringTableGroupProducer( declaringEntityPersister, navigableRole ); if ( bootValue instanceof ManyToOne manyToOne ) { - this.notFoundAction = manyToOne.getNotFoundAction(); + notFoundAction = manyToOne.getNotFoundAction(); cardinality = manyToOne.isLogicalOneToOne() ? Cardinality.LOGICAL_ONE_TO_ONE : Cardinality.MANY_TO_ONE; - final PersistentClass entityBinding = + final var entityBinding = manyToOne.getMetadata().getEntityBinding( manyToOne.getReferencedEntityName() ); if ( referencedPropertyName == null ) { SelectablePath bidirectionalAttributeName = null; - final String propertyPath = bootValue.getPropertyName() == null - ? name - : bootValue.getPropertyName(); + final String propertyPath = + bootValue.getPropertyName() == null + ? name + : bootValue.getPropertyName(); if ( cardinality == Cardinality.LOGICAL_ONE_TO_ONE ) { boolean hasJoinTable = false; // Handle join table cases @@ -317,16 +311,17 @@ && equal( join.getKey(), manyToOne ) ) { entityBinding.getPropertyClosure() ); } - this.bidirectionalAttributePath = bidirectionalAttributeName; + bidirectionalAttributePath = bidirectionalAttributeName; } else { // Only set the bidirectional attribute name if the referenced property can actually be circular i.e. an entity type - final Property property = entityBinding.getProperty( referencedPropertyName ); - this.hasJoinTable = cardinality == Cardinality.LOGICAL_ONE_TO_ONE - && property != null - && property.getValue() instanceof ManyToOne manyToOneValue - && manyToOneValue.isLogicalOneToOne(); - this.bidirectionalAttributePath = + final var property = entityBinding.getProperty( referencedPropertyName ); + hasJoinTable = + cardinality == Cardinality.LOGICAL_ONE_TO_ONE + && property != null + && property.getValue() instanceof ManyToOne manyToOneValue + && manyToOneValue.isLogicalOneToOne(); + bidirectionalAttributePath = property != null && property.getValue().getType() instanceof EntityType ? SelectablePath.parse( referencedPropertyName ) : null; @@ -335,23 +330,19 @@ && equal( join.getKey(), manyToOne ) ) { isKeyTableNullable = true; } else { - final String targetTableName = MappingModelCreationHelper.getTableIdentifierExpression( - manyToOne.getTable(), - declaringEntityPersister.getFactory() - ); + final String targetTableName = + MappingModelCreationHelper.getTableIdentifierExpression( manyToOne.getTable(), + declaringEntityPersister.getFactory() ); if ( CollectionPart.Nature.fromNameExact( navigableRole.getParent().getLocalName() ) != null ) { // * the to-one's parent is directly a collection element or index // * therefore, its parent-parent should be the collection itself - final PluralAttributeMapping pluralAttribute = (PluralAttributeMapping) declaringEntityPersister.findByPath( - navigableRole.getParent() - .getParent() - .getFullPath() - .substring( declaringEntityPersister.getNavigableRole() - .getFullPath() - .length() + 1 ) ); + final String path = + navigableRole.getParent().getParent().getFullPath() + .substring( declaringEntityPersister.getNavigableRole().getFullPath().length() + 1 ); + final var pluralAttribute = (PluralAttributeMapping) declaringEntityPersister.findByPath( path ); assert pluralAttribute != null; - final AbstractCollectionPersister persister = (AbstractCollectionPersister) pluralAttribute.getCollectionDescriptor(); + final var persister = (AbstractCollectionPersister) pluralAttribute.getCollectionDescriptor(); isKeyTableNullable = !persister.getTableName().equals( targetTableName ); } else { @@ -413,13 +404,12 @@ class PrimaryKey implements Serializable { the navigable path is NavigablePath(Card.fields.{element}.{id}.card) and it does not contain the "primaryKey" part, so in order to recognize the bidirectionality the "primaryKey." is removed from the otherSidePropertyName value. */ - final OneToOne oneToOne = (OneToOne) bootValue; - if ( oneToOne.getMappedByProperty() == null ) { - this.bidirectionalAttributePath = SelectablePath.parse( referencedPropertyName ); - } - else { - this.bidirectionalAttributePath = SelectablePath.parse( oneToOne.getMappedByProperty() ); - } + final var oneToOne = (OneToOne) bootValue; + final String mappedByProperty = oneToOne.getMappedByProperty(); + bidirectionalAttributePath = + mappedByProperty == null + ? SelectablePath.parse( referencedPropertyName ) + : SelectablePath.parse( mappedByProperty ); notFoundAction = null; isKeyTableNullable = isNullable(); isOptional = !bootValue.isConstrained(); @@ -441,19 +431,18 @@ the navigable path is NavigablePath(Card.fields.{element}.{id}.card) and it does if ( referencedPropertyName == null ) { final Set targetKeyPropertyNames = new HashSet<>( 2 ); targetKeyPropertyNames.add( EntityIdentifierMapping.ID_ROLE_NAME ); - final PersistentClass entityBinding = bootValue.getBuildingContext().getMetadataCollector() - .getEntityBinding( entityMappingType.getEntityName() ); - final Type propertyType; - if ( entityBinding.getIdentifierMapper() == null ) { - propertyType = entityBinding.getIdentifier().getType(); - } - else { - propertyType = entityBinding.getIdentifierMapper().getType(); - } + final var entityBinding = + bootValue.getBuildingContext().getMetadataCollector() + .getEntityBinding( entityMappingType.getEntityName() ); + final var identifierMapper = entityBinding.getIdentifierMapper(); + final Type propertyType = + identifierMapper == null + ? entityBinding.getIdentifier().getType() + : identifierMapper.getType(); if ( entityBinding.getIdentifierProperty() == null ) { if ( propertyType instanceof ComponentType compositeType && compositeType.isEmbedded() && compositeType.getPropertyNames().length == 1 ) { - this.targetKeyPropertyName = compositeType.getPropertyNames()[0]; + targetKeyPropertyName = compositeType.getPropertyNames()[0]; addPrefixedPropertyPaths( targetKeyPropertyNames, targetKeyPropertyName, @@ -468,7 +457,7 @@ the navigable path is NavigablePath(Card.fields.{element}.{id}.card) and it does ); } else { - this.targetKeyPropertyName = EntityIdentifierMapping.ID_ROLE_NAME; + targetKeyPropertyName = EntityIdentifierMapping.ID_ROLE_NAME; addPrefixedPropertyPaths( targetKeyPropertyNames, null, @@ -478,7 +467,7 @@ the navigable path is NavigablePath(Card.fields.{element}.{id}.card) and it does } } else { - this.targetKeyPropertyName = entityBinding.getIdentifierProperty().getName(); + targetKeyPropertyName = entityBinding.getIdentifierProperty().getName(); addPrefixedPropertyPaths( targetKeyPropertyNames, targetKeyPropertyName, @@ -489,8 +478,9 @@ the navigable path is NavigablePath(Card.fields.{element}.{id}.card) and it does this.targetKeyPropertyNames = targetKeyPropertyNames; } else { - final PersistentClass entityBinding = bootValue.getBuildingContext().getMetadataCollector() - .getEntityBinding( entityMappingType.getEntityName() ); + final var entityBinding = + bootValue.getBuildingContext().getMetadataCollector() + .getEntityBinding( entityMappingType.getEntityName() ); final Type propertyType = entityBinding.getRecursiveProperty( referencedPropertyName ).getType(); if ( bootValue.isReferenceToPrimaryKey() ) { this.targetKeyPropertyName = referencedPropertyName; @@ -586,7 +576,7 @@ private static SelectablePath findBidirectionalOneToManyAttributeName( if ( value instanceof Collection collection ) { if ( propertyPath.equals( collection.getMappedByProperty() ) && collection.getElement().getType().getName() - .equals( declaringType.getJavaType().getTypeName() ) ) { + .equals( declaringType.getJavaType().getTypeName() ) ) { return parentSelectablePath == null ? SelectablePath.parse( property.getName() ) : parentSelectablePath.append( property.getName() ); @@ -604,14 +594,15 @@ private SelectablePath findBidirectionalOneToOneAttributeName( for ( Property property : properties ) { final Value value = property.getValue(); if ( value instanceof Component component ) { - final SelectablePath bidirectionalAttributeName = findBidirectionalOneToOneAttributeName( - propertyPath, - declaringType, - parentSelectablePath == null - ? SelectablePath.parse( property.getName() ) - : parentSelectablePath.append( property.getName() ), - component.getProperties() - ); + final var bidirectionalAttributeName = + findBidirectionalOneToOneAttributeName( + propertyPath, + declaringType, + parentSelectablePath == null + ? SelectablePath.parse( property.getName() ) + : parentSelectablePath.append( property.getName() ), + component.getProperties() + ); if ( bidirectionalAttributeName != null ) { return bidirectionalAttributeName; } @@ -643,10 +634,8 @@ private static TableGroupProducer resolveDeclaringTableGroupProducer(EntityPersi NavigableRole parentRole = navigableRole.getParent(); String collectionRole = null; do { - final CollectionPart.Nature nature = CollectionPart.Nature.fromNameExact( - parentRole.getLocalName() - ); - if (nature != null) { + final var nature = CollectionPart.Nature.fromNameExact( parentRole.getLocalName() ); + if ( nature != null ) { collectionRole = parentRole.getParent().getFullPath(); break; } @@ -696,15 +685,15 @@ private ToOneAttributeMapping( } private static boolean equal(Value lhsValue, Value rhsValue) { - List lhsColumns = lhsValue.getSelectables(); - List rhsColumns = rhsValue.getSelectables(); + final var lhsColumns = lhsValue.getSelectables(); + final var rhsColumns = rhsValue.getSelectables(); if ( lhsColumns.size() != rhsColumns.size() ) { return false; } else { for ( int i=0; i determineCircularKeyResult( FetchParent fetchParent, NavigablePath fetchablePath, DomainResultCreationState creationState) { - final FromClauseAccess fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess(); - final TableGroup parentTableGroup = fromClauseAccess.getTableGroup( fetchParent.getNavigablePath() ); + final var fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess(); + final var parentTableGroup = fromClauseAccess.getTableGroup( fetchParent.getNavigablePath() ); assert !creationState.isResolvingCircularFetch(); try { creationState.setResolvingCircularFetch( true ); @@ -1194,11 +1182,11 @@ class Mother { this.mappedBy = "biologicalChild" parent.getFullPath() = "Mother.biologicalChild" */ - final NavigablePath grandparentNavigablePath = parentNavigablePath.getParent(); + final var grandparentNavigablePath = parentNavigablePath.getParent(); if ( parentNavigablePath.getLocalName().equals( CollectionPart.Nature.ELEMENT.getName() ) && grandparentNavigablePath != null && grandparentNavigablePath.isSuffix( bidirectionalAttributePath ) ) { - final NavigablePath parentPath = grandparentNavigablePath.getParent(); + final var parentPath = grandparentNavigablePath.getParent(); // This can be null for a collection loader if ( parentPath == null ) { return grandparentNavigablePath.getFullPath().equals( @@ -1319,8 +1307,8 @@ else if ( CollectionPart.Nature.fromNameExact( parentNavigablePath.getLocalName( // The problem with a bidirectional fetch though is that we can't find an initializer // because there is none, as we don't fetch the data of the parent node. // To avoid creating another join, we create a special join fetch that uses the existing joined data - final FromClauseAccess fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess(); - final TableGroup tableGroup = fromClauseAccess.getTableGroup( referencedNavigablePath ); + final var fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess(); + final var tableGroup = fromClauseAccess.getTableGroup( referencedNavigablePath ); fromClauseAccess.registerTableGroup( fetchablePath, tableGroup ); // Register a PROJECTION usage as we're effectively selecting the bidirectional association creationState.getSqlAstCreationState().registerEntityNameUsage( @@ -1342,8 +1330,8 @@ else if ( CollectionPart.Nature.fromNameExact( parentNavigablePath.getLocalName( else { // We get here is this is a lazy collection initialization for which we know the owner is in the PC // So we create a delayed fetch, as we are sure to find the entity in the PC - final FromClauseAccess fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess(); - final TableGroup parentTableGroup = fromClauseAccess.getTableGroup( parentNavigablePath ); + final var fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess(); + final var parentTableGroup = fromClauseAccess.getTableGroup( parentNavigablePath ); final DomainResult domainResult; if ( sideNature == ForeignKeyDescriptor.Nature.KEY ) { domainResult = foreignKeyDescriptor.createKeyDomainResult( @@ -1532,14 +1520,14 @@ public EntityFetch generateFetch( String resultVariable, DomainResultCreationState creationState) { - final SqlAstCreationState sqlAstCreationState = creationState.getSqlAstCreationState(); - final FromClauseAccess fromClauseAccess = sqlAstCreationState.getFromClauseAccess(); + final var sqlAstCreationState = creationState.getSqlAstCreationState(); + final var fromClauseAccess = sqlAstCreationState.getFromClauseAccess(); - final TableGroup parentTableGroup = fromClauseAccess.getTableGroup( fetchParent.getNavigablePath() ); + final var parentTableGroup = fromClauseAccess.getTableGroup( fetchParent.getNavigablePath() ); - final NavigablePath parentNavigablePath = fetchablePath.getParent(); + final var parentNavigablePath = fetchablePath.getParent(); assert parentNavigablePath.equals( fetchParent.getNavigablePath() ) - || fetchParent.getNavigablePath() instanceof TreatedNavigablePath + || fetchParent.getNavigablePath() instanceof TreatedNavigablePath && parentNavigablePath.equals( fetchParent.getNavigablePath().getRealParent() ); /* @@ -1567,9 +1555,10 @@ public static class EntityB { having the left join we don't want to add an extra implicit join that will be translated into an SQL inner join (see HHH-15342) */ - final ForeignKeyDescriptor.Nature resolvingKeySideOfForeignKey = creationState.getCurrentlyResolvingForeignKeyPart(); + final var resolvingKeySideOfForeignKey = creationState.getCurrentlyResolvingForeignKeyPart(); final ForeignKeyDescriptor.Nature side; - if ( resolvingKeySideOfForeignKey == ForeignKeyDescriptor.Nature.KEY && this.sideNature == ForeignKeyDescriptor.Nature.TARGET ) { + if ( resolvingKeySideOfForeignKey == ForeignKeyDescriptor.Nature.KEY + && this.sideNature == ForeignKeyDescriptor.Nature.TARGET ) { // If we are currently resolving the key part of a foreign key we do not want to add joins. // So if the lhs of this association is the target of the FK, we have to use the KEY part to avoid a join side = ForeignKeyDescriptor.Nature.KEY; @@ -1579,7 +1568,7 @@ public static class EntityB { } if ( fetchTiming == FetchTiming.IMMEDIATE && selected || !creationState.getSqlAstCreationState().isProcedureOrNativeQuery() && needsJoinFetch( side ) ) { - final TableGroup tableGroup = determineTableGroupForFetch( + final var tableGroup = determineTableGroupForFetch( fetchablePath, fetchParent, parentTableGroup, @@ -1658,9 +1647,10 @@ else if ( hasNotFoundAction() final DomainResult keyResult; if ( side == ForeignKeyDescriptor.Nature.KEY ) { - final TableGroup tableGroup = sideNature == ForeignKeyDescriptor.Nature.KEY - ? createTableGroupForDelayedFetch( fetchablePath, parentTableGroup, null, creationState ) - : parentTableGroup; + final var tableGroup = + sideNature == ForeignKeyDescriptor.Nature.KEY + ? createTableGroupForDelayedFetch( fetchablePath, parentTableGroup, null, creationState ) + : parentTableGroup; keyResult = foreignKeyDescriptor.createKeyDomainResult( fetchablePath, tableGroup, @@ -1669,9 +1659,10 @@ else if ( hasNotFoundAction() ); } else { - final TableGroup tableGroup = sideNature == ForeignKeyDescriptor.Nature.TARGET - ? parentTableGroup - : createTableGroupForDelayedFetch( fetchablePath, parentTableGroup, null, creationState ); + final var tableGroup = + sideNature == ForeignKeyDescriptor.Nature.TARGET + ? parentTableGroup + : createTableGroupForDelayedFetch( fetchablePath, parentTableGroup, null, creationState ); keyResult = foreignKeyDescriptor.createTargetDomainResult( fetchablePath, tableGroup, @@ -1711,11 +1702,11 @@ private boolean needsJoinFetch(ForeignKeyDescriptor.Nature side) { if ( side == ForeignKeyDescriptor.Nature.TARGET ) { // With composite identifier if the target model part doesn't correspond to the identifier of the target entity mapping // we must eagerly fetch with a join (subselect would still cause problems). - final EntityIdentifierMapping identifier = entityMappingType.getIdentifierMapping(); + final var identifier = entityMappingType.getIdentifierMapping(); if ( identifier instanceof BasicEntityIdentifierMappingImpl ) { return false; } - final ValuedModelPart targetPart = foreignKeyDescriptor.getTargetPart(); + final var targetPart = foreignKeyDescriptor.getTargetPart(); if ( identifier != targetPart ) { // If the identifier and the target part of the same class, we can preserve laziness as deferred loading will still work return identifier.getExpressibleJavaType().getJavaTypeClass() != targetPart.getExpressibleJavaType() @@ -1742,8 +1733,8 @@ else if ( !entityMappingType.isConcreteProxy() ) { // When resolving the concrete entity type we can preserve laziness // and handle not found actions based on the discriminator value return hasNotFoundAction() - || entityMappingType.getSoftDeleteMapping() != null - || ( !entityMappingType.getEntityPersister().isInstrumented() + || entityMappingType.getSoftDeleteMapping() != null + || ( !entityMappingType.getEntityPersister().isInstrumented() && cardinality == Cardinality.ONE_TO_ONE && isOptional ); } else { @@ -1758,13 +1749,13 @@ private TableGroup determineTableGroupForFetch( String resultVariable, FromClauseAccess fromClauseAccess, DomainResultCreationState creationState) { - final FetchableContainer parentEntityType = fetchParent.getReferencedMappingType(); - final SqlAstJoinType joinType = + final var parentEntityType = fetchParent.getReferencedMappingType(); + final var joinType = parentEntityType instanceof JoinedSubclassEntityPersister joinedSubclassEntityPersister && joinedSubclassEntityPersister.findDeclaredAttributeMapping( getPartName() ) == null ? getJoinTypeForFetch( fetchablePath, parentTableGroup ) : null; - final TableGroup existingTableGroup = fromClauseAccess.findTableGroupForGetOrCreate( fetchablePath ); + final var existingTableGroup = fromClauseAccess.findTableGroupForGetOrCreate( fetchablePath ); if ( existingTableGroup != null && existingTableGroup.getModelPart() == this ) { return existingTableGroup; } @@ -1773,7 +1764,7 @@ private TableGroup determineTableGroupForFetch( // and note that we prefer reusing an inner over a left join, // because a left join might stay uninitialized if unused TableGroup leftJoined = null; - for ( TableGroupJoin tableGroupJoin : parentTableGroup.getTableGroupJoins() ) { + for ( var tableGroupJoin : parentTableGroup.getTableGroupJoins() ) { if ( tableGroupJoin.getJoinedGroup().getModelPart() == this ) { switch ( tableGroupJoin.getJoinType() ) { case INNER: @@ -1800,7 +1791,7 @@ && isSimpleJoinPredicate( tableGroupJoin.getPredicate() ) ) { return leftJoined; } - final TableGroupJoin tableGroupJoin = createTableGroupJoin( + final var tableGroupJoin = createTableGroupJoin( fetchablePath, parentTableGroup, resultVariable, @@ -1811,7 +1802,7 @@ && isSimpleJoinPredicate( tableGroupJoin.getPredicate() ) ) { creationState.getSqlAstCreationState() ); parentTableGroup.addTableGroupJoin( tableGroupJoin ); - final TableGroup joinedGroup = tableGroupJoin.getJoinedGroup(); + final var joinedGroup = tableGroupJoin.getJoinedGroup(); fromClauseAccess.registerTableGroup( fetchablePath, joinedGroup ); return joinedGroup; } @@ -1823,7 +1814,7 @@ private TableGroup createTableGroupForDelayedFetch( String resultVariable, DomainResultCreationState creationState) { // Check if we can reuse a table group join of the parent - final TableGroup compatibleTableGroup = parentTableGroup.findCompatibleJoinedGroup( + final var compatibleTableGroup = parentTableGroup.findCompatibleJoinedGroup( this, SqlAstJoinType.LEFT ); @@ -1831,7 +1822,7 @@ private TableGroup createTableGroupForDelayedFetch( return compatibleTableGroup; } // We have to create the table group that points to the target so that table reference resolving works - final TableGroupJoin tableGroupJoin = createTableGroupJoin( + final var tableGroupJoin = createTableGroupJoin( fetchablePath, parentTableGroup, resultVariable, @@ -1842,10 +1833,8 @@ private TableGroup createTableGroupForDelayedFetch( creationState.getSqlAstCreationState() ); parentTableGroup.addTableGroupJoin( tableGroupJoin ); - creationState.getSqlAstCreationState().getFromClauseAccess().registerTableGroup( - fetchablePath, - tableGroupJoin.getJoinedGroup() - ); + creationState.getSqlAstCreationState().getFromClauseAccess() + .registerTableGroup( fetchablePath, tableGroupJoin.getJoinedGroup() ); return tableGroupJoin.getJoinedGroup(); } @@ -1861,12 +1850,9 @@ private boolean isSelectByUniqueKey(ForeignKeyDescriptor.Nature side) { else { // case 1.1 // Make sure the entity identifier is not a target key property i.e. this really is a unique key mapping - return bidirectionalAttributePath != null && ( - !( entityMappingType.getIdentifierMapping() instanceof SingleAttributeIdentifierMapping ) - || !targetKeyPropertyNames.contains( - entityMappingType.getIdentifierMapping().getAttributeName() - ) - ); + return bidirectionalAttributePath != null + && ( !( entityMappingType.getIdentifierMapping() instanceof SingleAttributeIdentifierMapping ) + || !targetKeyPropertyNames.contains( entityMappingType.getIdentifierMapping().getAttributeName() ) ); } } @@ -1928,7 +1914,7 @@ private EntityFetch withRegisteredAssociationKeys( final boolean added = creationState.registerVisitedAssociationKey( foreignKeyDescriptor.getAssociationKey() ); AssociationKey additionalAssociationKey = null; if ( cardinality == Cardinality.LOGICAL_ONE_TO_ONE && bidirectionalAttributePath != null ) { - final ModelPart bidirectionalModelPart = entityMappingType.findByPath( bidirectionalAttributePath ); + final var bidirectionalModelPart = entityMappingType.findByPath( bidirectionalAttributePath ); // Add the inverse association key side as well to be able to resolve to a CircularFetch if ( bidirectionalModelPart instanceof ToOneAttributeMapping bidirectionalAttribute ) { assert bidirectionalModelPart.getPartMappingType() == declaringTableGroupProducer; @@ -1962,9 +1948,8 @@ else if ( parentTableGroup.getModelPart() instanceof CollectionPart ) { } else { if ( parentTableGroup.canUseInnerJoins() ) { - final Class attributeDeclaringType = declaringTableGroupProducer.getJavaType().getJavaTypeClass(); - final Class parentTableGroupType = parentTableGroup.getModelPart().getJavaType().getJavaTypeClass(); - + final var attributeDeclaringType = declaringTableGroupProducer.getJavaType().getJavaTypeClass(); + final var parentTableGroupType = parentTableGroup.getModelPart().getJavaType().getJavaTypeClass(); // This attribute mapping must be declared on the parent table group type or one of its super types // If not, this is a fetch for a subtype of the parent table group, which might be left joined if ( attributeDeclaringType.isAssignableFrom( parentTableGroupType ) ) { @@ -2011,8 +1996,8 @@ public TableGroupJoin createTableGroupJoin( // This is vital for the map key property check that comes next assert !( lhs instanceof PluralTableGroup ); - final FromClauseAccess fromClauseAccess = creationState.getFromClauseAccess(); - final SqlAstJoinType joinType = determineSqlJoinType( lhs, requestedJoinType, fetched ); + final var fromClauseAccess = creationState.getFromClauseAccess(); + final var joinType = determineSqlJoinType( lhs, requestedJoinType, fetched ); // If a parent is a collection part, there is no custom predicate and the join is INNER or LEFT // we check if this attribute is the map key property to reuse the existing index table group @@ -2046,22 +2031,18 @@ public TableGroupJoin createTableGroupJoin( } if ( CollectionPart.Nature.ELEMENT.getName().equals( parentTableGroup.getNavigablePath().getLocalName() ) ) { - final NavigablePath parentParentPath = parentTableGroup.getNavigablePath().getParent(); - final PluralTableGroup pluralTableGroup = (PluralTableGroup) fromClauseAccess.findTableGroup( parentParentPath ); + final var parentParentPath = parentTableGroup.getNavigablePath().getParent(); + final var pluralTableGroup = (PluralTableGroup) fromClauseAccess.findTableGroup( parentParentPath ); if ( pluralTableGroup != null ) { - final String indexPropertyName = pluralTableGroup.getModelPart() - .getIndexMetadata() - .getIndexPropertyName(); - final String pathName; - if ( embeddablePathSb != null ) { - pathName = embeddablePathSb.append( getAttributeName() ).toString(); - } - else { - pathName = getAttributeName(); - } - + final String indexPropertyName = + pluralTableGroup.getModelPart().getIndexMetadata() + .getIndexPropertyName(); + final String pathName = + embeddablePathSb != null + ? embeddablePathSb.append( getAttributeName() ).toString() + : getAttributeName(); if ( pathName.equals( indexPropertyName ) ) { - final TableGroup indexTableGroup = pluralTableGroup.getIndexTableGroup(); + final var indexTableGroup = pluralTableGroup.getIndexTableGroup(); // If this is the map key property, we can reuse the index table group initializeIfNeeded( lhs, requestedJoinType, indexTableGroup ); return new TableGroupJoin( @@ -2082,7 +2063,7 @@ public TableGroupJoin createTableGroupJoin( } } - final LazyTableGroup lazyTableGroup = createRootTableGroupJoin( + final var lazyTableGroup = createRootTableGroupJoin( navigablePath, lhs, explicitSourceAlias, @@ -2093,7 +2074,7 @@ public TableGroupJoin createTableGroupJoin( creationState ); - final TableGroupJoin join = new TableGroupJoin( + final var join = new TableGroupJoin( navigablePath, // Avoid checking for nested joins in here again, since this is already done in createRootTableGroupJoin // and simply rely on the canUseInnerJoins flag instead for override the join type to LEFT @@ -2103,7 +2084,7 @@ public TableGroupJoin createTableGroupJoin( lazyTableGroup, null ); - final TableReference lhsTableReference = lhs.resolveTableReference( + final var lhsTableReference = lhs.resolveTableReference( navigablePath, this, identifyingColumnsTableExpression @@ -2130,8 +2111,9 @@ public TableGroupJoin createTableGroupJoin( // Note specifically we only apply `@Filter` restrictions that are applyToLoadByKey = true // to make the behavior consistent with lazy loading of an association - if ( getAssociatedEntityMappingType().getEntityPersister().hasFilterForLoadByKey() ) { - getAssociatedEntityMappingType().applyBaseRestrictions( + final var associatedEntityMappingType = getAssociatedEntityMappingType(); + if ( associatedEntityMappingType.getEntityPersister().hasFilterForLoadByKey() ) { + associatedEntityMappingType.applyBaseRestrictions( join::applyPredicate, tableGroup, true, @@ -2141,22 +2123,23 @@ public TableGroupJoin createTableGroupJoin( creationState ); } - getAssociatedEntityMappingType().applyWhereRestrictions( + associatedEntityMappingType.applyWhereRestrictions( join::applyPredicate, tableGroup, true, creationState ); - if ( getAssociatedEntityMappingType().getSuperMappingType() != null && !creationState.supportsEntityNameUsage() ) { - getAssociatedEntityMappingType().applyDiscriminator( null, null, tableGroup, creationState ); + if ( associatedEntityMappingType.getSuperMappingType() != null + && !creationState.supportsEntityNameUsage() ) { + associatedEntityMappingType.applyDiscriminator( null, null, tableGroup, creationState ); } - final SoftDeleteMapping softDeleteMapping = getAssociatedEntityMappingType().getSoftDeleteMapping(); + final var softDeleteMapping = associatedEntityMappingType.getSoftDeleteMapping(); if ( softDeleteMapping != null ) { // add the restriction final TableReference tableReference = lazyTableGroup.resolveTableReference( navigablePath, - getAssociatedEntityMappingType().getSoftDeleteTableDetails().getTableName() + associatedEntityMappingType.getSoftDeleteTableDetails().getTableName() ); join.applyPredicate( softDeleteMapping.createNonDeletedRestriction( tableReference, @@ -2174,12 +2157,12 @@ public SqlAstJoinType determineSqlJoinType(TableGroup lhs, @Nullable SqlAstJoinT if ( requestedJoinType != null ) { return requestedJoinType; } - if ( fetched ) { return getDefaultSqlAstJoinType( lhs ); } - - return SqlAstJoinType.INNER; + else { + return SqlAstJoinType.INNER; + } } @Override @@ -2199,9 +2182,9 @@ public LazyTableGroup createRootTableGroupJoin( creationState.getSqlAliasBaseGenerator() ); - final SoftDeleteMapping softDeleteMapping = getAssociatedEntityMappingType().getSoftDeleteMapping(); + final var softDeleteMapping = getAssociatedEntityMappingType().getSoftDeleteMapping(); final boolean canUseInnerJoin; - final SqlAstJoinType currentlyProcessingJoinType = + final var currentlyProcessingJoinType = creationState instanceof SqmToSqlAstConverter sqmToSqlAstConverter ? sqmToSqlAstConverter.getCurrentlyProcessingJoinType() : null; @@ -2214,10 +2197,10 @@ public LazyTableGroup createRootTableGroupJoin( } TableGroup realParentTableGroup = lhs; - final FromClauseAccess fromClauseAccess = creationState.getFromClauseAccess(); + final var fromClauseAccess = creationState.getFromClauseAccess(); while ( realParentTableGroup.getModelPart() instanceof EmbeddableValuedModelPart ) { - final NavigablePath parentNavigablePath = realParentTableGroup.getNavigablePath(); - final TableGroup tableGroup = fromClauseAccess.findTableGroup( parentNavigablePath.getParent() ); + final var parentNavigablePath = realParentTableGroup.getNavigablePath(); + final var tableGroup = fromClauseAccess.findTableGroup( parentNavigablePath.getParent() ); if ( tableGroup == null ) { assert parentNavigablePath.getLocalName().equals( ForeignKeyDescriptor.PART_NAME ) || parentNavigablePath.getLocalName().equals( ForeignKeyDescriptor.TARGET_PART_NAME ); @@ -2242,7 +2225,7 @@ public LazyTableGroup createRootTableGroupJoin( tableGroupProducer = this; } - final LazyTableGroup lazyTableGroup = new LazyTableGroup( + final var lazyTableGroup = new LazyTableGroup( canUseInnerJoin, navigablePath, fetched, @@ -2263,11 +2246,8 @@ public LazyTableGroup createRootTableGroupJoin( ); if ( predicateConsumer != null ) { - final TableReference lhsTableReference = lhs.resolveTableReference( - navigablePath, - identifyingColumnsTableExpression - ); - + final var lhsTableReference = + lhs.resolveTableReference( navigablePath, identifyingColumnsTableExpression ); lazyTableGroup.setTableGroupInitializerCallback( tableGroup -> predicateConsumer.accept( foreignKeyDescriptor.generateJoinPredicate( @@ -2280,14 +2260,11 @@ public LazyTableGroup createRootTableGroupJoin( if ( fetched && softDeleteMapping != null ) { // add the restriction - final TableReference tableReference = lazyTableGroup.resolveTableReference( - navigablePath, - getAssociatedEntityMappingType().getSoftDeleteTableDetails().getTableName() - ); - predicateConsumer.accept( softDeleteMapping.createNonDeletedRestriction( - tableReference, - creationState.getSqlExpressionResolver() - ) ); + final var tableReference = + lazyTableGroup.resolveTableReference( navigablePath, + getAssociatedEntityMappingType().getSoftDeleteTableDetails().getTableName() ); + predicateConsumer.accept( softDeleteMapping.createNonDeletedRestriction( tableReference, + creationState.getSqlExpressionResolver() ) ); } } @@ -2308,21 +2285,20 @@ public boolean canUseParentTableGroup( NavigablePath navigablePath, ValuedModelPart valuedModelPart) { return producer == this - && sideNature == ForeignKeyDescriptor.Nature.KEY - && foreignKeyDescriptor.isKeyPart( valuedModelPart ); + && sideNature == ForeignKeyDescriptor.Nature.KEY + && foreignKeyDescriptor.isKeyPart( valuedModelPart ); } private void initializeIfNeeded(TableGroup lhs, SqlAstJoinType sqlAstJoinType, TableGroup tableGroup) { if ( sqlAstJoinType == SqlAstJoinType.INNER && ( isNullable || !lhs.canUseInnerJoins() ) ) { if ( hasJoinTable ) { // Set the join type of the table reference join to INNER to retain cardinality expectation - final TableReference lhsTableReference = lhs.resolveTableReference( - tableGroup.getNavigablePath(), - identifyingColumnsTableExpression - ); - final List tableReferenceJoins = lhs.getTableReferenceJoins(); + final var lhsTableReference = + lhs.resolveTableReference( tableGroup.getNavigablePath(), + identifyingColumnsTableExpression ); + final var tableReferenceJoins = lhs.getTableReferenceJoins(); for ( int i = 0; i < tableReferenceJoins.size(); i++ ) { - final TableReferenceJoin tableReferenceJoin = tableReferenceJoins.get( i ); + final var tableReferenceJoin = tableReferenceJoins.get( i ); if ( tableReferenceJoin.getJoinType() != SqlAstJoinType.INNER && tableReferenceJoin.getJoinedTableReference() == lhsTableReference ) { tableReferenceJoins.set( @@ -2346,7 +2322,7 @@ private void initializeIfNeeded(TableGroup lhs, SqlAstJoinType sqlAstJoinType, T } private SqlAstJoinType getJoinTypeForFetch(NavigablePath navigablePath, TableGroup tableGroup) { - for ( TableGroupJoin tableGroupJoin : tableGroup.getTableGroupJoins() ) { + for ( var tableGroupJoin : tableGroup.getTableGroupJoins() ) { if ( tableGroupJoin.getNavigablePath().equals( navigablePath ) ) { return tableGroupJoin.getJoinType(); } @@ -2361,10 +2337,9 @@ public TableGroup createTableGroupInternal( String sourceAlias, final SqlAliasBase sqlAliasBase, SqlAstCreationState creationState) { - final TableReference primaryTableReference = getEntityMappingType().createPrimaryTableReference( - sqlAliasBase, - creationState - ); + final var primaryTableReference = + getEntityMappingType() + .createPrimaryTableReference( sqlAliasBase, creationState ); return new StandardTableGroup( canUseInnerJoins, @@ -2463,10 +2438,8 @@ protected Object extractValue(Object domainValue, SharedSessionContractImplement if ( referencedPropertyName != null ) { domainValue = lazyInitialize( domainValue ); - assert getAssociatedEntityMappingType() - .getRepresentationStrategy() - .getInstantiator() - .isInstance( domainValue ); + assert getAssociatedEntityMappingType().getRepresentationStrategy() + .getInstantiator().isInstance( domainValue ); return extractAttributePathValue( domainValue, getAssociatedEntityMappingType(), referencedPropertyName ); } @@ -2478,11 +2451,8 @@ assert getAssociatedEntityMappingType() * when possible. */ protected Object lazyInitialize(Object domainValue) { - final LazyInitializer lazyInitializer = HibernateProxy.extractLazyInitializer( domainValue ); - if ( lazyInitializer != null ) { - return lazyInitializer.getImplementation(); - } - return domainValue; + final var lazyInitializer = HibernateProxy.extractLazyInitializer( domainValue ); + return lazyInitializer == null ? domainValue : lazyInitializer.getImplementation(); } protected static Object extractAttributePathValue(Object domainValue, EntityMappingType entityType, String attributePath) { @@ -2497,7 +2467,7 @@ protected static Object extractAttributePathValue(Object domainValue, EntityMapp assert managedType != null; final String pathPart = pathParts[ i ]; - final AttributeMapping attributeMapping = managedType.findAttributeMapping( pathPart ); + final var attributeMapping = managedType.findAttributeMapping( pathPart ); value = attributeMapping.getValue( value ); managedType = attributeMapping.getMappedType() instanceof ManagedMappingType managedMappingType @@ -2590,19 +2560,12 @@ public Object disassemble(Object value, SharedSessionContractImplementor session @Override public void addToCacheKey(MutableCacheKeyBuilder cacheKey, Object value, SharedSessionContractImplementor session) { - final Object cacheValue; + final Object cacheValue = + value != null && foreignKeyDescriptor.getJavaType().getJavaTypeClass() == value.getClass() + ? value + : foreignKeyDescriptor.getAssociationKeyFromSide( value, sideNature.inverse(), session ); // the value may come from a database snapshot, in this case it corresponds to the value of the key and can be // added to the cache key - if ( value != null && foreignKeyDescriptor.getJavaType().getJavaTypeClass() == value.getClass() ) { - cacheValue = value; - } - else { - cacheValue = foreignKeyDescriptor.getAssociationKeyFromSide( - value, - sideNature.inverse(), - session - ); - } foreignKeyDescriptor.addToCacheKey( cacheKey, cacheValue, session ); } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/UnifiedAnyDiscriminatorConverter.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/UnifiedAnyDiscriminatorConverter.java index 3bf13b532d98..0b4dc5e05851 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/UnifiedAnyDiscriminatorConverter.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/UnifiedAnyDiscriminatorConverter.java @@ -5,7 +5,6 @@ package org.hibernate.metamodel.mapping.internal; import org.hibernate.HibernateException; -import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.metamodel.internal.FullNameImplicitDiscriminatorStrategy; import org.hibernate.metamodel.mapping.DiscriminatorConverter; import org.hibernate.metamodel.mapping.DiscriminatorValueDetails; @@ -13,7 +12,6 @@ import org.hibernate.metamodel.model.domain.NavigableRole; import org.hibernate.metamodel.spi.ImplicitDiscriminatorStrategy; import org.hibernate.metamodel.spi.MappingMetamodelImplementor; -import org.hibernate.persister.entity.EntityPersister; import org.hibernate.type.descriptor.java.CharacterJavaType; import org.hibernate.type.descriptor.java.JavaType; import org.hibernate.type.descriptor.java.StringJavaType; @@ -22,6 +20,7 @@ import java.util.function.Consumer; import java.util.function.Function; +import static org.hibernate.internal.util.collections.CollectionHelper.concurrentMap; import static org.hibernate.persister.entity.DiscriminatorHelper.NOT_NULL_DISCRIMINATOR; import static org.hibernate.persister.entity.DiscriminatorHelper.NULL_DISCRIMINATOR; @@ -48,11 +47,11 @@ public UnifiedAnyDiscriminatorConverter( this.implicitValueStrategy = resolveImplicitValueStrategy( implicitValueStrategy, explicitValueMappings ); - this.detailsByValue = CollectionHelper.concurrentMap( explicitValueMappings.size() ); - this.detailsByEntityName = CollectionHelper.concurrentMap( explicitValueMappings.size() ); + detailsByValue = concurrentMap( explicitValueMappings.size() ); + detailsByEntityName = concurrentMap( explicitValueMappings.size() ); explicitValueMappings.forEach( (value,entityName) -> { final String importedEntityName = mappingMetamodel.getImportedName( entityName ); - final EntityPersister entityMapping = mappingMetamodel.getEntityDescriptor( importedEntityName ); + final var entityMapping = mappingMetamodel.getEntityDescriptor( importedEntityName ); register( value, entityMapping ); } ); } @@ -75,7 +74,7 @@ private ImplicitDiscriminatorStrategy resolveImplicitValueStrategy(ImplicitDiscr } private DiscriminatorValueDetails register(Object value, EntityMappingType entityMapping) { - final DiscriminatorValueDetails details = new DiscriminatorValueDetailsImpl( value, entityMapping ); + final var details = new DiscriminatorValueDetailsImpl( value, entityMapping ); detailsByValue.put( value, details ); detailsByEntityName.put( entityMapping.getEntityName(), details ); return details; @@ -95,7 +94,7 @@ public DiscriminatorValueDetails getDetailsForDiscriminatorValue(Object relation return detailsByValue.get( NULL_DISCRIMINATOR ); } - final DiscriminatorValueDetails existing = detailsByValue.get( relationalValue ); + final var existing = detailsByValue.get( relationalValue ); if ( existing != null ) { return existing; } @@ -118,13 +117,14 @@ else if ( getRelationalJavaType() instanceof CharacterJavaType ) { } if ( implicitValueStrategy != null ) { - final EntityMappingType entityMapping = implicitValueStrategy.toEntityMapping( relationalValue, discriminatorRole, mappingMetamodel ); + final var entityMapping = + implicitValueStrategy.toEntityMapping( relationalValue, discriminatorRole, mappingMetamodel ); if ( entityMapping != null ) { return register( relationalValue, entityMapping ); } } - final DiscriminatorValueDetails nonNullMatch = detailsByValue.get( NOT_NULL_DISCRIMINATOR ); + final var nonNullMatch = detailsByValue.get( NOT_NULL_DISCRIMINATOR ); if ( nonNullMatch != null ) { return nonNullMatch; } @@ -134,13 +134,13 @@ else if ( getRelationalJavaType() instanceof CharacterJavaType ) { @Override public DiscriminatorValueDetails getDetailsForEntityName(String entityName) { - final DiscriminatorValueDetails existing = detailsByEntityName.get( entityName ); + final var existing = detailsByEntityName.get( entityName ); if ( existing != null) { return existing; } if ( implicitValueStrategy != null ) { - final EntityMappingType entityMapping = mappingMetamodel.getEntityDescriptor( entityName ); + final var entityMapping = mappingMetamodel.getEntityDescriptor( entityName ); assert entityMapping != null; final Object discriminatorValue = implicitValueStrategy.toDiscriminatorValue( entityMapping, @@ -160,7 +160,7 @@ public void forEachValueDetail(Consumer consumer) { @Override public X fromValueDetails(Function handler) { - for ( DiscriminatorValueDetails valueDetails : detailsByEntityName.values() ) { + for ( var valueDetails : detailsByEntityName.values() ) { final X result = handler.apply( valueDetails ); if ( result != null ) { return result; diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/VirtualIdEmbeddable.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/VirtualIdEmbeddable.java index 84ab5eb895c6..f1f69e3f4a3c 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/VirtualIdEmbeddable.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/VirtualIdEmbeddable.java @@ -6,8 +6,6 @@ import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.mapping.Component; -import org.hibernate.metamodel.mapping.AttributeMapping; -import org.hibernate.metamodel.mapping.AttributeMappingsList; import org.hibernate.metamodel.mapping.EmbeddableMappingType; import org.hibernate.metamodel.mapping.EmbeddableValuedModelPart; import org.hibernate.metamodel.mapping.EntityMappingType; @@ -46,16 +44,16 @@ public VirtualIdEmbeddable( MappingModelCreationProcess creationProcess) { super( new MutableAttributeMappingList( virtualIdSource.getType().getPropertyNames().length ) ); - this.navigableRole = idMapping.getNavigableRole(); this.idMapping = idMapping; - this.representationStrategy = new VirtualIdRepresentationStrategy( + navigableRole = idMapping.getNavigableRole(); + representationStrategy = new VirtualIdRepresentationStrategy( this, identifiedEntityMapping, virtualIdSource, creationProcess.getCreationContext() ); - final CompositeType compositeType = virtualIdSource.getType(); + final var compositeType = virtualIdSource.getType(); ( (CompositeTypeImplementor) compositeType ).injectMappingModelPart( idMapping, creationProcess ); creationProcess.registerInitializationCallback( @@ -165,7 +163,7 @@ public int decompose( else { int span = 0; for ( int i = 0; i < attributeMappings.size(); i++ ) { - final AttributeMapping attributeMapping = attributeMappings.get( i ); + final var attributeMapping = attributeMappings.get( i ); span += attributeMapping.decompose( attributeMapping.getValue( domainValue ), offset + span, @@ -239,15 +237,16 @@ private boolean finishInitialization( @Override public boolean areEqual(@Nullable Object one, @Nullable Object other, SharedSessionContractImplementor session) { - final IdClassEmbeddable idClassEmbeddable = idMapping.getIdClassEmbeddable(); + final var idClassEmbeddable = idMapping.getIdClassEmbeddable(); if ( idClassEmbeddable != null ) { return idClassEmbeddable.areEqual( one, other, session ); } else { - final AttributeMappingsList attributeMappings = getAttributeMappings(); + final var attributeMappings = getAttributeMappings(); for ( int i = 0; i < attributeMappings.size(); i++ ) { - final AttributeMapping attribute = attributeMappings.get( i ); - if ( !attribute.areEqual( attribute.getValue( one ), attribute.getValue( other ), session ) ) { + final var attribute = attributeMappings.get( i ); + if ( !attribute.areEqual( attribute.getValue( one ), + attribute.getValue( other ), session ) ) { return false; } } @@ -257,12 +256,14 @@ public boolean areEqual(@Nullable Object one, @Nullable Object other, SharedSess @Override public int compare(Object value1, Object value2) { - final IdClassEmbeddable idClassEmbeddable = idMapping.getIdClassEmbeddable(); + final var idClassEmbeddable = idMapping.getIdClassEmbeddable(); if ( idClassEmbeddable != null ) { - final AttributeMappingsList attributeMappings = idClassEmbeddable.getAttributeMappings(); + final var attributeMappings = idClassEmbeddable.getAttributeMappings(); for ( int i = 0; i < attributeMappings.size(); i++ ) { - final AttributeMapping attribute = attributeMappings.get( i ); - final int comparison = attribute.compare( attribute.getValue( value1 ), attribute.getValue( value2 ) ); + final var attribute = attributeMappings.get( i ); + final int comparison = + attribute.compare( attribute.getValue( value1 ), + attribute.getValue( value2 ) ); if ( comparison != 0 ) { return comparison; } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/VirtualIdRepresentationStrategy.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/VirtualIdRepresentationStrategy.java index 6411e7fa02b5..77367bf174f9 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/VirtualIdRepresentationStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/VirtualIdRepresentationStrategy.java @@ -6,7 +6,6 @@ import org.hibernate.bytecode.spi.ProxyFactoryFactory; import org.hibernate.bytecode.spi.ReflectionOptimizer; -import org.hibernate.internal.util.ReflectHelper; import org.hibernate.mapping.Component; import org.hibernate.mapping.Property; import org.hibernate.metamodel.RepresentationMode; @@ -21,6 +20,8 @@ import org.hibernate.property.access.spi.PropertyAccess; import org.hibernate.type.descriptor.java.JavaType; +import static org.hibernate.internal.util.ReflectHelper.isAbstractClass; + /** * @author Steve Ebersole */ @@ -34,18 +35,18 @@ public VirtualIdRepresentationStrategy( Component bootDescriptor, RuntimeModelCreationContext creationContext) { this.entityMappingType = entityMappingType; - if ( bootDescriptor.getComponentClassName() != null && ReflectHelper.isAbstractClass( bootDescriptor.getComponentClass() ) ) { - this.instantiator = new EmbeddableInstantiatorProxied( + if ( bootDescriptor.getComponentClassName() != null + && isAbstractClass( bootDescriptor.getComponentClass() ) ) { + instantiator = new EmbeddableInstantiatorProxied( bootDescriptor.getComponentClass(), () -> virtualIdEmbeddable, - creationContext.getServiceRegistry() - .requireService( ProxyFactoryFactory.class ) + creationContext.getServiceRegistry().requireService( ProxyFactoryFactory.class ) .buildBasicProxyFactory( bootDescriptor.getComponentClass() ) ); } else { - this.instantiator = new InstantiatorAdapter( virtualIdEmbeddable, entityMappingType ); + instantiator = new InstantiatorAdapter( virtualIdEmbeddable, entityMappingType ); } } @@ -80,7 +81,7 @@ private static class InstantiatorAdapter implements StandardEmbeddableInstantiat public InstantiatorAdapter(VirtualIdEmbeddable virtualIdEmbeddable, EntityMappingType entityMappingType) { this.virtualIdEmbeddable = virtualIdEmbeddable; - this.entityInstantiator = entityMappingType.getRepresentationStrategy().getInstantiator(); + entityInstantiator = entityMappingType.getRepresentationStrategy().getInstantiator(); } @Override