0

我刚开始学习spring-boot-jpa。我尝试在我的程序中使用一对一映射,当我使用 Getmapping 获取输出时,我得到了多次重复的相同数据。我不确定代码有什么问题。

一对一的亲子关系

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

一对一儿童关系

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

下面是控制器类

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

这是我得到的输出,相同的选项重复多次,

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

2 回答 2

0

你的映射有问题。在设计双向映射时,应该有一侧是关系的拥有侧,另一侧是映射侧。您不应该@OneToOne在双方都使用,而应该在一侧使用映射的。按照此答案更正您的映射

还要解决无限递归问题,请在一侧告诉您的序列化程序(默认情况下为杰克逊)在序列化对象时忽略一侧。@JsonManagedReference @JsonBackReference

于 2019-08-05T04:45:56.003 回答
0

尝试遵循具有子关系的代码

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

尝试使用父关系跟随代码

@OneToOne(mappedBy = "childrefrence ", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
于 2019-08-05T04:36:27.797 回答