单向1:1映射
相像一下一个员工只属于一个部门,站在员工的立场,就成了一对一了。
其实N:1与1:1的差别就是N与1的不同,其实把N变成1不就成了1:1了吗?怎么变呢?就是在之前的<many-to-one>中加入一个unique="true",其实这个unique属于数据库层次的限制,它将会限制department的id唯一,这样就直接导致了一个员工只能属于一个部门。
对于单向1:1无中间表的映射,不变的代码请参考单向N:1无中间表映射
更改的部分:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.longtech.hibernate.domain.Employee" table="Employee"> <id name="id" column="id" type="java.lang.Long" > <meta attribute="field-description">唯一标识</meta> <generator class="native"/> </id> <property name="name" type="java.lang.String" column="name" length="20"> <meta attribute="field-description">员工名称</meta> </property> <many-to-one name="department" column="dept_id" cascade="all" unique="true"></many-to-one> <!-- <join table="employ_depart"> <key column="empid"></key> <many-to-one name="department" cascade="all" column="deptid"></many-to-one> </join> --> </class> </hibernate-mapping>
单向1:1有中间表映射和单向N:1有中间表映射配置类似,改变的有
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.longtech.hibernate.domain.Employee" table="Employee"> <id name="id" column="id" type="java.lang.Long" > <meta attribute="field-description">唯一标识</meta> <generator class="native"/> </id> <property name="name" type="java.lang.String" column="name" length="20"> <meta attribute="field-description">员工名称</meta> </property> <!-- <many-to-one name="department" column="dept_id" cascade="all"></many-to-one> --> <join table="employ_depart"> <key column="empid"></key> <many-to-one name="department" cascade="all" column="deptid" unique="true"></many-to-one> </join> </class> </hibernate-mapping>
另外,还有一种方式就是基于外键的单向1:1关系,想一下,既然1员工对应1部门并且始终是1:1,那么为什么要每张表中用一个字段来记录主键信息呢,为什么不只在一张表中记录就好了?于是,就有了下面一种配置方式。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.longtech.hibernate.domain.Employee" table="Employee"> <id name="id" column="id" type="java.lang.Long" > <!-- <meta attribute="field-description">唯一标识</meta> <generator class="native"/> --> <generator class="foreign"> <param name="property">department</param> </generator> </id> <property name="name" type="java.lang.String" column="name" length="20"> <meta attribute="field-description">员工名称</meta> </property> <!-- <many-to-one name="department" column="dept_id" cascade="all"></many-to-one> --> <!-- <join table="employ_depart"> <key column="empid"></key> <many-to-one name="department" cascade="all" column="deptid" unique="true"></many-to-one> </join> --> <one-to-one name="department"></one-to-one> </class> </hibernate-mapping>
这种方式需要使用<one-to-one>标签,它需要指定一个name属性,作为关联时的属性名。