diff --git a/src/main/java/org/springframework/data/jpa/repository/query/QueryUtils.java b/src/main/java/org/springframework/data/jpa/repository/query/QueryUtils.java index 351a08f29..9a9f6c12e 100644 --- a/src/main/java/org/springframework/data/jpa/repository/query/QueryUtils.java +++ b/src/main/java/org/springframework/data/jpa/repository/query/QueryUtils.java @@ -588,7 +588,7 @@ public abstract class QueryUtils { propertyPathModel = from.get(segment).getModel(); } - if (requiresJoin(propertyPathModel, model instanceof PluralAttribute) && !isAlreadyFetched(from, segment)) { + if (requiresJoin(propertyPathModel, model instanceof PluralAttribute, !property.hasNext()) && !isAlreadyFetched(from, segment)) { Join join = getOrCreateJoin(from, segment); return (Expression) (property.hasNext() ? toExpressionRecursively(join, property.next()) : join); } else { @@ -603,9 +603,10 @@ public abstract class QueryUtils { * * @param propertyPathModel may be {@literal null}. * @param forPluralAttribute + * @param forLeafProperty * @return */ - private static boolean requiresJoin(@Nullable Bindable propertyPathModel, boolean forPluralAttribute) { + private static boolean requiresJoin(@Nullable Bindable propertyPathModel, boolean forPluralAttribute, boolean forLeafProperty) { if (propertyPathModel == null && forPluralAttribute) { return true; @@ -620,6 +621,9 @@ public abstract class QueryUtils { if (!ASSOCIATION_TYPES.containsKey(attribute.getPersistentAttributeType())) { return false; } + if (forLeafProperty && !attribute.isCollection()) { + return false; + } Class associationAnnotation = ASSOCIATION_TYPES.get(attribute.getPersistentAttributeType()); diff --git a/src/test/java/org/springframework/data/jpa/repository/query/QueryUtilsIntegrationTests.java b/src/test/java/org/springframework/data/jpa/repository/query/QueryUtilsIntegrationTests.java index 969811ac7..6e708115e 100644 --- a/src/test/java/org/springframework/data/jpa/repository/query/QueryUtilsIntegrationTests.java +++ b/src/test/java/org/springframework/data/jpa/repository/query/QueryUtilsIntegrationTests.java @@ -87,7 +87,7 @@ public class QueryUtilsIntegrationTests { CriteriaQuery query = builder.createQuery(User.class); Root root = query.from(User.class); - QueryUtils.toExpressionRecursively(root, PropertyPath.from("manager", User.class)); + QueryUtils.toExpressionRecursively(root, PropertyPath.from("manager.firstname", User.class)); assertThat(root.getJoins()).hasSize(1); }