I want to paginate response Data in Spring boot project. According to business logic, I added multiple RequestParam. All is ok, if I pass value for all request Param i.e Gender and Country. But if I don't give value either one or both, I get 500 status code, although I make gender and Country requestParam as optional. It means,
if I hit
http://localhost:8080/api/v1/users?page=1&country=Russia&gender=M,
I get response with pagination.
But if I hit
http://localhost:8080/api/v1/users?page=1&gender=M
http://localhost:8080/api/v1/users?page=1&country=Russia
http://localhost:8080/api/v1/users?page=1.
I get exception
Here is my code.
UserRepository.kt
@Repository
interface UserRepository: JpaRepository<User, Long> {
@Query(
nativeQuery = true,
value = "SELECT * FROM user_info WHERE gender =:gender AND country =:country"
)
fun getUsers(gender: String?, country: String?, pageable: Pageable): Page<User>
}
UserServiceImpl.kt
@Service
class UserServiceImpl(
@Autowired private val userRepository: UserRepository
): UserService {
override fun getUsers(gender: String?, country: String?, pageable: Pageable): Page<User> {
return userRepository.getUsers(gender, country, pageable)
}
}
UserController.kt
@RestController
@RequestMapping(
path = [
"/api/v1/"
]
)
class UserController(
@Autowired private val userService: UserService
) {
@GetMapping("users")
fun getUsers(
@RequestParam(required = true) page: Int,
@RequestParam(required = false) gender: String?,
@RequestParam(required = false) country: String?
): Page<User> {
return userService.getUsers(gender, country, PageRequest.of(page, 10))
}
}
response
{
"status": "500 INTERNAL_SERVER_ERROR",
"message": "Internal server error occurs",
"error": "could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet"
}