-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Different number of elements in paged result of non-distinct query #3220
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
For this case, you must provide your own count query via As the examples above do not define a |
@mp911de When it comes to the Anyway, the problem is not really in the count query alone. The problem lies in the |
In such a case, the implementation should go in a custom implementation. Repositories and Similar to
We have certain assumptions that we meet. If your queries do not meet these assumptions, then you need to provide either more specific queries or follow the route of implementing a custom fragment. That being said, we do not intend to introduce more complexity on our side. |
By default, all the results of the Repository query are returned as the distinct list. When pagination and joins are used the count of elements differs from the actually obtained results. In some cases it can totally break a pagination, mostly unpredictably.
This JPQL query:
SELECT a FROM Author a INNER JOIN Book b ON b.author = a
will return list of the uniqueAuthor
entities independently from the number of the books per author (assuming, that author have non-zero number of books).On the other hand, the native query will return the list as should be, with the duplicates caused by the join.
This behavior basically does not cause the problem, but when it comes to the pagination, it have some consequences.
Page.getTotalElements()
method shows different number than returned number of the entities.The problem looks like to be caused by the condition at
org/springframework/data/support/PageableExecutionUtils.java:66
The condition works with the actual results and if the result list is smaller than
pageSize
it will not runcountQuery
supplier. This causes differentgetTotalElements()
number on the pages wherecontent.size()<getPageSize()
. This can happen on every page because algorithm wrongly thinks, that it is the last page. On the affected pages the number oftotalElements
suddenly drops because it is calculated from the actual offset, not using the count query.To get the acceptable results:
countQuery
every time (you will get the wrong result, but the pagination will remain unchanged on all pages).countQuery
should be used (to not to change the actual behavior). Native queries must be unaffected.How to reproduce
Entities
Repository
Test Code
Related: #750
The text was updated successfully, but these errors were encountered: