I am using backend pagination and sorting with java spring boot pageable
. While passing sort field as usercount
(This gives count of user_role_mapping
), Java triggering an error column f.usercount does not exist .
Actually usercount
not a column it's an Alias name.
How to sort using usercount as Alies name without f. as prefix?
API URL:
http://localhost:8080/facility/list?pageNumber=0&pageSize=10&sortBy=usercount&sortType=asc
Default sortBy & sortType are id and desc respectively in controller layer.
Java Code give below:
Pageable pageable = PageRequest.of(pageNumber, pageSize, Sort.by(sortBy).descending());
if (sortType.equalsIgnoreCase("asc")) {
pageable = PageRequest.of(pageNumber, pageSize, Sort.by(sortBy).ascending());
}
Page<FacilityProjection> facilityList = facilityRepository.facilityListing(12,pageable);
Postgres sql Hibernate query for listing facility details along with user count based on role id, given below:
@Query(nativeQuery = true, value = " Select f.name as facilityname,f.id as facilityid,count(urm.id) as usercount
from facility f
join user u on f.user_id=u.id
join user_role_mapping urm on u.id = urm.user_id
where urm.role_id=:roleId ")
Page<FacilityProjection> facilityListing(@Param("roleId") Long roleId,Pageable pageable);