天天看点

Hibernate一对多(多对一)外键设置汇总

我打算在角色表(role)中添加一个帐号表(account)的外键(accountId),步骤如下:

1、首先在角色表(role)中添加列。

         添加语句:alter table role add(accountid varchar2(50));

         添加语句时注意事项:单词之间的空格必须为英文空格,不可为中文空格;accountId添加后不可

         设为主键!

2、将accountId这一列设为外键,链接角色表(role)和帐号表(account)。 

         添加语句:alter table role add constraint fk_role_account foreign key(accountId)

         references account(id) on delete cascade;

         或:

         alter table role add constraint fk_role_account foreign key(accountId) references

         account(id) on delete set null;

    解释:constraint:约束,即外键约束。

          fk_role_account:外键名称。

          foreign key(accountId):将accountId设为外键。

          references:参照。

          account(id):account,帐号表明;id,外键accountId的参照列。

          on delete cascade和on delete set null:两个要害字,第一个的意思就是当帐号删除的时候,

         所有角色表中accountId与删除帐号id相同的角色信息删除;第二个的意思就是当帐号删除的时候,所

         有角色表中accountId与删除帐号id相同的角色accountId这一列清空。

3、在role.hbm.xml配置文件中添加多对一关系   

   代码如下:

        <many-to-one name="account" class="com.yuanit.app.model.Account" update="false"

        insert="false" fetch="select">

                  <column name="ACCOUNTID" length="50" />

        </many-to-one>

   解释:

        <many-to-one name="对应一对多中一的实体类的集合的属性" class="一对多中一的实体类

        的类名" update="false" insert="false" fetch="select">

                  <column name="对应其外键的字段" length="50" />

4、在account.hbm.xml配置文件中添加一对多关系

        <set name="roles" inverse="true" lazy="false" >

             <key>

                 <column name="ACCOUNTID" length="50"/>

             </key>

             <one-to-many class="com.yuanit.app.model.Role"/>

        </set>

    解释:

        <set name="对应一对多中多的实体类的集合的属性" inverse="true" lazy="false" >

                 <column name="对应其外键的字段" length="50"/>

             <one-to-many class="一对多中多的实体类的类名"/>

       </set>

5、在role的model中添加account集合及其set/get方法:

       private Account account;

       public void setAccount(Account account) {

           this.account = account;

       }

       public Account getAccount() {

           return account;

6、在account的model中添加roles集合及其set/get方法:

       private Set<Role> roles = new HashSet<Role>(0);

       public void setRoles(Set<Role> roles) {

          this.roles = roles;

       public Set<Role> getRoles() {

          return roles;