您好,登錄后才能下訂單哦!
今天我們介紹的是jpa刪除和事務(wù)的一些坑,接下來看看具體內(nèi)容。
業(yè)務(wù)場景(這是一個在線考試系統(tǒng))和代碼:根據(jù)問題的id刪除答案
repository層:
int deleteByQuestionId(Integer questionId);
service 層:
public void deleteChoiceAnswerByQuestionId(Integer questionId) { choiceAnswerRepository.deleteByQuestionId(questionId);
測試層:
@Test public void testDeleteByQuestionId() { choiceAnswerService.deleteChoiceAnswerByQuestionId(5); System.out.println("hehehhe"); System.out.println("hehehhe"); System.out.println("hehehhe"); System.out.println("hehehhe"); System.out.println("hehehhe"); System.out.println("hehehhe"); System.out.println("hehehhe"); }
問題1:如果各層都不加事務(wù)管理的話
@Transactional
會報這個錯誤
org.springframework.dao.InvalidDataAccessApiUsageException: No EntityManager with actual transaction available for current thread - cannot reliably process ‘remove' call; nested exception is javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process ‘remove' call
當(dāng)我們除了query外的modiy和delete外如果沒有各層的方法中進行事務(wù)管理的話也就是沒加@Transactional話會報錯
問題2:只在test層加@Transactional
沒有錯誤但是數(shù)據(jù)并沒有被刪除,在用IDEA的調(diào)試是,在執(zhí)行這個測試方法的過程時還可以在choiceanswer表中進行操作并沒有加鎖事務(wù)并沒有起作用
問題3:只在 Repository層加@Transactional
public void deleteChoiceAnswerByQuestionId(Integer questionId) { choiceAnswerRepository.deleteByQuestionId(questionId); System.out.println(“hehehhe”); System.out.println("hehehhe"); // questionRepository.delete(5); System.out.println(“hehehhe”); System.out.println("hehehhe"); System.out.println("hehehhe"); System.out.println("hehehhe"); System.out.println("hehehhe"); }
這時當(dāng)執(zhí)行完
choiceAnswerRepository.deleteByQuestionId(questionId);
數(shù)據(jù)里面被修改
問題4:只在 service層加@Transactional
當(dāng)只有執(zhí)行完service內(nèi)的對應(yīng)方法時數(shù)據(jù)才會被刪除
問題5:在service 層和Repository都加上@transactional
當(dāng)只有執(zhí)行完service內(nèi)的對應(yīng)方法時數(shù)據(jù)才會被刪除
問題6:只要在test(或者是除了service層和Repository層)加上@Transactional,不管service層和Repository層加不加@Transactional數(shù)據(jù)都不會被刪除
問題7:
@Modifying @Query(“delete from ChoiceAnswer c where c.question.id=?1 “) @Transactional int deleteByQuestionId(Integer questionId);
與
@Transactional int deleteByQuestionId(Integer questionId);
有什么區(qū)別,上面的會直接執(zhí)行delete語句
下面的會先執(zhí)行select 再執(zhí)行delete
總結(jié):
事務(wù)管理只有在service加上事務(wù)管理才起作用,query不需要事務(wù)管理但是delete update但需要事務(wù)管理為了不在Service層不加事務(wù)管理可以再Repository層的delete uodate加上@transactional 但這樣不能真正保持事務(wù)的完整性.
本文關(guān)于Spring boot jpa 刪除數(shù)據(jù)和事務(wù)管理的問題實例詳解的介紹就到這里,希望對大家有所幫助,歡迎大家參閱本站其他專題。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。