Hibernate关联映射4——多对多关联映射

一、多对多关联映射(每个员工拥有多个部门,每个部门也有多个员工)多对多关联映射关系使用中间表表示。导出关系模型时Hibernate将自动生成复合主键以及外键约束。

关系模型:

t_employee(idintpk,namevarchar)

t_department(idintpk,namevarchar)

t_employee_department(employeeid int fk->t_employee(id), departmentid int fk->t_department(id), pk(employeeid, departmentid))

1、多对多单向关联

实体模型:

com.lrh.hibernate.Employee(intid,Stringname,Setdepartments)

com.lrh.hibernate.Department(int id, String name)

配置文件:<!-- com.lrh.hibernate/Employee.hbm.xml -->

 <hibernate-mapping> 

<classname="com.lrh.hibernate.Employee"table="t_employee">

<idname="id">

<generatorclass="native"/>

</id>

<propertyname="name"/>

<!--<set>映射集合,在多对多关系中,Hibernate将生成中间表-->

<setname="departments"table="t_employee_department">

<!--<key>指定引用至自身的外键表(t_employee_department)中的外键-->

<keycolumn="employeeid"/>

<!--<many-to-many>映射多对多关系,column指定另一端在表t_employee_department中的列-->

<many-to-manyclass="com.lrh.hibernate.Department"column="departmentid"/>

</set>

</class>

 </hibernate-mapping>

 <!-- com.lrh.hibernate/Department.hbm.xml -->

<hibernate-mapping>

<classname="com.lrh.hibernate.Department"table="t_department">

<idname="id"><generatorclass="native"/></id>

<propertyname="name"/>

</class>

</hibernate-mapping>

2、多对多双向关联

实体模型:

com.lrh.hibernate.Employee(intid,Stringname,Setdepartments)

com.lrh.hibernate.Department(int id, String name, Set employees)

配置文件:

 <!-- com.lrh.hibernate/Employee.hbm.xml -->

 <hibernate-mapping> 

<classname="com.lrh.hibernate.Employee"table="t_employee">

<idname="id">

<generatorclass="native"/>

</id>

<propertyname="name"/>

<!--<set>映射集合,在多对多关系中,Hibernate将生成第三张表-->

<setname="departments"table="t_employee_department">

<!--<key>指定引用至自身的外键表(t_employee_department)中的外键-->

<keycolumn="employeeid"/>

<!--<many-to-many>映射多对多关系,column指定另一端在表t_employee_department中的列-->

<many-to-manyclass="com.lrh.hibernate.Department"column="departmentid"/>

</set>

</class>

</hibernate-mapping>

<!--com.lrh.hibernate/Department.hbm.xml-->

<hibernate-mapping>

<classname="com.lrh.hibernate.Department"table="t_department">

<idname="id">

<generatorclass="native"/>

</id>

<propertyname="name"/>

<!--<set>映射集合,在多对多关系中,Hibernate将生成第三张表-->

<setname="employees"table="t_employee_department">

<!--<key>指定引用至自身的外键表(t_employee_department)中的外键-->

<keycolumn="department"/>

<!--<many-to-many>映射多对多关系,column指定另一端在表t_employee_department中的列-->

<many-to-manyclass="com.lrh.hibernate.Employee"column="employeeid"/>

</set>

</class>

</hibernate-mapping>

相关推荐