You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Remove duplicate 'distinct' applied in count operations.
When performing a count operation, we are using countDistinct from JPA, and hence, don't need the JpaQueryCreator applying distinct outside the whole thing.
Also added some details in the ref docs to help guide users on writing proper distinct-based queries.
See #1380.
Copy file name to clipboardExpand all lines: spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/query/JpaQueryRewriteIntegrationTests.java
Copy file name to clipboardExpand all lines: src/main/asciidoc/jpa.adoc
+21
Original file line number
Diff line number
Diff line change
@@ -253,6 +253,27 @@ The following table describes the keywords supported for JPA and what a method c
253
253
254
254
NOTE: `In` and `NotIn` also take any subclass of `Collection` as a parameter as well as arrays or varargs. For other syntactical versions of the same logical operator, check "`<<repository-query-keywords>>`".
255
255
256
+
[WARNING]
257
+
====
258
+
`DISTINCT` can be tricky and not always producing the results you expect.
259
+
For example, `select distinct u from User u` will produce a complete different result than `select distinct u.lastname from User u`.
260
+
In the first case, since you are including `User.id`, nothing will duplicated, hence you'll get the whole table, and it would be of `User` objects.
261
+
262
+
However, that latter query would narrow the focus to just `User.lastname` and find all unique last names for that table.
263
+
This would also yield a `List<String>` result set instead of a `List<User`> result set.
264
+
265
+
266
+
`countDistinctByLastname(String lastname)` can also produce unexpected results.
267
+
Spring Data JPA will derive `select count(distinct u.id) from User u where u.lastname = ?1`.
268
+
Again, since `u.id` won't hit any duplicates, this query will count up all the users that had the binding last name.
269
+
Which would the same as `countByLastname(String lastname)`!
270
+
271
+
What is the point of this query anyway? To find the number of people with a given last name? To find the number of _distinct_ people with that binding last name?
272
+
To find the number of _distinct last names_? (That last one is an entirely different query!)
273
+
Using `distinct` sometimes requires writing the query by hand and using `@Query` to best capture the information you seek, since you also may be needing a projection
0 commit comments