TomasEdision 2011-10-24
主键关联生成的关系模型: (每个员工只属于一个部门)
t_employee(idintpkfk->t_department(id),namevarchar)
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">
<!--采用foreign生成策略,Employee的主键来源Department,forgeign会取得关联对象的标识-->
<generatorclass="foreign">
<!--指定要参照的属性-->
<paramname="property">department</param>
</generator>
</id>
<propertyname="name"/>
<!--one-to-one标签的含义,表明hibernate如何加载它的关联对象,默认是根据主键加载,
constrained="true",表明当前主键上存在一个约束,当前主键(Employee的主键)还是一个外键
参照了对端的主键(Department的主键)
-->
<one-to-onename="department"constrained="true"/>
</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,Departmentdepartment)
com.lrh.hibernate.Department(int id, String name, Employee employee)配置文件:
<!--com.lrh.hibernate/Employee.hbm.xml-->
<hibernate-mapping>
<classname="com.lrh.hibernate.Employee"table="t_employee">
<idname="id">
<!--指定主键生成策略为外键-->
<generatorclass="foreign">
<!--指定要参照的属性-->
<paramname="property">department</param>
</generator>
</id>
<propertyname="name"/>
<!--使用<one-to-one>映射一对一关系。-->
<one-to-onename="department">
</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"/>
<!--
需要在Department映射文件中加入<one-to-one>标签指向employee,指示hibernate如何加载employee
默认根据主键加载
-->
<one-to-onename="employee"/>
</class>
</hibernate-mapping>