【问题标题】:How to return 'Integer' type for ResponseEntity<> and get the result on api page?如何为 ResponseEntity<> 返回“整数”类型并在 api 页面上获取结果?
【发布时间】:2020-04-09 10:13:42
【问题描述】:

我刚开始在 MVC 中开发一个 spring-boot 应用程序 (Java)。在控制器类中,

@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 student (id, name, age, gender) 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);

另外,学生姓名、性别(Type:String)的请求也成功了。但是,年龄请求(类型:整数)没有产生类似的结果。

【问题讨论】:

    标签: java sql spring-boot rest spring-mvc


    【解决方案1】:

    将您的 SELECT 查询调整为:

    @Query("select d.age from Student d where d.id = :id")
    Integer findAgeById(@Param("id") Long id);
    

    您问题中的查询会将您的 SELECT 中的第一个字段映射到您的方法类型,如您所见,即您的学生 ID。

    您也可以在方法声明中提供@Param,因为根据this guide

    带有命名参数的查询更易于阅读,并且在需要重构查询时不易出错。

    如果您想同时提取 ID 和年龄,您可以返回整个 Student 实体,然后使用它。另一种选择是使用projection,但我真的不相信您的用例足够先进,无法从中受益。

    【讨论】:

    • 嗨,这回答了这个问题。但是,如果我希望在结果页上同时打印 ID 和年龄怎么办?在这种情况下,方法的返回类型应该是什么?例如:@Query("select d.id, d.age from Student d where d.id = :id") &lt;Type&gt; findAgeById(@Param("id") Long id);
    猜你喜欢
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 2017-04-28
    • 2012-02-06
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    相关资源
    最近更新 更多