StackOverflow in bidirectional relationship in JPA

3

I am facing this problem with a bidirectional relationship, when I put a question in question to create an answer it does the persistence, until then beauty, but if I try to get a get or even in the API response points me an http 500, I discovered that the problem is: Question contains a list of Answer, Answer contains a Question, which contains a List of Answer, which contains a Question .... tending to infinity, does anyone know how to stop it?

@Entity
public class Question extends BasicForum {

    private String title;
    private Integer views;

    @OneToMany(fetch= FetchType.LAZY, cascade= CascadeType.ALL, mappedBy = "question")
    private List<Answer> answerList;

    public void transformAnswerInList(Answer answer){
        List<Answer> answers = getAnswerList();
        answers.add(answer);
        this.setAnswerList(answers);
    }
}
@Entity
public class Answer extends BasicForum {

    @ManyToOne
    private Question question;

}
@RestController
@RequestMapping(QuestionController.MAPPING)
public class QuestionController extends SuperController<Question, QuestionRepository> {
    public static final String MAPPING = "/api/questions";

    @Autowired
    private QuestionRepository repository;

    @Override
    public QuestionRepository getRepository() {
        return repository;
    }

    //Outros metodos ocultos

    @RequestMapping(method = RequestMethod.PUT, value = "/{id}/answers")
    public ResponseEntity<Question> postAnswer(@PathVariable("id") final String id, @RequestBody Answer answer){
        Question question = repository.findOne(id);
        question.addAnswer(answer);
        answer.setQuestion(question);
        return super.update(question);
    }
}

I'm using Generics and Liquibase, I do not know if that can be it. Thank you in advance.

    
asked by anonymous 08.06.2016 / 13:38

1 answer

2

This problem happens when Spring tries to serialize the object to JSON, and because there are circular references, it throws an exception indicating this, so you can solve this problem, you usually have 2 options,

1 - You can annotate a field to be ignored in serialization with @JsonIgnore, in which case it would be in the answer list or in the Question list.

2 - You can create a custom Jackson serializer and you format the serialization to suit you.

Note: You can still try to use 2 annotations, but it is not sure to solve this problem.

@Entity
public class Answer extends BasicForum {

    @ManyToOne
    @JsonBackReference
    private Question question;
}

@Entity
public class Question extends BasicForum {

    @OneToMany(fetch= FetchType.LAZY, cascade= CascadeType.ALL, mappedBy = "question")
    @JsonManagedReference
    private List<Answer> answerList;
}
    
08.06.2016 / 14:24