三重嵌套JPA实体到JSON - Sping Boot 项目

5gfr0r5j  于 2023-01-13  发布在  其他
关注(0)|答案(2)|浏览(124)

因此,我有3个@Entity类

class Campaign
{
  @Id
  private long campaignId;
  //Other fields

  @OneToMany(mappedBy = "campaign",cascade=CascadeType.ALL)
    private Set<Question> questions;
}

class Question
{
  @Id
  private long questionId;

  //Other fields
  @OneToMany(mappedBy = "question",cascade=CascadeType.ALL)
    private Set<Choices> choices;

  @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="CAMPAIGN_ID")
    private Campaign campaign;
}

class Choices
{
  @Id
  private long choiceId;

  //Other fields
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="QUESTION_ID")
    private Question question;
}

创建和发送JSON时

{
    "campaignName" : "Dummy Quiz Campaign",
    "campaignDescription" : "This is a dummy quiz campaign for testing",
    "noOfQuestions":2,
    "noOfChoices":3,
    "lastUpdatedTime":"2012-04-23T18:25:43.511Z",
    "createdTime":"2012-04-23T18:25:43.511Z",
    "questions":[
        {
            "question":"Question 1",
            "choices":[
                {"choice":"Choice 1"},
                {"choice":"Choice 2"},
                {"choice":"Choice 3"}
                ],
            "correctAnswer":"Choice 2"
        },
        {
            "question":"Question 2",
            "choices":[
                {"choice":"Choice 4"},
                {"choice":"Choice 5"},
                {"choice":"Choice 6"}
                ],
            "correctAnswer":"Choice 2"
        }
    ]
}

它正在被准确地创建和Map,也正在被准确地删除。
但当我尝试获取AllCampaigns()时

@GetMapping("/api/campaign/all")
    public List<Campaign> getAllCampaigns() throws Exception 
    {
        return campaignService.getAllCampaigns();
    }

它显示了jackson.bind错误,当我试图将JSON写入文件时,它最终得到了一个无限嵌套的JSON。
我可以做什么来检索活动和有Map的实体一样,在我发送它的格式。
对于表,3个表活动表具有Campaign_Id的问题表具有Question_Id的选择表
先谢了。

vx6bjr1n

vx6bjr1n1#

您得到无限递归的原因是,问题Map到市场活动类,而市场活动Map到问题类。这种双向关系导致无限递归。这可以通过使用@JsonManagedReference来解决。和@JsonBackReference注解。您可以在一对多关系上使用@JsonManagedRefernce注解,在多对一关系上使用@JsonBackReference注解。这应该可以解决递归问题。你可以从here得到更多的信息。如果有帮助的话,请告诉我。

2vuwiymt

2vuwiymt2#

此处需要添加@JsonIgnore注解,如下所示:

class Question{
@Id
private long questionId;

//Other fields
@OneToMany(mappedBy = "question",cascade=CascadeType.ALL)
private Set<Choices> choices;

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="CAMPAIGN_ID")
@JsonIgnore
private Campaign campaign;
}

相关问题