Answer the question
In order to leave comments, you need to log in
Why doesn't Hibenate create an entity?
There are Questions and Answers tables linked via @OneToMany and @ManyToOne. When adding an answer to a question, nothing happens.
Responsible controller
@Controller
@RequestMapping("/answers")
public class AnswersController {
private final String BASEDIR = "/answers";
private final AnswersDAO answersDAO;
private final QuestionsDAO questionsDAO;
public AnswersController(AnswersDAO answersDAO, QuestionsDAO questionsDAO) {
this.answersDAO = answersDAO;
this.questionsDAO = questionsDAO;
}
@GetMapping("")
public String main(){
return "redirect:".concat("/student");
}
@GetMapping("/new")
public String createAnswer(Model model) {
model.addAttribute("answer", new Answers());
model.addAttribute("questions", questionsDAO.getQuestionsList());
return BASEDIR.concat("/answers_create");
}
@PostMapping
public String create(@ModelAttribute(name = "answer") @Valid Answers answer,
BindingResult bindingResult) {
if (bindingResult.hasErrors())
return "redirect:".concat(BASEDIR.concat("/new"));
answersDAO.create(answer);
System.out.println(1111);
return "redirect:".concat(BASEDIR);
}
}
@Entity
public class Questions {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@NotEmpty
private String question;
@NotEmpty
private String author;
@NotEmpty
@Column(name = "correct_answer")
private String correctAnswer;
@OneToMany(mappedBy = "answer", cascade = CascadeType.ALL)
private List<Answers> answers;
public Questions() {
}
}
@Entity
@Table(name = "answers")
public class Answers {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@NotEmpty
@Column(name = "answer")
private String answer;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "question_id", foreignKey = @ForeignKey(name = "FK_QUESTION_ID"))
private Questions question;
public Answers() {
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form th:method="POST" th:action="@{/answers}" th:object="${answer}">
<label for="answer">Введите ответ</label>
<input type="text" th:field="*{answer}" id="answer">
<br>
<label for="questionsList">К какому вопросу?</label>
<select id="questionsList" name="question">
<option th:each="questionq : ${questions}"
th:text="${questionq.getQuestion()}"
th:value="${questionq}">
value
</option>
</select>
<br>
<input type="submit" value="Добавить">
</form>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question