Cut bidirectional relationship looping

Asked

Viewed 430 times

4

I am with a Spring project, using JPA and liquibase, I have a bi-directional relationship between two entities, I wonder if anyone has a solution to the problem of infinite referencing between the two? Exemplifying I have a Question that has many Swers, an Swer has this Question that has this Swer and so it tends to infinity, I can not lose the bidirectionality then the Annotation @IgnoreJson would not be interesting. Follows 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;

2 answers

0


Well, I left the question kind of forgotten, but what I did to solve it was:

Basically I removed the list of Answer from within Question, and created a method in Controller that returns to me the Answers from the 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);
}

0

You can give a Lazy in the Answer entity Question, so it won’t fetch Question.

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

@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.Lazy)
private Question question;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.