![](/img/trans.png)
[英]Adding collection to JSON response using Spring Boot and fasterxml jackson and @OneToMany annotation
[英]spring boot include OneToMany association in json response
我有一個實體
@Entity
public class Post {
@Id
private Long id;
@NotNull
private Date createdAt;
@NotNull
private String text;
@NotNull
private Date updatedAt;
@OneToMany
private List<Comment> comments;
}
和另一個實體
@Entity
public class Comment {
@Id
private Long id;
@NotNull
private Date createdAt;
@NotNull
private String text;
@NotNull
private Date updatedAt;
}
我有一個簡單的控制器,返回給定id的post json
@RestController
@RequestMapping("/posts")
public class ProductDimensionsController {
@RequestMapping(method = RequestMethod.GET)
public Post getPost(@RequestParam(value = "id") String id) throws ApiException {
...
...
...
}
}
我得到回應:
{
"id": 401,
"createdAt": 1482364510614,
"updatedAt": 1482364510614,
"text": "abc",
}
我要關注:
{
"id": 401,
"createdAt": 1482364510614,
"updatedAt": 1482364510614,
"text": "abc",
"comments": [{
"id": 101,
"createdAt": 1482364510614,
"updatedAt": 1482364510614,
"text": "xyz",
}]
}
如何在json響應中包含關聯的OneToMany實體?
為了獲得所需的結果,您必須在Comment
實體上標記@ManyToOne(fetch = FetchType.LAZY)
。 這將導致以FetchType.LAZY
模式獲取結果。
另一種方法可能是:
@Entity
public class Post {
@Id
private Long id;
@NotNull
private Date createdAt;
@NotNull
private String text;
@NotNull
private Date updatedAt;
@OneToMany
@JsonIgnore
private List<Comment> comments;
@JsonIgnore
public List<Comment> getComments() {
return comments;
}
@JsonProperty
public void setComments(List<Comment> comments) {
this.comments = comments;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.