JPA入門02 關聯關係

2021-08-22 12:59:40 字數 3457 閱讀 2694

對映單向一對多的關聯關係(跟前面是類似的)

對映雙向多對一的關聯關係()

對映雙向一對一的關聯關係

對映雙向多對多的關聯關係(由一方放棄主鍵維護)

@table(name = "customer2")

@entity

public

class

customer

@table(name = "order2")

@entity

public

class

order

}

/**

* 儲存多對一時, 建議先儲存 1 的一端, 後儲存多的一端, 這樣不會多出額外的 update 語句.

*/@test

public

void

testmanytoonepersist()

//預設情況下, 使用左外連線的方式來獲取 n 的一端的物件和其關聯的 1 的一端的物件.

//可使用 @manytoone 的 fetch 屬性來修改預設的關聯屬性的載入策略

@test

public

void

testmanytoonefind()

//不能直接刪除 1 的一端, 因為有外來鍵約束.

@test

public

void

testmanytooneremove()

@test

public

void

testmanytooneupdate()

@table(name = "customer2")

@entity

public

class

customer2

@table(name = "order2")

@entity

public

class

order2

//單向 1-n 關聯關係執行儲存時, 一定會多出 update 語句.

//因為 n 的一端在插入時不會同時插入外來鍵列.

@test

public void testonetomanypersist()

//預設對關聯的多的一方使用懶載入的載入策略.

//可以使用 @onetomany 的 fetch 屬性來修改預設的載入策略

@test

public void testonetomanyfind()

//預設情況下, 若刪除 1 的一端, 則會先把關聯的 n 的一端的外來鍵置空, 然後進行刪除.

//可以通過 @onetomany 的 cascade 屬性來修改預設的刪除策略.

@test

public void testonetomanyremove()

@test

public void testupdate()

@table(name="jpa_cutomers")

@entity

public

class

customer )

public setgetorders()

..........

}

@table(name="jpa_orders")

@entity

public

class

order

.......

}

//若是雙向 1-n 的關聯關係, 執行儲存時

//因為雙方都維護外來鍵所以肯定有多餘的sql語句,所以我們需要由一方放棄維護

//雙向1-多關聯關係,建議放棄1的一方維護外來鍵(學生記老師的名字比老師記學生的要方便)

@test

public void testonetomanypersist()

//雙向關聯find()方法預設都是懶載入

//可以使用 @onetomany 的 fetch 屬性來修改預設的載入策略

@test

public void testonetomanyfind()

//預設情況下, 若刪除 1 的一端, 則會先把關聯的 n 的一端的外來鍵置空, 然後進行刪除.

//但是如果要刪除的哪一方放棄了外來鍵維護那麼就刪除不了會報錯(外來鍵約束)

@test

public void testonetomanyremove()

@test

public void testupdate()

@table(name = "managers")

@entity

public

class

manager

}

@table(name = "department")

@entity

public

class

department

}

//雙向 1-1 的關聯關係, 建議先儲存不維護關聯關係的一方, 即沒有外來鍵的一方, 這樣不會多出 update 語句.

@test

public

void

testonetoonepersistence()

//1. 預設情況下, 若獲取不維護關聯關係的一方, 則也會通過左外連線獲取其關聯的物件.

//可以通過 @onetoone 的 fetch 屬性來修改載入策略. 但依然會再傳送 sql 語句來初始化其關聯的物件

//這說明在不維護關聯關係的一方, 不建議修改 fetch 屬性.

@test

public

void

testonetoonefind2()

//1.預設情況下, 若獲取維護關聯關係的一方, 則會通過左外連線獲取其關聯的物件.

//但可以通過 @onttoone 的 fetch 屬性來修改載入策略.

@test

public

void

testonetoonefind()

}

@table(name = "items")

@entity

public

class

item

//多對所的儲存

@test

public void testmanytomanypersist()

//對於關聯的集合物件, 預設使用懶載入的策略.

//使用維護關聯關係的一方獲取, 還是使用不維護關聯關係的一方獲取, sql 語句相同.

@test

public void testmanytomanyfind()

JPA 4 對映關聯關係

以customer和order為例,多個order可以同屬於乙個使用者。table name jpa orders entity public class order public class jpatestsinglemanytoone 單向多對一關聯關係之查詢 1 預設情況下使用左外連線的方式來...

JPA實體關聯關係對映之概述

一 簡介 首先來說關聯關係是物件導向分析,物件導向設計最重要的部分,jpa是完全可以通過對映來簡化資料持久化到資料,和 hibernate 一樣,jpa 的關聯關係也分為兩種,一種是單向關聯,一種是雙向關聯 單向關聯 只需要單向訪問關聯端,比如說 我們只能通過某一學期訪問這學期的課程,而不能通過課程...

JPA 物件關係對映之關聯關係對映策略

關聯關係對映 關聯關係對映,是對映關係中比較複雜的一種對映關係,總的說來有一對 一 一對多和多對多幾種關係。細分起來他們又有單向和雙向之分。王 漢敏,軟體工程師,ibm 2013 年 6 月 17 日 開始您的試用 關聯關係對映,是對映關係中比較複雜的一種對映關係,總的說來有一對 一 一對多和多對多...