Udemy Course Spring JPA 19

Transaction,Entity Manager,and Persistence context

ZONGRU Li
5 min readMay 3, 2019

在StudentRepository中建立一個Method並註解要說明之概念

如上我們將在Method內執行四個動作

在此情況中我們希望這四個動作合為一次交易(transaction)

先確認我們data.sql內容為

在Transaction運行過程中,還要引入一個概念-Persistence Context

實際寫相對應的code進去

在沒有引用@Transactional來讓spring管控交易的情況下

一個Operation即代表一次交易

我們將同樣的code擺進StudentRepositoryTest裡

並指針對這個Method執行測試

很明顯的我們未針對此Method標上@Transactional來處理交易

所以得到正常的console結果,但是...

測試NG-no Session

同樣上一節原因em.find(Student.class,20001L);執行完交易即結束

沒有交易可供student.getPassport();執行

接著我們讓Spring來管理交易(讓整個Method內都視為一次交易)

就會測試成功

過程中em.find(Student.class,20001L);的"動作"會紀錄在-Persistence Context

接著student.getPassport();再次紀錄進同一個-Persistence Context

以下同理

所以code新增註解改成

最後一行的Persistence Context內紀錄的內容為

(student++,passport++)在該Method結束後

一次性的將紀錄的動作交易出去!!!

把同樣的code放回原本的StudentRepository內

注意!StudentRepository開頭已經有標註@Transactional

並改寫StudentRepositoryTest,將

改成

連@Transactional都不需要了,因為StudentRepository已有定義@Transactional

同樣執行測試得:

測試正常
依定義的Operation執行動作

重要概念:

以測試的例子當有@Transactional在Method上讓Spring管理該Method的交易

一個Method的結束也代表"一次交易的結束"

而交易結果可能是成功也可能是失敗

並且交易的開始即表示一個Persistence context的建立

而與Method結束的同時,交易也結束且代表Persistence context的結束

而Persistence context管理並紀錄entity及其變化

(如上例就是Persistence context包含student & passport)

Persistence context在結束的同時將一切entity變化轉進DB

對應JPA其實EntityManager就是Persistence Context的界面

而同樣是ORM的Hibernate使用的是Session & SessionFactory

但在JPA裡Session & SessionFactory已不再重要

相關專案置於"SpringJPA深入(交易&PersistenceContet)_0503"

--

--

ZONGRU Li
ZONGRU Li

Written by ZONGRU Li

2022/11/17 開源部分個人筆記給LINE "Java程式語言討論區"社群,希望能對社群的技術學習做一點點貢獻.(掩面....記得退訂閱!

No responses yet