Hibernate关系映射2——唯一外键关联
一、唯一外键关联映射: (每个员工只属于一个部门)
唯一外键关联生成的关系模型:
t_employee(idintpk,namevarchar,departmentidintfk->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>加上unique就变成了一对一-->
<many-to-onename="department"unique="true"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,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="native"/>
</id>
<propertyname="name"/>
<!--<many-to-one>加上unique='true'表示一对一-->
<many-to-onename="department"unique="true"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"/>
<!--
只需要在另一端(department)加入<one-to-one>标签,但是hibernate默认按照主键加载,所以要指示hibernate按照指定列来加载
-->
<one-to-onename="employee"property-ref="department"/>
</class>
</hibernate-mapping>