一对多,多对一,自关联的配置

1. 多对一的配置

<many-to-one name="parent" column="pid" class="Party" cascade="all"/>

配在"多"表中即可。parent 是类中的属性名, column="pid"是 对应表中的存储列

注意,数据库中需要在“多”表中加上外键,关联“一”表。 "多"表中也得有一列来存储“一”表的一列。

“一”表的那列需要是key在mysql中。

alter table onetablexxx add constraint xxxx foreign key (xxx) reference manyTbale(key);

2. 一对多的配置

一的类中加上Set<xx>=new HashSet<xxx>();或者List之类的集合

hbm.xml中配上。key column是多表中的存储列,one-to-many配的是对应多表的类名

<set name="teachers" cascade="all" lazy="extra">
  <key column="studentid"/>
  <one-to-many class="Teacher"/>
</set>

3. 自关联的配置

自己可能拥有自己的情况。可能有parent,也有children的情况。

按照上面一对多,多对一的配置进行配置。class都写本身的类。

<many-to-one name="parent" column="pid" class="Party" cascade="all"/>
<set name="children" cascade="all">
<key column="pid"/>
<one-to-many class="Party" />
</set>

原文地址:https://www.cnblogs.com/unixshell/p/3417227.html