Hibernate 关联映射
单向 many-to-one 关联
在有外键的表对应的实体里加上一方实体作为字段,在 xml 里加上 many-to-one
双向 one-to-many 关联
在一的一方加上多的 set 集合作为字段 , 在 xml 里加上 one-to-many
双向 many-to-many 关联
多对一单向关联(和关系数据库的外键参照关系匹配 )
示例: Item 类 SubItem 类
Public class Item{
private Integer itemId;
private String itemName;
private String itemCode;
}
Public class SubItem{ subitem 表中 itemid 是 item 表的外键
private Integer subId;
private String subName;
private Item item;
private Integer subCode;
}
Item.hbm.xml 与 item 表中的字段一一对应即可。
< hibernate-mapping >
< class name = "com.pojo.Item" table = "item" catalog = "gdev" >
< id name = "itemId" type = "java.lang.Integer" >
< column name = "itemid" />
< generator class = "sequence" >
< param name = "sequence" > sequence_ip_info </ param >
</ generator >
</ id >
< property name = "itemName" type = "java.lang.String" >
< column name = "itemname" length = "32" not-null=”true” />
</ property >
< property name = "itemCode" type = "java.lang.String" >
< column name = "itemcode” length=”32” not-null=”true” />
</ property >
</ class >
</ hibernate-mapping >
SubItem.hbm.xml
< hibernate-mapping >
< class name = "com.pojo.SubItem" table = "subitem" catalog = "gdev" >
< id name = "subId" type = "java.lang.Integer" >
< column name = "subid" />
< generator class = "sequence" >
< param name = "sequence" > sequence_ip_info </ param >
</ generator >
</ id >
< property name = "subName" type = "java.lang.String" >
< column name = "subname" length = "32" not-null=”true” />
</ property >
< property name = "subCode" type = "java.lang.String" >
< column name = "subcode” length=”32” not-null=”true” />
</ property >
<many-to-one name="item" column=”itemid” class=”com.pojo.Item”/>
</ class >
</ hibernate-mapping >
注解: <many-to-one> 元素建立了 item 属性和 subitem 表的外键 itemid 的映射关系,实现了可以通过 many 方得到 one 方相关的数据。
双向一对多关联(有外键关系)
如果想得到给定的 Item 对象所关联的 subItem 对象怎么办呢?
接上边
Item 实体里加上
private Set subItems=new HashSet();
get/set() 方法
Item.hbm.xml 里边加入
<set name=”subItems” >
<key column=”itemid”/>
<one-to-many class=”com.pojo.SubItem”/>
</set>
如果要删除一个 Item 元素,那么相关的 SubItem 元素也要删除,所以加上
<set name=”subItems” cascade=”all” inverse=”true” >
<key column=”itemid”/>
<one-to-many class=”com.pojo.SubItem”/>
</set>
inverse : 表示关系的维护由谁来执行。 true 表示不由自己执行,而由对应的另外一方执行。
Cascade : 表示是否进行级联操作。 all: 表示所有的操作都进行级联。
双向多对多关联 ( 在数据库设计时,要加一个表 tea_stu_relation )
必须把其中一端的属性的 inverse 设为 true, 关联的两端都可以使用 <set> 元素。
例如:一个老师可以教多个学生,一个学生要上多个老师的课。
Student 类
private Set teachers=new HashSet();
Teacher 类
private Set students=new HashSet();
Teacher.hbm.xml
<set name=”students” table=” tea_stu_relation” inverse=”true” cascade=”all”>
<key column=”teaid”/>
<many-to-many class=”com.hibernate3.pojo.student” column=”stuid”/>
</set>
Student.hbm.xml
<set name=”teachers” table=” tea_stu_relation” >
<key column=”stuid”/>
<many-to-many class=”com.hibernate3.pojo.Teacher” column=”teaid”/>
</set>