【发布时间】:2021-06-10 04:59:58
【问题描述】:
我想在 Spring Boot 项目中对响应数据进行分页。根据业务逻辑,我添加了多个RequestParam。一切都好,如果我传递所有请求参数的值,即性别和国家。但是,如果我没有给出任何一个或两个值,我会得到 500 状态代码,尽管我将性别和国家/地区 requestParam 设为可选。这意味着,
如果我打了
http://localhost:8080/api/v1/users?page=1&country=Russia&gender=M,
我得到了分页响应。
但是如果我打了
http://localhost:8080/api/v1/users?page=1&gender=M
http://localhost:8080/api/v1/users?page=1&country=俄罗斯
http://localhost:8080/api/v1/users?page=1.
我得到异常
这是我的代码。
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"
}
【问题讨论】:
-
为国家和性别字段添加默认值。它将解决问题。
-
对于具有不同参数的动态查询,使用谓词而不是方法来执行查询。
标签: spring spring-boot kotlin pagination