【问题标题】:spring boot include OneToMany association in json responsespring boot 在 json 响应中包含 OneToMany 关联
【发布时间】:2016-12-22 20:51:38
【问题描述】:

我有一个实体

@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 实体?

【问题讨论】:

  • 如果您需要更多说明,请在 cmets 中询问。我会在早上回复。

标签: java json spring spring-boot


【解决方案1】:

为了获得您想要的结果,您必须在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;
    }
}

【讨论】:

  • ManyToOne 有@Target(value={METHOD,FIELD})...这意味着我无法将我的评论实体类标记为@ManyToOne。
  • @riship89 你也可以在setter上添加@JsonIgnoregetComments@JsonProperty
  • 我不是很明白...如果@ManyToOne 是字段级别的注释,我如何用@ManyToOne 标记class Comment
  • 我想包含 cmets 而不是排除。
  • @riship89 试试我刚刚发布的内容。时间不早了,我累了。代码变得更好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-07
  • 2023-02-02
  • 2018-07-13
  • 2019-01-07
  • 2019-02-07
  • 2014-01-09
  • 1970-01-01
相关资源
最近更新 更多