Skip to content

Commit 055422a

Browse files
committed
HQL queries without a primary alias don't need Sorted properties prefixed.
In the event a Hibernate query doesn't have a primary alias, don't attempt to prefix order by property settings. See #2969
1 parent 94ea258 commit 055422a

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/JpaQueryTransformerSupport.java

+9-2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import org.springframework.data.domain.Sort;
1313
import org.springframework.data.jpa.domain.JpaSort;
1414
import org.springframework.lang.Nullable;
15+
import org.springframework.util.ObjectUtils;
1516

1617
/**
1718
* Transformational operations needed to support either {@link HqlQueryTransformer} or {@link JpqlQueryTransformer}.
@@ -103,7 +104,7 @@ private void checkSortExpression(Sort.Order order) {
103104
*/
104105
private String generateOrderByArgument(@Nullable String primaryFromAlias, Sort.Order order) {
105106

106-
if (shouldPrefixWithAlias(order)) {
107+
if (shouldPrefixWithAlias(order, primaryFromAlias)) {
107108
return primaryFromAlias + "." + order.getProperty();
108109
} else {
109110
return order.getProperty();
@@ -115,9 +116,15 @@ private String generateOrderByArgument(@Nullable String primaryFromAlias, Sort.O
115116
* FROM clause's alias.
116117
*
117118
* @param order
119+
* @param primaryFromAlias
118120
* @return boolean whether or not to apply the primary FROM clause's alias as a prefix
119121
*/
120-
private boolean shouldPrefixWithAlias(Sort.Order order) {
122+
private boolean shouldPrefixWithAlias(Sort.Order order, String primaryFromAlias) {
123+
124+
// If there is no primary alias
125+
if (ObjectUtils.isEmpty(primaryFromAlias)) {
126+
return false;
127+
}
121128

122129
// If the Sort contains a function
123130
if (order.getProperty().contains("(")) {

spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/query/HqlQueryTransformerTests.java

+7
Original file line numberDiff line numberDiff line change
@@ -966,6 +966,13 @@ void shouldHandleAliasInsideCaseStatement() {
966966
"order by newDateDue desc");
967967
}
968968

969+
@Test // GH-2969
970+
void fromWithoutAPrimaryAliasShouldWork() {
971+
972+
assertThat(createQueryFor("FROM Story WHERE enabled = true", Sort.by(Sort.Direction.DESC, "created")))
973+
.isEqualTo("FROM Story WHERE enabled = true order by created desc");
974+
}
975+
969976
private void assertCountQuery(String originalQuery, String countQuery) {
970977
assertThat(createCountQueryFor(originalQuery)).isEqualTo(countQuery);
971978
}

0 commit comments

Comments
 (0)