Java spring引导在json响应中包含OneToMany关联
我有一个实体Java spring引导在json响应中包含OneToMany关联,java,json,spring,spring-boot,Java,Json,Spring,Spring Boot,我有一个实体 @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 Post {
@Id
private Long id;
@NotNull
private Date createdAt;
@NotNull
private String text;
@NotNull
private Date updatedAt;
@OneToMany
private List<Comment> comments;
}
我有一个简单的控制器,返回给定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实体?为了获得所需的结果,您必须在
注释
实体上标记@manytone(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;
}
}
@实体
公营职位{
@身份证
私人长id;
@NotNull
私人日期创建日期;
@NotNull
私有字符串文本;
@NotNull
私人日期更新日期;
@独身癖
@杰索尼奥雷
私人名单评论;
@杰索尼奥雷
公共列表getComments(){
返回评论;
}
@JsonProperty
公共注释(列出注释){
this.comments=注释;
}
}
如果您需要更多说明,请在评论中询问。我会在早上回复。ManyToOne有@Target(value={METHOD,FIELD})…这意味着我不能将我的注释实体类标记为@ManyToOne@riship89如果@ManyToOne是字段级注释,那么还可以将@JsonIgnore
添加到设置的getComments
和@JsonProperty
中。我想包括评论不排除。@riship89请尝试我刚刚发布的内容。很晚了,我累了。代码运行得更好
@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;
}
}