我有两个表:
<class name="Content" table="language_content" lazy="false">
<composite-id>
<key-property name="contentID" column="contentID"/>
<key-property name="languageID" column="languageID"/>
</composite-id>
<property name="Content" column="Content" />
</class>
和
<class name="SecretQuestion" table="secretquestions" lazy="true">
<id name="questionID" type="integer" column="QuestionID">
<generator class="increment"></generator>
</id>
<property name="question" column="Question"/>
<property name="isUsing" column="IsUsing"/>
<bag name="contents" inverse="true" cascade="all,delete-orphan">
<key column="question" />
<one-to-many class="Content" />
</bag>
</class>
我试图将 SecretQuestion 的“question”属性映射到 Content 的“contentID”属性,但 Eclipse 抛出异常:
org.hibernate.exception.SQLGrammarException: could not initialize a collection: [com.sms.model.entity.SecretQuestion.contents#1]
如果我替换 <key column="question" />
与 <key column="contentID" />
,它可以运行但映射了错误的数据(实际上,据我所知,它将问题 ID 映射到内容的 contentID)
有人知道如何实现我在这里想要实现的目标吗?
谢谢。
更新
好的,按照 Pascal 所说的修改后,这是新的错误:
javax.servlet.ServletException: org.hibernate.MappingException: Foreign key (FKB65C9692FCD05581:language_content [contentID,languageID])) must have same number of columns as the referenced primary key (secretquestions [QuestionID])
这个错误意味着我必须有一个我不想要的 secretquestions 表的复合主键:(
更新
我将举一个例子来更清楚地说明我想做什么:
Table SecretQuestion
questionID* question answer
1 4 a
2 5 a
3 6 a
Table Content
contentID* languageID* content
1 1 a
1 2 b
2 1 c
2 2 d
3 1 e
3 2 f
4 1 g
4 2 h
5 1 i
5 2 j
6 1 k
6 2 l
现在我想将问题 4、5、6 映射到内容 ID 4、5、6。
最佳答案
看起来这种方法行不通并且不受 Hibernate 支持(Content 表具有复合主键,而我只想将其映射到 Question 表中的一个字段),因此我使用了一种仅映射问题的解决方法到 contentID,我使用 ContentGetter 类,该类将根据 languageID 获取内容。
关于java - Hibernate 一对多映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3633060/