英文:
How to return 'Integer' type for ResponseEntity<> and get the result on api page?
问题
我刚开始在一个使用Spring Boot框架(Java)的MVC应用程序上工作。在控制器类中,
@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);
此外,对于学生的姓名和性别(类型:String)的请求是成功的。但是,年龄(类型:Integer)的请求没有产生类似的结果。
英文:
I just started working on a spring-boot application (Java) in MVC. In the controller class,
@GetMapping("/{id}/age")
public ResponseEntity<Integer> getStudentAge(@PathVariable Long id) {
Integer age = studentService.retrieveAgeById(id);
return new ResponseEntity<Integer>(age, HttpStatus.OK);
}
With a simple SQL data, as simple as this:
INSERT INTO student (id, name, age, gender) VALUES (1, 'Rio', 5, 'Male');
When I run the application and check the webpage with path: http://localhost:8080/1/age
I get a response in which age is NOT printed:
Result
The Query used in repository package is:
@Query("select d.id, d.age from Student d where d.id=:id")
Integer findAgeById(Long id);
Also, the requests for student name, gender(Type:String) is successful. But, the request for age (Type:Integer) is not producing similar results.
答案1
得分: 1
适应您的SELECT查询为:
@Query("select d.age from Student d where d.id = :id")
Integer findAgeById(@Param("id") Long id);
问题中的查询将会将SELECT的第一个字段映射到您方法的类型,正如您所看到的,这是您的学生ID。
您还可以在方法声明中提供一个@Param
,因为根据这个指南所述:
> 使用命名参数的查询更易于阅读,并且在需要重构查询时更不容易出错。
如果您想要提取ID和年龄,您可以返回整个Student
实体并使用它。另一种选择是使用投影,但我实际上不认为您的用例足够复杂,可以从中受益。
英文:
Adapt your SELECT query to:
@Query("select d.age from Student d where d.id = :id")
Integer findAgeById(@Param("id") Long id);
The query in your question will map the first field from your SELECT to the type of your method, an as you can see, that is your Student ID.
You also could to provide a @Param
in your method declaration, because according to this guide:
>A query with named parameters is easier to read and is less error-prone in case the query needs to be refactored.
If you want to extact both the ID and the age, you can return your entire Student
entity, and use that. Another option is to use a projection but I really don't believe your use-case is advanced enough to benefit from this.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论