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:
<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:
public void updateParent(MyParent param) {
ht.saveOrUpdate(param);
}
UPDATE: I had used the wrong relation type (updated), bu开发者_运维百科t now I have another problem: It seems that when creating the child rows in the table, the parentid is null. Since parentid is part of the composite key, they insert fails.
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:
- Many-to-one should be declared in the MyChild class (if I understand correctly).
- When using @JoinColumn annotation with composite keys, referencedColumnName is mandatory. Maybe this applies to XML as well...? See http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_and_ManyToOne_Relationships
PS: if childid is already identifying (unique, not-null), there's no need to have the parentid in the key (FK would be enough).
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?
As Tom Anderson says, you'll need a many-to-one mapping on the child to the parent, and perhaps stick inverse=true on the parent set mapping to let hibernate know that the child manages the relationship.
精彩评论