Spring boot jpa削除データと事務管理の問題例詳細


今日紹介したのはjpa削除と事務の穴です。具体的な内容を見てみます。
ビジネスシーン(これはオンラインテストシステムです)とコード:問題のIDから答えを削除します。
repository層:

int deleteByQuestionId(Integer questionId);
サービス層:

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:各階に事務管理をしないと
@Transation al
このエラーを報告します
org.spring frame ebook.dao.InvalidDataAccess Acception:No EnttityManager with actual trance available for current-cannot reliable process‘remove’call;neted exception is javax.persistence.Transation RequiredException:No EnttyManager with actual transaction available for current thread-cannot reable process‘remove’call
私たちはquery以外のmodiyとdeleteを除いて、各階層の方法で事務管理を行っていないなら、つまり@Transationを追加していないとエラーが発生します。
問題2:test層だけに@Transationを追加する
エラーはありませんが、データは削除されていません。IDEAでのデバッグは、このテスト方法を実行する過程で、chociceanswerで操作できるようになりました。ロックをかけていません。
問題3:Repository層だけに@Transationを追加します。

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");
}
この時点で実行が完了します

choiceAnswerRepository.deleteByQuestionId(questionId);
データが修正されました。
問題4:service層だけに@Transactionを追加する
service内の対応方法を実行した場合のみデータが削除されます。
問題5:service層とRepositoryに@transactionalを追加します。
service内の対応方法を実行した場合のみデータが削除されます。
問題6:test(またはservice層とRepository層を除く)に@Transationを加える限り、service層とRepository層に@Transactionalデータを加えなくても削除されません。
問題7:

@Modifying
@Query(“delete from ChoiceAnswer c where c.question.id=?1 “)
@Transactional
int deleteByQuestionId(Integer questionId);
を選択します

@Transactional
int deleteByQuestionId(Integer questionId);
どのような違いがありますか?上の文は直接delete文を実行します。
以下は先にselectを実行してからdeleteを実行します。
まとめ:
事務管理はserviceに事務管理を加えてこそ機能し、queryは事務管理は不要ですが、delete udateは事務管理が必要です。Service層に事務管理をしないためには、Repository層のdelete uodateに@tractionalを加えても、本当に業務の完全性を維持することができません。
本文はSpring boot jpa削除データと事務管理の問題例について詳しく紹介します。ここに来て、皆さんに助けてほしいです。