如何在ResponseEntity<>中返回 ‘Integer’ 类型,并在API页面获取结果?

huangapple go评论83阅读模式
英文:

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(&quot;/{id}/age&quot;)
public ResponseEntity&lt;Integer&gt; getStudentAge(@PathVariable Long id) {
    Integer age = studentService.retrieveAgeById(id);
    return new ResponseEntity&lt;Integer&gt;(age, HttpStatus.OK);
}

With a simple SQL data, as simple as this:
INSERT INTO student (id, name, age, gender) VALUES (1, &#39;Rio&#39;, 5, &#39;Male&#39;);
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(&quot;select d.id, d.age from Student d where d.id=:id&quot;)
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(&quot;select d.age from Student d where d.id = :id&quot;)
Integer findAgeById(@Param(&quot;id&quot;) 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.

huangapple
  • 本文由 发表于 2020年4月9日 18:13:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/61118830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定