'Query and CountQuery Concurrently Java Spring JPA?
I have a query that requires pagination and I want to run the query and countQuery at the same time. I also want to get the result in a Page object so I know how many items, total count, nextPage etc. I am not sure if this is possible without some sort of custom implementation.
Lets say I have something like this
@Query(value="select * from users where tag=tag;" countQuery="select count(*) from (select * from users where tag=tag) as qcount") Page<User> getUsersWithTag(Tag tag, Pageable pagination)
Is it possible to run both the count and query at the same time and get a Page result? I am thinking about using springs @Async annotation, I guess these methods would have to be split apart.
I have tried just adding @Async onto the method but that seems to actually hurt the performance. I am aware I may need to use Future or CompletableFuture to do this, just not sure how I can get the Page information together.
Update: I have found somewhat of a hacky soltuion but basically using java Futures and Spring Async I have done this.
@Query(value="select * from users;")
@Async
Future<Page<User>> getUsersWithTag(Tag tag, Pageable pagination)
@Query(value="select count(*) from (select * from users where tag=tag) as qcount")
@Async
Future<Long> getUsersWithTagCount(Tag tag, Pageable pagination)
List<User> users = getUsersWithTag(tag, pageable).get();
long count = getUsersWithTagCount(tag, pageable).get();
Page<User> = new PageImpl<>(users, pageable, count);
Solution 1:[1]
You already have this information in your paged result set
Page<User> getAllUsers(Pageable pagination)
You return Page<User> and there you have available the method getTotalElements() which should return to you the total number of elements contained in all pages.
Also
@Query(value="select * from users;" countQuery="select count(*) from (select * from users) as qcount") Page<User> getAllUsers(Pageable pagination)
The part countQuery="select count(*) from (select * from users) as qcount" is redundant as spring will by default create and use the same query by itself, only because you use Pagination in your declared method.
Solution 2:[2]
With org.springframework.data.domain.Page you already have :
{ "totalElements": 0, "totalPages": 0, "size": 0, "content": [ {...
See Page doc for more details.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Montassar El Béhi |
