您的位置:首页 > 其它

hibernate一对一唯一外键关联

2014-08-06 14:57 316 查看
一:

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



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

[xhtml] view
plaincopy

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class table="_person" name="com.spl.model.Person">

<id access="field" name="id">

<generator class="native"/>

</id>

<property name="name" access="field"/>

<property name="phone" access="field"/>

<many-to-one unique="true" column="userId" access="field" name="user"/>

</class>

</hibernate-mapping>

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

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

[java] view
plaincopy

/**

* @hibernate.many-to-one

* unique="true"

* column="userId"

*/

private User user;

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

二:

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



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

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

[xhtml] view
plaincopy

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class table="_user" name="com.spl.model.User">

<id access="field" name="id">

<generator class="native"/>

</id>

<property name="loginName" access="field"/>

<property name="passWord" access="field"/>

<one-to-one name="person" access="field" property-ref="user"/>

</class>

</hibernate-mapping>

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

property-ref="user"指定的是根据外键来加载。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: