Create bidirectional relationship without using DTO?

0

Hello, I'm in 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;

Thanks to everyone in the community.

    
asked by anonymous 01.07.2016 / 16:53

2 answers

0

I basically removed the list of Answer from within Question , and created a method on Controller that returns me Answers from 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);
}
    
11.11.2016 / 13:33
0

To manipulate services the strategy commonly adopted is to use DTOs, even to avoid these annotated entity issues with two-way 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 persisted from what is "transient." Another benefit is to "denormalize" some information distributed across multiple entities, so it is easier to manipulate the data because you keep the information required / provided by the service in a single access point (DTO).     

31.08.2016 / 16:29