[英]How do I map a many-to-one association in Hibernate where the child has a composite key and a part of that is the primary key in the parent?
I have a (legacy) table structure that looks a little bit like this: 我有一个(旧式)表结构,看起来有点像这样:
table parent (
parentid int (PK)
...
)
table child (
parentid int (PK)
childid int (PK)
...
)
That is, part of the primary key of child is the primary key for parent. 也就是说,子级主键的一部分是父级的主键。 I have tried to map this (we use xml-based Hibernate) like this:
我试图像这样映射此(我们使用基于xml的Hibernate):
<hibernate-mapping>
<class name="com.example.MyParent" table="parent">
<id name="parentid" column="parentid" unsaved-value="0" >
<generator class="identity"/>
</id>
<set name="children" cascade="all">
<key>
<column name="parentid"/>
</key>
<one-to-many class="com.example.MyChild" />
</set>
...
</class>
<class name="com.example.MyChild" table="child">
<composite-id name="id" class="com.example.MyChildId">
<key-property name="parentid" column="parentid" />
<key-property name="childid" column="childid" />
</composite-id>
...
</class>
Java class: Java类:
public void updateParent(MyParent param) {
ht.saveOrUpdate(param);
}
UPDATE: I had used the wrong relation type (updated), but now I have another problem: It seems that when creating the child rows in the table, the parentid is null. 更新:我使用了错误的关系类型(已更新),但是现在我遇到了另一个问题:似乎在表中创建子行时,parentid为null。 Since parentid is part of the composite key, they insert fails.
由于parentid是组合键的一部分,因此插入失败。
From the log: 从日志中:
DEBUG SQL - insert into Child(PARENTID, CHILDID) values (?, ?)
TRACE IntegerType - binding null to parameter: 1
TRACE IntegerType - binding '5678' to parameter: 2
WARN JDBCExceptionReporter - SQL Error: -10, SQLState: 23502
ERROR JDBCExceptionReporter - integrity constraint violation: NOT NULL check constraint; SYS_CT_10028 table: Child
I think you have two issues here: 我认为您在这里有两个问题:
PS: if childid is already identifying (unique, not-null), there's no need to have the parentid in the key (FK would be enough). PS:如果childid已经可以识别(唯一,非null),则无需在密钥中包含parentid(FK就足够了)。
What's in the ...
in the child mapping? 子映射中的
...
中有什么? Does it by any chance declare a property called parent which is mapped to the parentid column? 它是否有机会声明一个称为parent的属性,该属性映射到parentid列?
正如汤姆·安德森(Tom Anderson)所说,您将需要在子代与父代之间进行多对一映射,并且可能在父集映射上使用inverse = true,以使休眠状态知道子代正在管理该关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.