我有以下三个表:
测验
问题
答案
questions_answers
问题有一个由quiz_id和question_id组成的复合PK。答案还有一个由quiz_id和answer_id组成的复合PK。
每个测验都有自己的问题和答案,这些问题和答案在多对多关系中(在测验的范围内)相互匹配。我知道这听起来有点奇怪,但问题可能有几个答案,一个答案也可能与不同的问题有关。
我正在尝试在QuestionEntity中实现这种关系。这是我班级的相关部分:
@Entity
@Table(name = "questions")
public class QuestionEntity implements Serializable {
@EmbeddedId
private QuestionPK primaryKey = new QuestionPK();
@ManyToMany
@JoinTable(
name = "questions_answers",
joinColumns = {
@JoinColumn(name = "quiz_id", referencedColumnName = "quiz_id"),
@JoinColumn(name = "question_id", referencedColumnName = "question_id")
},
inverseJoinColumns = {
@JoinColumn(name = "quiz_id", referencedColumnName = "quiz_id"),
@JoinColumn(name = "answer_id", referencedColumnName = "answer_id")
}
)
private List<AnswerEntity> keys = new ArrayList<AnswerEntity>();
}
我在编译时遇到以下错误:
Caused by: org.hibernate.MappingException: Repeated column in mapping for collection: ru.andrewquiz.dao.quiz.QuestionEntity.keys column: quiz_id
这是否意味着我必须在我的questions_answers表中创建2个单独的列:question_quiz_id和answer_quiz_id?虽然在我的例子中,它们总是包含对同一个测验的引用?
修改 我查看了@XtremeBaumer建议的示例:link。试图实现它,引入QuestionsAnswersEntity.class并根据示例更改其他类。我的QuestionsAnswersEntity类声明如下:
@Entity
@Table(name = "questions_answers")
@AssociationOverrides({
@AssociationOverride(name = "primaryKey.question",
joinColumns = {@JoinColumn(name = "quiz_id", referencedColumnName = "quiz_id"),
@JoinColumn(name = "question_id", referencedColumnName = "question_id")}),
@AssociationOverride(name = "primaryKey.answer",
joinColumns = {@JoinColumn(name = "quiz_id", referencedColumnName = "quiz_id"),
@JoinColumn(name = "answer_id", referencedColumnName = "answer_id")})
})
public class QuestionsAnswers implements Serializable {...}
然而,这似乎对我的问题没有多大影响,因为hibernate再次抱怨我的quiz_id列是两个不同表的外键的一部分。我得到了和以前一样的错误。