java - 如何为 ResponseEntity<> 返回 'Integer' 类型并在 api 页面上获取结果?

标签 java sql spring-boot rest spring-mvc

我刚刚开始在 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/

相关文章:

sql - Laravel 中“调用未定义的方法 Illuminate\Database\Query\Builder::appends()”错误

php - 这是一个 MySQL 错误还是我疯了?查询未返回足够的结果

javascript - AngularJS 两个日期之间的区别

java - 我的带有 onClickListener 的 ImageView 在单击时不执行任何操作

java - 如何使用 FutureTask 从 Runnable 接口(interface)返回值

java - 通过语音命令启动应用程序 (android)

spring-boot - 每个请求的 Jooq 配置

java - 自动执行依赖:build-classpath in maven

PHP简单地将表单数据插入数据库不起作用

intellij-idea - IntelliJ Spring Boot : How to create an executable jar