我已经从课程中遗漏了所有其他属性等。我在 Question 中的所有列表都没有序列化。我添加了答案列表的示例。JSON 响应很好,只是“答案”为空。为什么?当我将测验对象打印到控制台时,它已完全初始化(是的,即使它是延迟加载的,存储库层中的自定义代码也会得到照顾)。我还使用调试器进行检查。
@XmlRootElement
public class Quiz {
private List<Question> questions;
public List<Question> getQuestions() {
return questions;
}
public void setQuestions(List<Question> questions) {
this.questions = questions;
}
}
public class Question {
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "QuestionId", nullable = false)
@XmlElementWrapper(name = "answers")
public List<Answer> getAnswers() {
return answers;
}
public void setAnswers(final List<Answer> answers) {
this.answers = answers;
}
}
@Entity
@Table(name = "Answer")
public class Answer {
}
编辑:
似乎未注释的代码造成了麻烦。切换评论使代码工作。
public void setAnswers(final List<Answer> answers) {
//this.answers = answers;
this.answers.clear();
for (Answer answer : answers) {
addAnswer(answer);
}
}
public void addAnswer(final Answer answer) {
if (!(answers.contains(answer))) {
checkThatOnlyOneAnswerMayBeCorrect(answer);
answers.add(answer);
}
}