Hibernate關聯映射(單項多對一和一對多、雙向一對多)

來源:互聯網
上載者:User

標籤:

  最近總是接觸著新的知識點來擴充自己的知識面;不停的讓自己在原地接觸天空的感覺真的很美好!!!革命沒有成功,程式員的我們怎麼能不努力呢......

 一、用員工和部門來剖析關聯映射的原理。

1)從這張可以看出我會站在員工的角度講述:(單向關聯)

  關係:(多個員工對應一個部門)多對一的關係

  意味:多個Emp對象只會引用一個Dept對象

  方法:在Emp類中定義一個Dept類型屬性,來引用所有關聯的Dept對象

eg.

  第一步建立兩個實體類省略

  第二步建立大配置

  

<?xml version=‘1.0‘ encoding=‘utf-8‘?><!DOCTYPE hibernate-configuration PUBLIC        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration>                <session-factory>        <!-- Database connection settings 資料庫連接設定-->        <!-- 驅動類 -->        <property name="connection.driver_class">oracle.jdbc.OracleDriver</property>        <!-- url地址 -->        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>        <property name="connection.username">sa</property>        <property name="connection.password">1</property>        <!-- SQL dialect  (SQL 方言) -->        <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>        <!-- Echo all executed SQL to stdout 在控制台列印多工緩衝的SQL語句 -->        <property name="show_sql">true</property>                        <!-- 格式化顯示SQL -->        <property name="format_sql">true</property>                    <!-- Drop and re-create the database schema on startup -->          <property name="hbm2ddl.auto">update</property>                     <!--  <property name="current_session_context_class">thread</property> -->         <!-- 配置Hibernate.cfg.xml開啟二級緩衝 -->           <property name="hibernate.cache.use_second_level_cache">true</property>          <!-- 配置二級緩衝的供應商 -->        <property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>         <!--  * 在hibernate.cfg.xml檔案中啟用查詢快取-->    <property name="hibernate.cache.use_query_cache">true</property>                                     <!-- 關聯小配置 -->         <mapping resource="cn/happy/entity/Dept.hbm.xml" />        <mapping resource="cn/happy/entity/Emp.hbm.xml" />                   <class-cache    usage="read-write" class="cn.happy.entity.Dept"/>    </session-factory></hibernate-configuration>

  第三步建立小配置Emp

  <!-- 植入一個Dept對象 : 多對一-->      <many-to-one name="dept" class="Dept" column="deptNo"></many-to-one> 關鍵代碼
   解析:<many-to-one>:元素建立了Dept屬性和Emp表的DEPTNo之間的映射關聯
      name:設定持久化類的屬性名稱
      column:name對應表的外鍵(Emp表的外鍵)
      class:設定持久化類的屬性類型
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.happy.entity">   <class name="Emp" table="EMP">      <id name="empId">        <generator class="sequence">          <param name="sequence">SEQ_NUM</param>        </generator>      </id>       <property name="empName" type="string"/>            <!-- 植入一個Dept對象 : 多對一-->      <many-to-one name="dept" class="Dept" column="deptNo"></many-to-one>   </class></hibernate-mapping>

第四步建立小配置Dept

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.happy.entity">   <class name="Dept" table="DEPT">   <!--  <cache usage="read-write"/> -->      <id name="deptNo">        <generator class="sequence">          <param name="sequence">SEQ_NUM</param>        </generator>      </id>       <property name="deptName"/>   </class></hibernate-mapping>

第五步就是測試類別

@Test        public void AddObjectToDept(){            Emp emps=new Emp();            emps.setEmpName("西麗");        Session session=HibernateUtil.currentSession();            Transaction tx = session.beginTransaction();        session.save(emps);        System.out.println("ok");        tx.commit();        HibernateUtil.closeSession();        }

第六步運行結果

上述結果:現將資料尋找一遍確保沒有在進行添加

 2)從可以看出我接下來就要站在部門Dept的角度剖析:(單項關聯)

   關係:(部門)一對多關聯

   意味:每一個Dept對象會引用一組Emp對象

   方法:Dept類中應該定義一個集合類型屬性,來引用所有關聯的Emp對象。

  與上述步驟唯一不同的就是Dept.hbm.xml的小配置

  關鍵代碼一對多<set name="emps">

                <key column="deptNo"></key>                <one-to-many class="Emp" />            </set>

 

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC     "-//Hibernate/Hibernate Mapping DTD 3.0//EN"    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.happy.entity">   <class name="Dept" table="DEPT">   <!--  <cache usage="read-write"/> -->      <id name="deptNo">        <generator class="sequence">          <param name="sequence">SEQ_NUM</param>        </generator>      </id>       <property name="deptName"/>      <set name="emps">        <key column="deptNo"></key>        <one-to-many class="Emp" />      </set>   </class></hibernate-mapping>

二、雙向關聯

  

如所示:滿足多對一和一對多的關聯就是雙向關聯。

三、cascade屬性

  問題:刪除Dept對象,並串聯刪除與Dept對象關聯的Emp對象

  解析:我們可以在<set>、<many-to-one>元素裡面寫cascade=“delete”屬性就能完成並串聯刪除

   

cascade屬性值               描述                    
none       當Session操縱當前對象,忽略其它的關聯對象   cascade的預設值none
save-update       儲存或者更新資料
delete     當通過Session的delete()方法刪除當前對象時會串聯刪除所有的關聯的對象
all     包含save—update和delete

      初學者的我理解所致,既有不足,請多多指教。

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.