Cut bi-directional relationship looping

4

I'm having a Spring project, using JPA and Liquibase, I have a two-way relationship between two entities, I wonder if anyone has a solution to the infinite referral problem between the two? For example, I have a Question that has many answers, a answer has this question that has this answer and so it tends to infinity, I can not lose the bidirectionality so the annotation @IgnoreJson would not be interesting. Follow my entities.

@Entity
@Table(name = "question")
public class Question extends BasicForum{

private String title;
private Integer views;

@OneToMany(cascade= CascadeType.ALL, mappedBy = "question")
private List<Answer> answerList;
@Entity
@Table(name = "answer")
public class Answer extends BasicForum {

@ManyToOne(cascade = CascadeType.ALL)
private Question question;
    
asked by anonymous 10.06.2016 / 13:45

2 answers

0

Well, I left the question a little forgotten, but what I did to solve this was:

I basically removed the list of Answer from within Question , and created a method on Controller that returns me Answers from Question .

Controller:

@RequestMapping(method = RequestMethod.GET, value = "/question/{id}")
public List<Answer> getAnswersByQuestion(@PathVariable("id") final String id) {
        return repository.findByQuestionIdAndDeadIsFalse(id);
}

Repository:

@Repository
public interface AnswerRepository extends SuperRepository<Answer> {
    List<Answer> findByQuestionIdAndDeadIsFalse(String questionId);
}
    
11.11.2016 / 13:17
0

You can give Lazy a Question in the Answer entity, so it will not fetch a question.

@Entity
@Table(name = "answer")
public class Answer extends BasicForum {

@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.Lazy)
private Question question;
    
10.06.2016 / 14:23