Hibernate一对一唯一外键关联:
就是多对一的特列,把外键设置成unique为true。
采用<many-to-one name="idCard" unique="true"/>
单向:
Person.hbm.xml
<hibernate-mapping>
<class name="com.bjsxt.hibernate.Person" table="t_person">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<many-to-one name="idCard" unique="true"/>
</class>
</hibernate-mapping>
IdCard.hbm.xml
<hibernate-mapping>
<class name="com.bjsxt.hibernate.IdCard" table="t_idcard">
<id name="id">
<generator class="native"/>
</id>
<property name="cardNo"/>
</class>
</hibernate-mapping>
双向:
需要在另一端添加<one-to-one name="person" property-ref="idCard"/>,指示hibernate如何加载关联对象,默认根据主键关联,采用外键关联需要采用property-ref="idCard"
<hibernate-mapping>
<class name="com.bjsxt.hibernate.Person" table="t_person">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<many-to-one name="idCard" unique="true"/>
</class>
</hibernate-mapping>
IdCard.hbm.xml
<hibernate-mapping>
<class name="com.bjsxt.hibernate.IdCard" table="t_idcard">
<id name="id">
<generator class="native"/>
</id>
<property name="cardNo"/>
<one-to-one name="person" property-ref="idCard"/>
</class>
</hibernate-mapping>