如何返回响应实体的'Integer'类型<>并在 api 页面上获取结果?



我刚刚开始在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我得到了一个没有打印年龄的回复:结果

存储库包中使用的查询是:

@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,因为根据本指南:

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

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

相关内容

最新更新