hibernate中配置非主键关联(单向一对多)
hibernate中配置非主键关联(单向一对多)
表结构:
create table primaryTable(
primaryTableId int primary key,
refKey varchar(16)--被关联键,注意不是id
)ENGINE=innodb
create table childTable(
childTableId int primary key,
linkRefKey varchar(16)--关联到primaryTable表中的refKey
)ENGINE=innodb
hibernate映射文件:(注意红字部分)
primaryTable.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class
name="PrimaryTable"
table="primaryTable">
<id name="id" type="java.lang.Integer">
<column name="primaryTableId"/>
<generator type="java.lang.String">
<column name="refKey" length="16" />
</property> <set name="childTables" inverse="true">
<!-- <key column="linkRefKey外键属性" property-ref="refKey" />-->
<key column="linkRefKey" property-ref="refKey" />
<one-to-many />
</set>
</class>
</hibernate-mapping>
childTable.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="childTable" table="childTable">
<id name="id" type="java.lang.Integer">
<column name="childTableId" />
<generator type="java.lang.String">
<column name="linkRefKey" length="16" />
</property>
</class>
</hibernate-mapping>