一段时间没使用过Hibernate了,对于Hibernate配置非主键关联方式基本遗忘了,现在整理一下:
一个 Area 对象对应多个 Nation 对象,以下配置双向多对一关联,其中各对象的属性分别为:
// Area对象属性列表
public class Area {
private Integer id;
private String areaCode; // 地区编码
private String cnName; // 地区中文名称
private String enName; // 地区英文名称
private Date created; // 创建时间
private Date updated; // 更新时间
private Set<Nation> nations = new HashSet<Nation>(0); // 国家列表
}
// Nation对象属性列表
public class Nation {
private Integer id;
private Area area; // 地区
private String nationCode;// 国家编码
private String cnName; // 国家中文名称
private String enName; // 国家英文名称
private Date created; // 创建时间
private Date updated; // 更新时间
}
<hibernate-mapping>
<class name="com.domain.Area" table="Area" catalog="test" optimistic-lock="version">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="areaCode" type="string">
<column name="areaCode" length="50" <span style="color:#ff0000;">not-null="true" unique="true"</span>/>
</property>
<property name="cnName" type="string">
<column name="cnName" length="50" />
</property>
<property name="enName" type="string">
<column name="enName" length="50" />
</property>
<property name="created" type="timestamp">
<column name="created" length="19" />
</property>
<property name="updated" type="timestamp">
<column name="updated" length="19" />
</property>
<set name="nations" table="Nation" inverse="true" lazy="true" fetch="select" cascade="all">
<span style="color:#ff0000;"><key column="areaCode" property-ref="areaCode" foreign-key="areaCode"/></span>
<one-to-many class="com.domain.Nation" />
</set>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="com.domain.Nation" table="Nation" catalog="test" optimistic-lock="version">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="nationCode" type="string">
<column name="nationCode" length="50" />
</property>
<property name="cnName" type="string">
<column name="cnName" length="50" />
</property>
<property name="enName" type="string">
<column name="enName" length="50" />
</property>
<property name="created" type="timestamp">
<column name="created" length="19" />
</property>
<property name="updated" type="timestamp">
<column name="updated" length="19" />
</property>
<span style="color:#ff0000;"><many-to-one name="area" column="areaCode" class="com.domain.Area" property-ref="areaCode" foreign-key="areaCode" fetch="select"/></span>
</class>
</hibernate-mapping>