Create bi-directional relationship without using DTO?

Asked

Viewed 228 times

0

Hello, I’m on a project and I need to do bidirectional relationship between two entities, the relationship is @OneToMany @ManyToOne, so far so good. But I wonder if there is any way to do it without using DTO?

@Entity
public class Answer extends BasicForum {

    @ManyToOne
    @JsonIgnore
    private Question question;

    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "answer")
    private List<CommentAnswer> commentList;

@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;

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

I thank all of the community.

  • The relationship is already bidirectional, had some problem?

  • @Matheussilva the problem is Jsonignore, it cuts the bidirectionality because it ignores in json the attribute Question within Answer, if I remove it the relationship tends to infinity and a stack burst because a Question has a list of Answer, that each attribute on the list has a Question, which has a list of Answer.... and so it goes on to infinity.

2 answers

0


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.

Answer:

@Entity
public class Answer extends BasicForum {
    @ManyToOne
    private Question question;

    private Boolean bestAnswer;
    private Integer numberComments;

    //Outros metodos
}

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

To manipulate services the strategy commonly adopts is to use Dtos, even to avoid these annotated entity problems with bi-directional dependencies. Even replicating information is a good practice to have DTO entities to represent a persistent entity that will be manipulated by a service, by separating what is persistent from what is "transient". Another advantage is even to "denormalize" some information distributed in several entities, so it is easier to manipulate the data because you keep in a single access point (in DTO) the information required/provided by the service.

Browser other questions tagged

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