Hibernate关联映射4——多对多关联映射
一、多对多关联映射(每个员工拥有多个部门,每个部门也有多个员工)多对多关联映射关系使用中间表表示。导出关系模型时Hibernate将自动生成复合主键以及外键约束。
?
关系模型:
t_employee(id int pk, name varchar)
t_department(id int pk, name varchar)
t_employee_department(employeeid int fk->t_employee(id), departmentid int fk->t_department(id), pk(employeeid, departmentid))
1、多对多单向关联
实体模型:
com.lrh.hibernate.Employee(int id, String name, Set departments)
com.lrh.hibernate.Department(int id, String name)
?
配置文件:
<!-- com.lrh.hibernate/Employee.hbm.xml -->
?<hibernate-mapping>?
???? <class name="com.lrh.hibernate.Employee" table="t_employee">?
???????? <id name="id">?
??????????? <generator table="t_employee_department">?
???????????? <!-- <key>指定引用至自身的外键表(t_employee_department)中的外键 -->
???????????? <key column="employeeid"/>?
???????????? <!-- <many-to-many>映射多对多关系,column指定另一端在表t_employee_department中的列 -->
???????????? <many-to-many column="departmentid"/>?
???????? </set>?
???? </class>?
?</hibernate-mapping>
?<!-- com.lrh.hibernate/Department.hbm.xml -->
?<hibernate-mapping>?
???? <class name="com.lrh.hibernate.Department" table="t_department">?
???????? <id name="id"><generator table="t_employee">?
???????? <id name="id">?
???????????? <generator table="t_employee_department">?
???????????? <!-- <key>指定引用至自身的外键表(t_employee_department)中的外键 -->
??????????? <key column="employeeid"/>?
???????????? <!-- <many-to-many>映射多对多关系,column指定另一端在表t_employee_department中的列 -->
??????????? <many-to-many column="departmentid"/>?
???????? </set>?
???? </class>?
?</hibernate-mapping>
?
?
?<!-- com.lrh.hibernate/Department.hbm.xml -->
?<hibernate-mapping>?
???? <class name="com.lrh.hibernate.Department" table="t_department">?
???????? <id name="id">?
???????????? <generator table="t_employee_department">?
???????????? <!-- <key>指定引用至自身的外键表(t_employee_department)中的外键 -->
???????????? <key column="department"/>?
???????????? <!-- <many-to-many>映射多对多关系,column指定另一端在表t_employee_department中的列 -->
??????????? <many-to-many column="employeeid"/>?
???????? </set>?
???? </class>?
?</hibernate-mapping>