我有一个实体
@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实体?
答案 0 :(得分:3)
为了获得您想要的结果,您必须在@ManyToOne(fetch = FetchType.LAZY)
实体上标记Comment
。这将导致以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;
}
}