1. 程式人生 > >Hibernate入門(八)級聯刪除

Hibernate入門(八)級聯刪除

Hibernate級聯刪除

  上一篇文章學習了級聯儲存和更新,這個級聯刪除應該很好理解的。一樣的道理,刪除一方,同時刪除有關聯的一方。

  同樣有方向性。

  刪除客戶,客戶下的訂單也同樣刪除。

  使用者表:

  

  訂單表:

業務:刪除id值為1的客戶,想要的效果:同時刪除id值為1的客戶下的所有訂單

1.配置customer.hbm.xml檔案(cascade = "delete")

<!-- 配置一對多屬性 -->
        <set name="ods" cascade="delete">
            <
key column="cust_order_id" ></key> <one-to-many class="Order"/> </set>

2.java測試類

/**
     * 刪除id值為1的使用者,級聯刪除該使用者下的訂單
     */
    @Test
    public void fun(){
        Session session = HibernateUtils.getSession();
        session.getTransaction().begin();
        
        
try { //獲取id值為1的使用者 持久態 Customer cst = session.get(Customer.class, 1); session.delete(cst); } catch (Exception e) { session.getTransaction().rollback(); // TODO Auto-generated catch block e.printStackTrace(); } session.getTransaction().commit(); }

 

 

 

 

 生成的SQL語句

Hibernate: 
    select
        customer0_.cust_id as cust_id1_0_0_,
        customer0_.cust_name as cust_nam2_0_0_,
        customer0_.cust_gender as cust_gen3_0_0_,
        customer0_.cust_age as cust_age4_0_0_,
        customer0_.cust_phone as cust_pho5_0_0_ 
    from
        customera customer0_ 
    where
        customer0_.cust_id=?
Hibernate: 
    select
        ods0_.cust_order_id as cust_ord3_1_0_,
        ods0_.order_id as order_id1_1_0_,
        ods0_.order_id as order_id1_1_1_,
        ods0_.detail_id as detail_i2_1_1_,
        ods0_.cust_order_id as cust_ord3_1_1_ 
    from
        ordersa ods0_ 
    where
        ods0_.cust_order_id=?
Hibernate: 
    update
        ordersa 
    set
        cust_order_id=null 
    where
        cust_order_id=?
Hibernate: 
    delete 
    from
        ordersa 
    where
        order_id=?
Hibernate: 
    delete 
    from
        ordersa 
    where
        order_id=?
Hibernate: 
    delete 
    from
        customera 
    where
        cust_id=?

很明顯,刪除了id為1的客戶同時,刪除了該客戶下的訂單

 

然後翻轉方向,刪除訂單,同時刪除有這個訂單的所有客戶(雖然應該不會有這種奇怪的需求把....hah )

一樣的配置和java程式碼編寫後同樣是測試成功了。

提示:最好在測試第二個之前,要把customer.hbm.xml配置中的級聯刪除的屬性去掉,不然訂單刪除,然後刪除級聯的客戶,客戶刪除後,又級聯刪除該客戶下的訂單,如此反覆,估計表裡的資料也差不多沒了吧。。。。