Hibernate关系映射3——多对一和一对多关联映射

一、多对一和一对多关联映射(多个员工属于同一部门)这几种关联映射后的关系模型都是一致的:

t_employee(id int pk, name varchar, departmentid int fk->t_department(id)) t_department(id int pk, name varchar)

1、多对一单向关联

实体模型:

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

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"/>

<!--<many-to-one>映射多对一关系。导出ddl时将自动生成一个外键-->

<many-to-onename="department"column="departmentid"/>

</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)

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"/>

</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"/>

<setname="employees">

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

<keycolumn="departmentid"/>

<!--<one-to-many>映射一对多关系-->

<one-to-manyclass="com.lrh.hibernate.Employee"/>

</set>

</class>

 </hibernate-mapping>

3、双向关联

实体模型:

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

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"/>

<!--<many-to-one>映射多对一关系-->

<many-to-onename="department"column="departmentid"/>

</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>加入”inverse=true”可以反转维护关系:

Hibernate将放弃从一的一端维护。也就是employee和department的关系必须使用employee维护,

操作department时Hibernate将不维护这个关系。

-->

<setname="employees">

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

<keycolumn="departmentid"/>

<!--<one-to-many>映射一对多关系-->

<one-to-manyclass="com.lrh.hibernate.Employee"/>

</set>

</class>

 </hibernate-mapping>

相关推荐