Hibernate多對多關係映射

來源:互聯網
上載者:User

標籤:

 兩張表的多對多關係,在資料庫中通常是通過第三張中間表來實現的,第三張中間表放的是兩張表各自的主索引值,通過主鍵與主鍵的對應來體現表直接的關係。比如在許可權系統中,一個使用者可以擁有多種許可權,而一種許可權也可以授予多個使用者。

   在持久化對象設計的時候,角色和使用者都分別有一個集合來防止擁有它的使用者或角色。角色類的設計:

public class RolePO {
 private int id;
 
 private String name;
 
 private Set employees = new HashSet();

......

}

使用者類的設計:

public class EmployeePO {
 private int id;

 private String name;

 private Set roles = new HashSet();

......

}

映射對象關係對應檔配置如下:

RolePO.hbm.xml:

<hibernate-mapping>
 <class name="com.lovo.po.RolePO" table="t_role">
  <id name="id" column="r_id" type="int">
   <generator class="increment"></generator>
  </id>
  <property name="name" column="f_name" type="string"></property>
  <set name="employees" table="mapping" cascade="all" inverse="false">
   <key column="f_r_id"></key>
   <many-to-many class="com.lovo.po.EmployeePO" column="f__e_id"/>
  </set>
 </class>
</hibernate-mapping>

EmployeePO.hbm.xml:

<hibernate-mapping>
 <class name="com.lovo.po.EmployeePO" table="t_employee">
  <id name="id" column="e_id" type="int">
   <generator class="increment"></generator>
  </id>
  <property name="name" column="f_name" type="string"></property>
  <set name="roles" table="mapping" cascade="all" inverse="true">
   <key column="f_e_id"></key>
   <many-to-many class="com.lovo.po.RolePO" column="f_r_id"/>
  </set>
 </class>
</hibernate-mapping>
需要注意的是<key>中的column對應的是當前類在中間表中對應的欄位,即對方想要的外鍵,而<many-to-many class="com.lovo.po.RolePO" column="f_roleid"/>中的column指示的是中間表中本類想要的外鍵。還要注意的是inverse的值只能有一個為true,因為如果雙發都為true,那麼雙發都去維護關係,會造成中間關係表中出現重複的資料。在進行刪除的時候Hibernate會刪除id所對應的資訊和中間關係表中對應的資訊,如,刪除使用者

如:Hibernate: delete from mapping where f_e_id=?
Hibernate: delete from employee where e_id=?

Hibernate多對多關係映射

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.