0

I'm just starting to learn spring-boot-jpa. I tried using one-to-one mapping in my program and when I fetch the output using Getmapping I get same data repeated multiple times. I'm not sure what the problem is with the code.

One to One parent relationship

@OneToOne(mappedBy = "question", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Options options;

One to One Child relationship

@OneToOne (cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinColumn(name = "questionId")
    private Question question;

Below is the Controller Class

@RestController
public class QuizController {
    List<Question> question = new ArrayList<Question>();

    @Autowired
    QuestionRepo questionRepo;


    @Autowired
    OptionsRepo optionsRepo;

    @GetMapping("/question")
    public List<Question> getQues() {
         return questionRepo.findAll();
    }


    @PostMapping("/question")
    public void setQues(@RequestParam String ques, String choice1, String choice2, String choice3, String choice4) {
        Question setQues = new Question();
        setQues.setQuestion(ques);
        Options setOp = new Options();
        setOp.setOption1(choice1);
        setOp.setOption2(choice2);
        setOp.setOption3(choice3);
        setOp.setOption4(choice4);

        setQues.setOptions(setOp);
        setOp.setQuestion(setQues);
        questionRepo.save(setQues);

This is the output I'm getting, same options repeating multiple times,

[{"questionId":1,"options":{"option1":"Red","option2":"Black","option3":"Yellow","option4":"Green","question":{"questionId":1,"options":{"option1":"Red","option2":"Black","option3":"Yellow","option4":"Green"}]
Kabil
  • 1

2 Answers2

0

Try Following Code with Child relationship

@OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "Child columnname", referencedColumnName = "parent columnname")

Try Following Code with parent relationship

@OneToOne(mappedBy = "childrefrence ", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
AMAR MAGAR
  • 137
  • 2
  • 13
0

There is a problem in your mapping. While designing bi directional mapping, there should be one side which is the owning side of the relation and the other is mapped side. You should not use @OneToOne in both of your side rather one side should use mapped by. Follow this answer to correct your mapping

Also to solve infinite recursion problem use @JsonManagedReference @JsonBackReference at one side to tell your serializer (Jackson by default) to ignore one side while serializing your object.

Rakib
  • 145
  • 13