现在的位置: 首页 > 综合 > 正文

hibernate一对一唯一外键关联

2018年05月07日 ⁄ 综合 ⁄ 共 2035字 ⁄ 字号 评论关闭

一:

   hibernate的一对一唯一外键关联(单向),类图:

 一对一的外键关联可以采用<many-to-one>,指定多的一端unique=true,保证多的一方唯一性,Person.hbm.xml:

[xhtml] view
plain
copy

  1. <?xml version="1.0" encoding="ISO-8859-1"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  3.   
  4. <hibernate-mapping>  
  5.   <class table="_person" name="com.spl.model.Person">  
  6.     <id access="field" name="id">  
  7.       <generator class="native"/>  
  8.     </id>  
  9.     <property name="name" access="field"/>  
  10.     <property name="phone" access="field"/>  
  11.     <many-to-one unique="true" column="userId" access="field" name="user"/>  
  12.   </class>  
  13. </hibernate-mapping>  

其中<many-to-one unique="true" column="userId" access="field" name="user"/>表示对PersonUser一对一外键的关系配置。可以看出一对一的外键关联可是说是多对一得一种特例,只不过一对一的外键关联中设置了unique=true来保证多一方的唯一性。

要是使用Xdoclet来自动生成Person.hbm.xml配置文件时在Person类中Xdoclet相对应的配置:

[java] view
plain
copy

  1. /** 
  2.   * @hibernate.many-to-one  
  3.   * unique="true" 
  4.   * column="userId" 
  5.   */  
  6.  private User user;  

   这里要提醒的一点是,Myeclipse本身是支持Xdoclet的,写注解的时候也会自动提示,不过笔者在写的时候怎么也不给我自动补全,按Alt+/也无济于事,只有在类名前加注解的时候才会提示,后来无意间发现对于属性添加Xdoclet注解的时候,要是写在字段前是不会提示的,写在属性方法前就会提示,笔者这里是写在字段前的,就这个折腾了好久.......

 二:

   hibernate的一对一唯一外键关联(双向),类图:


对于双向关联,对数据库本身是没有影响的,只是在Hibernate的配置上略有不同,一对一外键双向关联需要在另一端User添加

<one-to-one>User.hbm.xml配置文件:

 

[xhtml] view
plain
copy

  1. <?xml version="1.0" encoding="ISO-8859-1"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">  
  3.   
  4. <hibernate-mapping>  
  5.   <class table="_user" name="com.spl.model.User">  
  6.     <id access="field" name="id">  
  7.       <generator class="native"/>  
  8.     </id>  
  9.     <property name="loginName" access="field"/>  
  10.     <property name="passWord" access="field"/>  
  11.     <one-to-one name="person" access="field" property-ref="user"/>  
  12.   </class>  
  13. </hibernate-mapping>  

 这里添加<one-to-one>应该为其指示应该如何加载Person,这里默认的是根据主键来加载,因为UserPerson之间的关系是由Person的外键关联起来的,所以要是不为User指定如何加载Person时,就会以默认的主键来加载,所以需要以外键来加载Person

property-ref="user"指定的是根据外键来加载。

抱歉!评论已关闭.