我刚刚开始在 MVC 中开发 spring-boot 应用程序 (Java)。在 Controller 类中,
@GetMapping("/{id}/age")
public ResponseEntity<Integer> getStudentAge(@PathVariable Long id) {
Integer age = studentService.retrieveAgeById(id);
return new ResponseEntity<Integer>(age, HttpStatus.OK);
}
用一个简单的SQL数据,就这么简单:
INSERT INTO 学生(ID、姓名、年龄、性别)VALUES (1, 'Rio', 5, 'Male');
当我运行应用程序并检查路径为: http://localhost:8080/1/age 的网页时
我收到的回复中未打印年龄:
Result
存储库包中使用的查询是:
@Query("select d.id, d.age from Student d where d.id=:id")
Integer findAgeById(Long id);
此外,对学生姓名、性别(类型:字符串)的请求也成功。但是,年龄请求(类型:Integer)不会产生类似的结果。
最佳答案
将您的 SELECT 查询调整为:
@Query("select d.age from Student d where d.id = :id")
Integer findAgeById(@Param("id") Long id);
问题中的查询会将 SELECT 中的第一个字段映射到方法的类型,如您所见,即您的学生 ID。
您还可以在方法声明中提供@Param
,因为根据 this guide :
A query with named parameters is easier to read and is less error-prone in case the query needs to be refactored.
如果您想提取 ID 和年龄,您可以返回整个 Student
实体并使用它。另一种选择是使用 projection但我真的不相信您的用例足够先进,无法从中受益。
关于java - 如何为 ResponseEntity<> 返回 'Integer' 类型并在 api 页面上获取结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61118830/