繁体   English   中英

Spring Boot在json响应中包含OneToMany关联

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM