What is a transaction
A transaction can be thought of as an uninterruptible, continuous task that receives rewards along the way (writing to the database), and if there is a problem (throwing exceptions), the task fails and all rewards disappear (rollback).
In Spring Boot you can easily use the @Transactional annotation to complete transactions
How to use
Transactional can be applied to methods and classes, simply by adding it in the right places where transactions are needed
You can refer to this article for more detailed configurations
Add the following two points:
Specify exceptions for transactions
When designing to a custom exception rollback, we can use:
@Transactional(rollbackFor = {MyException.class})
public class MyService {business code... }Copy the code
MyException is my custom exception, and the transaction will only trigger a rollback if it catches such an exception
Read-only mode
@Transactional(readOnly=true)
Hibernate provides some Session optimization for transactions when they are set to read-only
Various possible data read errors
Today I want to write about all kinds of reading
The types of data read errors are: dirty read/unrepeatable read/phantom read
You can prevent error situations by setting @Transactional’s Isolation, or isolation level
Dirty read
- Operator A: change the sex of user 1 in t_user to -99, but the operation failed because of network timeout
- User B: select * from t_user where id = 1 and sex = -99
For operator B, the “dirty” data is read because -99 is an unfinished transaction and the gender of the user with the actual ID 1 has not changed
TransactionDefinition. ISOLATION_READ_COMMITTED can solve this problem
irrepeatability
- Operator A: Change the sex of user 1 in t_user to -99. The operation succeeds
- Operator B: Check the gender of user 1 twice. The first time is 1 and the second time is 99
In this case, an unrepeatable read occurs for user B. That is, the data is read twice in the same operation and the data results are inconsistent
RansactionDefinition. ISOLATION_REPEATABLE_READ can prevent non-repeatable degrees, at the same time also can prevent dirty reads well
Phantom read
- Operator A: Modify all data in t_user and set their sex to -99
- Operator B: Insert a new user named “World beater” into t_user
At this point, operator A seemed to have an illusion. The gender of everyone was set to -99, but the gender of “Invincible” was still 3, as if he had escaped the limitation of the system
TransactionDefinition. ISOLATION_SERIALIZABLE can prevent phantom read, at the same time prevent not repeatable read and dirty, however, this setting will seriously affect the performance
conclusion
Operator B is miserable. It’s always him