我有 2 个具有 OneToMany 映射的类。有一个问题类和一个答案类。对于每个问题,表中都有 4 个答案。表格中有 10 个问题行和相应的 40 个答案行现在,当我尝试获取列表时,它给了我 40 个问题而不是 10 个问题,每个问题有 4 个重复。
这是我的问题课:
@Entity
@Table(name = "QUESTIONS")
public class Question implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "QUES_ID_SEQ")
@SequenceGenerator(name = "QUES_ID_SEQ", sequenceName = "QUES_ID_SEQ")
@Column(name = "QUESTION_ID")
private Long id;
@Column(length = 255)
private String question;
@OneToMany(targetEntity = Answer.class, fetch = FetchType.EAGER)
@Cascade(CascadeType.SAVE_UPDATE)
@JoinTable(name = "QNA",
joinColumns = @JoinColumn(name = "QUESTION_ID"),
inverseJoinColumns = @JoinColumn(name = "ANSWER_ID", referencedColumnName = "ANSWER_ID"))
private List<Answer> answers;
public Question() {}
// getters and setters ...
}
这是我的答案类:
@Entity
@Table(name = "ANSWERS")
public class Answer implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ANS_ID_SEQ")
@SequenceGenerator(name = "ANS_ID_SEQ", sequenceName = "ANS_ID_SEQ")
@Column(name = "ANSWER_ID")
private Long id;
@Column(length = 255)
private String answer;
private boolean correct;
public Answer() {}
// getters and setters ...
}
我正在获取这样的问题:
@Transactional
public List<Question> retrieveQuestions(){
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Question.class);
return (List<Question>) criteria.list();
}