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 300a8927d3..33e68fd1bf 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 @@ -148,12 +148,24 @@ public abstract class AbstractDomainPath implements DomainPath { ); } else if ( referenceModelPart instanceof EntityValuedModelPart ) { - final ModelPart subPart; + ModelPart subPart; if ( ELEMENT_TOKEN.equals( modelPartName ) ) { subPart = ( (EntityValuedModelPart) referenceModelPart ).getEntityMappingType().getIdentifierMapping(); } else { subPart = ( (EntityValuedModelPart) referenceModelPart ).findSubPart( modelPartName ); + if ( subPart == null && referenceModelPart instanceof ToOneAttributeMapping ) { + // this is the case of sort by to-one attribute inside an embedded item, + // at this stage the foreign key descriptor should have been set on the attribute mapping, + // so we can generate a sub part valid for the order-by generation + ToOneAttributeMapping toOneAttribute = (ToOneAttributeMapping) referenceModelPart; + String foreignKeyModelPart = toOneAttribute.getAttributeName() + "." + + toOneAttribute.getTargetKeyPropertyName(); + + if ( modelPartName.equals( foreignKeyModelPart ) ) { + subPart = toOneAttribute.findSubPart( toOneAttribute.getTargetKeyPropertyName() ); + } + } } apply( subPart, diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/DomainPathContinuation.java b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/DomainPathContinuation.java index 4c49419e44..79b2bbac06 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/DomainPathContinuation.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/mapping/ordering/ast/DomainPathContinuation.java @@ -78,7 +78,9 @@ public class DomainPathContinuation extends AbstractDomainPath { return new DomainPathContinuation( navigablePath.append( name ), this, - subPart + // unfortunately at this stage the foreign key descriptor could not be set + // on the attribute mapping yet, so we need to defer the sub part extraction later + referencedModelPart ); } }