hibernate中配置非主键关联(单向一对多)
hibernate中配置非主键关联(单向一对多)
表结构:
createtableprimaryTable(
primaryTableIdintprimarykey,
refKeyvarchar(16)--被关联键,注意不是id
)ENGINE=innodb
createtablechildTable(
childTableIdintprimarykey,
linkRefKeyvarchar(16)--关联到primaryTable表中的refKey
)ENGINE=innodb
hibernate映射文件:(注意红字部分)
primaryTable.hbm.xml
<?xmlversion="1.0"encoding="utf-8"?>
<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class
name="PrimaryTable"
table="primaryTable">
<idname="id"type="java.lang.Integer">
<columnname="primaryTableId"/>
<generatorclass="assigned"></generator>
</id>
<!--refKey属性必须写,否则hibernate会说找不到这个属性-->
<propertyname="refKey"type="java.lang.String">
<columnname="refKey"length="16"/>
</property><setname="childTables"inverse="true">
<!--<keycolumn="linkRefKey外键属性"property-ref="refKey"/>-->
<keycolumn="linkRefKey"property-ref="refKey"/>
<one-to-manyclass="childTable"/>
</set>
</class>
</hibernate-mapping>
childTable.hbm.xml
<?xmlversion="1.0"encoding="utf-8"?>
<!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/HibernateMappingDTD3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<classname="childTable"table="childTable">
<idname="id"type="java.lang.Integer">
<columnname="childTableId"/>
<generatorclass="assigned"></generator>
</id>
<propertyname="linkRefKey"type="java.lang.String">
<columnname="linkRefKey"length="16"/>
</property>
</class>
</hibernate-mapping>