hibernate 雙向n-n

來源:互聯網
上載者:User

標籤:des   c   style   class   blog   code   

  • 領域模型:

  • 關係資料模型

  • 雙向 n-n 關聯需要兩端都使用集合屬性
  • 雙向n-n關聯必須使用串連表
  • 集合屬性應增加 key 子項目用以映射外鍵列, 集合元素裡還應增加many-to-many子項目關聯實體類
  • 在雙向 n-n 關聯的兩邊都需指定串連表的表名及外鍵列的列名. 兩個集合元素 set 的table 元素的值必須指定,而且必須相同。set元素的兩個子項目:key 和 many-to-many 都必須指定 column 屬性,其中,key 和 many-to-many 分別指定本持久化類和關聯類別在串連表中的外鍵列名,因此兩邊的 key 與 many-to-many 的column屬性交叉相同。也就是說,一邊的set元素的key的 cloumn值為a,many-to-many 的 column 為b;則另一邊的 set 元素的 key 的 column 值 b,many-to-many的 column 值為 a. 
  • 對於雙向 n-n 關聯, 必須把其中一端的 inverse 設定為 true, 否則兩端都維護關聯關係可能會造成主鍵衝突.



代碼詳解:Category.java
package com.atguigu.hibernate.n2n;import java.util.HashSet;import java.util.Set;public class Category {private Integer id;private String name;private Set<Item> items = new HashSet<>();public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Set<Item> getItems() {return items;}public void setItems(Set<Item> items) {this.items = items;}}

Item.java
package com.atguigu.hibernate.n2n;import java.util.HashSet;import java.util.Set;public class Item {private Integer id;private String name;private Set<Category> categories = new HashSet<>();public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Set<Category> getCategories() {return categories;}public void setCategories(Set<Category> categories) {this.categories = categories;}}

Category.hbm.xml
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="com.atguigu.hibernate.n2n">    <class name="Category" table="CATEGORIES">            <id name="id" type="java.lang.Integer">            <column name="ID" />            <generator class="native" />        </id>            <property name="name" type="java.lang.String">            <column name="NAME" />        </property>                <!-- table: 指定中間表 -->        <set name="items" table="CATEGORIES_ITEMS">            <key>                <column name="C_ID" />            </key>            <!-- 使用 many-to-many 指定多對多的關聯關係. column 執行 Set 集合中的持久化類在中間表的外鍵列的名稱  -->            <many-to-many class="Item" column="I_ID"></many-to-many>        </set>            </class></hibernate-mapping>

Item.hbm.xml
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>    <class name="com.atguigu.hibernate.n2n.Item" table="ITEMS">                <id name="id" type="java.lang.Integer">            <column name="ID" />            <generator class="native" />        </id>                <property name="name" type="java.lang.String">            <column name="NAME" />        </property>                <set name="categories" table="CATEGORIES_ITEMS" inverse="true">        <key column="I_ID"></key>        <many-to-many class="com.atguigu.hibernate.n2n.Category" column="C_ID"></many-to-many>        </set>            </class></hibernate-mapping>


package com.atguigu.hibernate.n2n;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.sql.Blob;import java.sql.Connection;import java.sql.SQLException;import java.util.Date;import java.util.Set;import org.hibernate.Hibernate;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.hibernate.jdbc.Work;import org.hibernate.service.ServiceRegistry;import org.hibernate.service.ServiceRegistryBuilder;import org.junit.After;import org.junit.Before;import org.junit.Test;public class HibernateTest {private SessionFactory sessionFactory;private Session session;private Transaction transaction;@Beforepublic void init(){Configuration configuration = new Configuration().configure();ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())                            .buildServiceRegistry();sessionFactory = configuration.buildSessionFactory(serviceRegistry);session = sessionFactory.openSession();transaction = session.beginTransaction();}@Afterpublic void destroy(){transaction.commit();session.close();sessionFactory.close();}@Testpublic void testGet(){Category category = (Category) session.get(Category.class, 1);System.out.println(category.getName()); //需要串連中間表Set<Item> items = category.getItems();System.out.println(items.size()); }@Testpublic void testSave(){Category category1 = new Category();category1.setName("C-AA");Category category2 = new Category();category2.setName("C-BB");Item item1 = new Item();item1.setName("I-AA");Item item2 = new Item();item2.setName("I-BB");//設定關聯關係category1.getItems().add(item1);category1.getItems().add(item2);category2.getItems().add(item1);category2.getItems().add(item2);item1.getCategories().add(category1);item1.getCategories().add(category2);item2.getCategories().add(category1);item2.getCategories().add(category2);//執行儲存操作session.save(category1);session.save(category2);session.save(item1);session.save(item2);}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.