天天看點

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;