使用Thymeleaf形式保存两个实体之间的一对多双向关联

时间:2019-04-07 11:10:33

标签: java hibernate spring-boot spring-mvc thymeleaf

我正在尝试保存两个实体QuizQuestion之间的双向关联,其中@One端实体(Quiz)是{{1 }}我的Thymeleaf表格。

这是th:object实体:

Quiz

这是@Data @ToString(exclude = { "subject", "questions" }) @Entity @Table(name = "quiz", uniqueConstraints = @UniqueConstraint (columnNames="id_quiz")) public class Quiz implements Serializable { private static final long serialVersionUID = 7899292643417556205L; @Id @Column(name = "id_quiz") @GeneratedValue(strategy = GenerationType.IDENTITY) private int idQuiz; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "subject_code", referencedColumnName = "code", nullable = false) private Subject subject; @JsonIgnore @OneToMany(mappedBy = "quiz", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private Set<Question> questions = new HashSet<>(); public Quiz() { addQuestion(new Question()); } public void addQuestion(Question question) { this.questions.add(question); question.setQuiz(this); } public void removeQuestion(Question question) { this.questions.remove(question); question.setQuiz(this); } } 实体:

Question

@Data @ToString(exclude = { "quiz", "answers" }) @Entity @Table(name = "question", uniqueConstraints = @UniqueConstraint (columnNames="id_question")) public class Question implements Serializable { private static final long serialVersionUID = -8286865818098612133L; @Id @Column(name = "id_question") @GeneratedValue(strategy = GenerationType.IDENTITY) private int idQuestion; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "quiz_id", referencedColumnName = "id_quiz", nullable = false) private Quiz quiz; @Column(name = "question") @NotNull private String question; } GET格式的控制器方法是:

POST

到目前为止,我已经尝试将 @GetMapping("/quiz") public String quizPage(@RequestParam(name = "edit", required = false) Integer quizId, Model model, HttpSession session) { if(quizId != null) { model.addAttribute("edit", true); } Quiz quiz = (quizId == null ? new Quiz() : quizService.find(quizId)); model.addAttribute("quiz", quiz); model.addAttribute("questions", quiz.getQuestions()); int teacherNiu = (int) session.getAttribute(SessionConstants.USER_NIU); model.addAttribute("subjects", subjectService.getSubjectsByUser(teacherNiu)); return "teacher/quiz"; } @PostMapping("/process-quiz") public String processQuiz(@RequestParam("publish") boolean publish, @Valid @ModelAttribute Quiz quiz) { quiz.setEnabled(publish); quizService.save(quiz); return "redirect:/teacher"; } 集合作为@Many的形式包含在表单中,并使用th:field表示法将其字段绑定:

*{}

但是当我尝试提交表单时,出现以下错误: <form th:object="${quiz}" th:action="@{/teacher/process-quiz}" method="POST"> <div th:each="question, iter : ${questions}" th:id="${'question-' + iter.index}"> <input type="text" th:field="*{questions[__${iter.index}__].question}" required /> </div> </form>

我不知道我是否做对了,但是我找不到其他方法。

请帮助我们。

0 个答案:

没有答案