由父级设置后,OneToMany实体父级字段为null

时间:2019-04-16 06:52:14

标签: hibernate spring-mvc jpa spring-data-jpa thymeleaf

我正在尝试提交一个以Quiz作为表单支持实体以及其中的一些Question作为表单的表单。

这两个实体在双向关联中相关:

@Getter
@Setter
@ToString(exclude = { "questions" })
@Entity
@Table(name = "quiz")
public class Quiz {

    @Id
    @Column(name = "id_quiz")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int idQuiz;

    @OneToMany(mappedBy = "quiz", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<Question> questions = new LinkedList<>();

    public Quiz() {
                // Creating a Quiz with at least one question
        addQuestion(new Question());
    }

    public void addQuestion(Question question) {
        this.questions.add(question);
        // Setting Question parent for bidirectional association
        question.setQuiz(this);
    }
}
@Getter
@Setter
@ToString(exclude = { "quiz" })
@Entity
@Table(name = "question")
public class Question {

    @Id
    @Column(name = "id_question")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int idQuestion;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "quiz_id", referencedColumnName = "id_quiz")
    private Quiz quiz;
}

加载表单时,我在控制器中正在做的事情如下:

@GetMapping("/quiz")
    public String quizPage(Model model) {
        Quiz quiz = new Quiz();
                // At this point quiz.questions contains one question object with its quiz field set.
        model.addAttribute("quiz", quiz);

        return "teacher/quiz";
    }

然后将其发布到以下端点:

    @PostMapping("/process-quiz")
    public String processQuiz(@Valid @ModelAttribute Quiz quiz) {

        /*
// At this point, quiz.questions contains the question filled in the form but with its quiz field null
// I need to do this to set it again manually
                   for(Question question : quiz.getQuestions()) {
            question.setQuiz(quiz);
        }

*/
        quizService.save(quiz);

        return "redirect:/teacher";
    }

问题在于,当我加载表单时,我的Quiz正确添加了Question字段关联,并正确添加了quiz

但是当我发布表单时,这个Question的{​​{1}}字段为空

为什么会这样?

谢谢

0 个答案:

没有答案