So, I have 3 @Entity classes
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;
}
When I create and send a 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"
}
]
}
It is being created and mapped accurately. It is also being deleted accurately.
But when I am trying to getAllCampaigns()
@GetMapping("/api/campaign/all")
public List<Campaign> getAllCampaigns() throws Exception
{
return campaignService.getAllCampaigns();
}
It is showing a jackson.bind error, when I tried to write the JSON to a file, it ended up having an infinitely nested JSON.
What I can do to retrieve the Campaigns and there mapped entities like in the format I have send it.
As for the tables, 3 Tables Campaign Table Question Table with Campaign_Id Choices Table with Question_Id
Thanks in advance.
CodePudding user response:
The reason you are getting the infinite recursion is because, the question is mapped in the campaign class and the campaign is mapped in the question class. This bi-directional relation causes the infinite recursion. This can be solved by using @JsonManagedReference
, and @JsonBackReference
annotations on the mappings. You can use the @JsonManagedRefernce
annotation on the one to many relation and @JsonBackReference
annotation on the Many to one relation. This should solve the recursion problem. You can get more info from here . Let me know if this helps.
CodePudding user response:
Here you need to add @JsonIgnore Anotation like this:
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;
}