`
cheng330301560
  • 浏览: 174480 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Hibernate中一对一关联

阅读更多

在hibernate中实现一对一的关联有两种方法,分别是共享主键关联和唯一外键关联

 

(1)共享主键关联

有两个表 user和profile

 

user表中有id(主键) username password

 

profile表中有id(主键) email phone

 

其实profile表正是从user表中分割出来的,

 

设置相应的类User类,和profile类

 

user类中的字段

    private Integer id;
    private String username;
    private String password;
    private Profile profile;

生成对应的get/set方法

 

profile表中的字段

    private Integer id;
    private String email;
    private String phone;
    private User user;

生成对应的get/set方法

 

在User.hbm.xml中

    <class name="com.cheng.entry.User" table="user">
        <id name="id" type="java.lang.Integer">
            <column name="id"></column>
            <generator class="native"></generator>
        </id>
        <property name="username" type="java.lang.String">
            <column name="username" length="200"></column>
        </property>
        <property name="password" type="java.lang.String">
            <column name="password" length="200"></column>
        </property>
        <one-to-one name="profile(这个就是user表中设置的属性)" class="com.cheng.entry.Profile"></one-to-one>
    </class>

 

 

 

在Profile.hbm.xml中

    <class name="com.cheng.entry.Profile" table="profile">
        <id name="id" type="java.lang.Integer">
            <column name="id"></column>
            <generator class="foreign">//注意这里有变化
                <param name="property">user(这个就是profile类中的属性)</param>
            </generator>
        </id>
        <property name="email" type="java.lang.String">
            <column name="email" length="200"></column>
        </property>
        <property name="phone" type="java.lang.String">
            <column name="phone" length="200"></column>
        </property>
        <one-to-one name="user" class="com.cheng.entry.User"></one-to-one>
    </class>

 

 

(2)唯一外键关联

在上面的profile表中修改一下,增加一个外键关联到user表中u_id,而原来的id设置为自动增长。

修改Profile.hbm.xml文件

 

    <class name="com.cheng.entry.Profile" table="profile">
        <id name="id" type="java.lang.Integer">
            <column name="id"></column>
            <generator class="native"></generator>
        </id>
        <property name="email" type="java.lang.String">
            <column name="email" length="200"></column>
        </property>
        <property name="phone" type="java.lang.String">
            <column name="phone" length="200"></column>
        </property>
        <many-to-one name="user" class="com.cheng.entry.User" unique="true">
            <column name="u_id"></column>
        </many-to-one>

    </class>

 

红色的字体表示修改过的

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics