Spring transaction operations
I. Transaction (Concept)
1. What are transactions
- A transaction is the most basic unit of a database, a logical set of operations that either all succeed or, if one fails, all fail
- Typical scenario:
- Lucy transferred 100 yuan to Mary
- Lucy is 100 yuan less and Mary is 100 yuan more
2. Four properties of transactions (ACID)
- Atomicity
- Consistency
- Isolation
- “Durability”
Second, transaction operation
1. Introduction to Spring Transaction Management
-
Transactions are added to the Service layer (business logic layer) in the JavaEE three-tier structure.
-
Transaction management operations in Spring
- Programmatic transaction management: Writing code in code to manually open transactions
- Declarative transaction management: Configure and enable transactions faceted
-
Declarative transaction management
- Annotation-based approach (use)
- Based on XML configuration files
-
Declarative transaction management in Spring, using AOP principles at the bottom
-
Spring transaction management API
-
Provides an interface that represents the transaction manager and provides different implementation classes for different frameworks
-
2. Annotation declarative transaction management
-
Configure the transaction manager in the Spring configuration file
<! Create transaction manager --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <! Inject data source --> <property name="dataSource" ref="dataSource"></property> </bean> Copy the code
-
In the Spring configuration file, turn on transaction annotations
-
Introduce the namespace TX in the Spring configuration file
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> Copy the code
-
Open transaction annotations
<! -- Enable transaction annotations --> <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven> Copy the code
-
-
Add transaction annotations above the Service class (or above the methods in the Service class)
-
Transaction. This annotation can be added to a class or method
-
If you add this annotation to a class, all the methods in the class add transactions
-
If you add this annotation to the method, you simply add a transaction to the method
@Service @Transaction public class UserService {... }Copy the code
-
3. Set parameters for declarative transaction management
-
Add the @Transaction annotation to the Service class declaration, which allows you to configure Transaction parameters
-
Propagation: Transaction propagation behavior
-
** Transaction propagation behavior: ** How are transactions managed when multiple transaction methods are invoked directly
-
Transaction method: The operation to change the books of a database table
-
The Spring framework has seven transactional propagation behaviors, focusing on REQUIRED and REQUIRES_NEW
-
REQUIRED: If the add method itself has a transaction, the update method uses the transaction in the current add method after calling the update method. If the Add method does not have a transaction itself, a new transaction is created after the update method is called
-
REQUIRES_NEW: The update method is called with the add method. The update method creates a new transaction whether the Add method has a transaction or not. If the add method’s transaction is running, the update method’s transaction is suspended first
-
-
-
Isolation: transaction isolation level
- Transactions have a property called isolation, where operations between multiple transactions have no impact. Many problems can arise if isolation is not considered
- There are three problems: dirty reads, unrepeatable reads, and phantom reads
- Dirty read: Data read from one transaction to another uncommitted transaction
- ** Non-repeatable read: ** Inconsistent results from two queries in one transaction (for update operations)
-
** Phantom reading: ** Inconsistent results from two queries in one transaction (for INSERT operations)
-
How to solve these problems?
-
Resolve read problems by setting transaction isolation level
-
SQL standard transaction isolation levels include read uncommitted, read Committed, repeatable read (default in MySQL), and serialization
- Read uncommitted: Changes made by a transaction can be seen by other transactions before it is committed
- Read Committed: After a transaction commits, its changes can’t be seen by other transactions
- Repeatable read: The data seen during the execution of a transaction is always the same as the data seen when the transaction is started
- Serialization: For the same row, write will add write lock, read will add read lock. When a read-write lock conflict occurs, the last accessed transaction must wait for the previous transaction to complete before execution can continue
-
-
Timeout: indicates the timeout period
- Transactions need to commit within a certain amount of time, and if they don’t, they are rolled back
- The default value is -1, and the setting time is measured in seconds
-
ReadOnly: Indicates whether it is read-only
- Read: query operation Write: Add, modify, and delete
- ReadOnly The default value is false, indicating that it can be read or written
- ReadOnly is set to true. Only read operations, that is, queries, can be performed
-
RollbaclFor: rolled back
- Sets which exceptions occur for transaction rollback
-
NoRollbackFor: does not roll back
- Sets which exceptions do not roll back transactions
XML declarative transaction management
-
Do this in the Spring configuration file
-
Configure the transaction manager
<! Create transaction manager --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> Copy the code
-
Configure notification
<! -- 2. Configure notifications --> <tx:advice id="txadvice"> <! -- Set transaction parameters --> <tx:attributes> <tx:method name="accountMoney" propagation="REQUIRED"/> </tx:attributes> </tx:advice> Copy the code
-
Configure pointcuts and facets
<! -- 3. Configure pointcuts and facets --> <aop:config> <! Configure pointcuts --> <aop:pointcut id="pt" expression="execution(* com.atguigu.spring5.service.UserService.*(..) )"/> <! -- Configuration section --> <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/> </aop:config> Copy the code
-
5. Fully annotated declarative transaction management
-
Creating a Configuration Class
@Configuration / / configuration class @ComponentScan(basePackages = "com.atguigu") // Enable component scanning @EnableTransactionManagement // Start the transaction public class TxConfig { @Bean public DruidDataSource getDruidDataSource(a) { DruidDataSource druidDataSource = new DruidDataSource(); druidDataSource.setDriverClassName("com.mysql.jdbc.Driver"); druidDataSource.setUrl("jdbc:mysql://localhost:3306/spring"); druidDataSource.setUsername("root"); druidDataSource.setPassword("root"); return druidDataSource; } // Create JdbcTemplate object @Bean(value = "jdbcTemplate") public JdbcTemplate getJdbcTemplate(DataSource dataSource) { JdbcTemplate jdbcTemplate = new JdbcTemplate(); jdbcTemplate.setDataSource(dataSource); return jdbcTemplate; } // Create transaction manager @Bean public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource) { DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); dataSourceTransactionManager.setDataSource(dataSource); returndataSourceTransactionManager; }}Copy the code