Re: [J2EE] JPA JTA

看板java作者 (study)時間10年前 (2015/08/06 08:56), 10年前編輯推噓1(100)
留言1則, 1人參與, 最新討論串4/4 (看更多)
回一下save與update的問題 首先,我必須說JPA裡面沒有定義這兩個method JPA只有persist與merge (底層實作可以是Hibernate的save與update) - persist(Object entity) Make an instance managed and persistent. - merge(T entity) Merge the state of the given entity into the current persistence context. 前面luoqr已經有提到:「entity處於managed狀態 只要有異動就會反應到db」 這點可以在spec 3.2.4找到。然後搭配JTA EM, 會讓人覺得只是改entity連commit也沒有, 異動就通通進資料庫的錯覺。 順便補充JPA entity的life cycle 1. A new entity instance has no persistent identity, and is not yet associated with a persistence context. 2. A managed entity instance is an instance with a persistent identity that is currently associated with a persistence context. 3. A detached entity instance is an instance with a persistent identity that is not (or no longer) associated with a persistence context. 4. A removed entity instance is an instance with a persistent identity, associated with a persis- tence context, that will be removed from the database upon transaction commit. 結論: 1. persist的使用時機, 當你新增了一個物件(new entity instance), 要把他變成managed entity並存入db時必須使用 2. 當entity狀態變成detached時, 可以透過merge把它變成managed entity. 如果對detached entity用persist, 可能會炸EntityExistsException的例外 更細節的定義與行為可以在spec的下面章節找到 persist: 3.2.2 merge: 3.2.7.1 ※ 引述《phstudy (study)》之銘言: : 剛剛重新看了Spec, 發現我的回文也不太準確... : spec在這裡: https://jcp.org/en/jsr/detail?id=338 : 準確來說是這樣 : EM的部分 : 1. Container Managed(CM) EM必須是JTA EM : 2. Application Managed(AM) EM可以是JTA EM或resource-local EM : Container的部分 : 1. JEE Container支援JTA EM與resource-local EM, 可以在JEE Container中使用CM與AM : 2. 非JEE Container支援JTA EM與resource-local EM, 但只能使用AM : 所以這種method結束後會自動commit的行為是JTA EM造成的 XD : ※ 引述《cyclone350 (老子我最神)》之銘言: : : 我在寫某個專案也很奇怪 : : 只要 entity 有異動到,就算不做 save or update 等方法 : : transaction 結束後會把全部的異動 commit 到 DB 裡面... : : 還有一個就是 : : 若 entity constraint 設定若跟 DB 不符, : : save 當下不會出錯,transaction 結束後才會出錯 : : 但是包在 transaction 外層的 code block 並不會接到 exception... : : 像這樣 : : try { : : test1(); : : log.info("完成"); : : } catch(Exception e) { : : log.error("出現錯誤") : : } : : 就算 test1 出錯 (transaction 掛 test1),仍會 log 出 "完成" : : 這兩個 case 我不能理解阿,有人能解釋嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.195.55.170 ※ 文章網址: https://www.ptt.cc/bbs/java/M.1438822587.A.83F.html ※ 編輯: phstudy (123.195.55.170), 08/06/2015 09:16:26

08/08 09:46, , 1F
哈 我沒說清楚,意思就是指交易正常commit狀況下 XD
08/08 09:46, 1F
文章代碼(AID): #1Lmh2xW_ (java)
討論串 (同標題文章)
本文引述了以下文章的的內容:
3
7
完整討論串 (本文為第 4 之 4 篇):
1
1
3
7
5
17
1
5
10年前, 08/03
文章代碼(AID): #1Lmh2xW_ (java)