Detailed explanation of spring boot JPA data deletion and transaction management
Today we'll introduce some pitfalls of JPA deletion and transaction. Let's take a look at the details.
Business scenario (this is an online examination system) and code: delete the answer according to the ID of the question
Repository layer:
Service layer:
Test layer:
Question 1: if all layers do not add transaction management, @ transactional
This error will be reported
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
Except for modiy and delete in query, if we do not have transaction management in the methods of each layer, that is, if @ transactional is not added, an error will be reported
Problem 2: there is no error in adding @ transactional only to the test layer, but the data has not been deleted. During debugging with idea, you can still operate in the choiceanswer table during the execution of this test method, and the locking transaction does not work
Question 3: only add @ transactional in the repository layer
When the execution is finished
The data is modified
Question 4: only add @ transactional in the service layer
The data will be deleted only after the corresponding method in the service is executed
Question 5: add @ transactional to both the service layer and the repository
The data will be deleted only after the corresponding method in the service is executed
Question 6: as long as @ transactional is added to the test layer (or in addition to the service layer and repository layer), the data will not be deleted regardless of whether @ transactional is added to the service layer and repository layer
Question 7:
And
What's the difference? The above will directly execute the delete statement
The following will execute select first and then delete
Summary:
Transaction management works only when service is added with transaction management. Query does not need transaction management, but delete update needs transaction management. In order not to add transaction management in service layer, you can add @ transactional to delete uodate in repository layer, but this can not really maintain the integrity of transactions
This article on spring boot JPA delete data and transaction management issues, detailed examples of the introduction here, I hope to help you, welcome to refer to other topics on this site.