Udemy Course Spring JPA 23
簡化上一節的Method
原本在CourseRepository.java內的addReviewsForCourse Method寫法如下
額外再新增一個帶參數的addReviewsForCourse Method
將原本不帶參數的addReviewsForCourse改名為 →addHardcodeReviewsForCourse
改寫DemoApplication內的呼叫:
執行DemoApplication得到一樣結果
接著來觀察OneToMany的fetch模式
在CourseRepositoryTest中加入新的測試retrieveReviewsForCourse Method
指針對該Method做Unit Test得到
因為取得course已經用掉transaction,接著就沒有transaction再去getReviews
所以該Method需要加上transaction annotation
並且在31行加上中斷點,準備用debug mode來觀察fetch mode
在結束了第31行取得course物件會見到
console中只有Select 取出我們要的course資料
尚未連對應的review(或reviews)也拿出
所以我們可以認定跟OneToOne不同的是
OntToMany的fetch default mode is “LAZY”
接著繼續讓dubug mode往下跑
在完成了course.getReviews()後可以見到
console中有出現select review的資料(也就是要取用時才取用(LAZY mode))
一般來說LAZY效率也比較好一點,所以我們也不特地改成EAGER mode如下
而是改加上註解
在CourseRepositoryTest反向從Review中取得course資料
加入新的Method
當然還另外需要Autowired EntityMange
用deBug mode觀察
在完成Review review = em.find(Review.class,50001L);後會見到SELECT
而且是連同review 與 course都取得的SELECT
再按F6
至此得到一個相反的結論:
@ManyToOne Default is Eager fetch
相關專案置於"SpringJPA深入(ManyToOne)0513"