我在设置OneToMany关系方面遇到了问题。
我的数据库架构:
TABLE PARENT (
VENDOR,
CHANNEL,
CREATEDATE,
REFID,
...
)
UNIQUE INDEX PK_PARENT (VENDOR, CHANNEL, CREATEDATE, REFID)
TABLE CHILD (
REFID,
NAME,
)
UNIQUE INDEX PK_CHILD (REFID, NAME)
和Java类
public class Parent {
String vendor;
String channel;
Date createdate;
Long refid;
List<Child> childs;
...
}
public class Child {
Long refid;
String name;
}
我的问题是我无法为这些类开发正确的映射。出于一致的原因,我被迫使用hbm xml。我能够将它映射为两个独立的实体。
<hibernate-mapping>
<class name="Parent" table="PARENT">
<composite-id >
<key-property name="vendor" type="string">
<column name="VENDOR" />
</key-property>
<key-property name="vendor" type="string">
<column name="CHANNEL" />
</key-property>
<key-property name="vendor" type="Date">
<column name="CREATEDATE" />
</key-property>
<key-property name="vendor" type="Long">
<column name="REFID" />
</key-property>
<composite-id />
<list name="childs" table="CHILD" lazy="true" fetch="select">
<key column="REFID" />
<index column="REFID" />
<one-to-many class="Child" />
</list>
</class>
<class name="Child" table="CHILD">
<composite-id >
<key-property name="vendor" type="Long">
<column name="REFID" />
</key-property>
<key-property name="name" type="string">
<column name="NAME" />
</key-property>
<composite-id />
</class>
</hibernate-mapping>
我得到例外:
Caused by: org.hibernate.MappingException: Foreign key (FK_9897tr114hxkewktsi9vb92x6:CHILD[REFID])) must have same number of columns as the referenced primary key (PARENT[VENDOR,CHANNEL,CREATEDATE,REFID])
at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:110)
at org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:93)
at org.hibernate.cfg.Configuration.secondPassCompileForeignKeys(Configuration.java:1818)
at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1741)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1426)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1930)
对此有何看法?
答案 0 :(得分:1)
因为您的Child实体具有复杂的键,因此在Parent实体中您还需要将外键指定为复数。
答案 1 :(得分:1)
根据hibernate配置xml文件中的java类字段更改属性名称。如果您的java类中有“channel”字段,那么它应该在您的hbm配置中命名为“channel”,尽管它是复合主键的一部分。
<class name="Parent" table="PARENT">
<composite-id >
<key-property name="vendor" type="string">
<column name="VENDOR" />
</key-property>
<key-property name="channel" type="string">
<column name="CHANNEL" />
</key-property>
<key-property name="createdate" type="Date">
<column name="CREATEDATE" />
</key-property>
<key-property name="refid" type="Long">
<column name="REFID" />
</key-property>
<composite-id />
<list name="childs" table="CHILD" lazy="true" fetch="select">
<key column="REFID" />
<index column="REFID" />
<one-to-many class="Child" />
</list>
此外,您应该在映射的另一侧定义manyToOne关系。并且子类中可以有一个Parent实例。(不仅仅是一个ID)