Spring 5 self study notes_ Real004 (transaction operation)
1, Basic concepts of transaction
1. What is a transaction:
(1) Transaction is the most basic unit of database operation. A group of logical operations either succeed or fail, and all will fail.
A transaction is a set of operations. It is an inseparable work unit. All operations as a whole submit or latch operation requests to the system, that is, these operations either succeed at the same time or fail at the same time.
(2) Typical scenario: bank transfer
If Party A transfers 100 yuan to Party B, there will be 100 yuan less in Party A's account and 100 yuan more in Party B's account. If Party A loses 100 yuan when the system is running again, there will be an accident. For example, if there is a power failure and Party B does not have 100 yuan more, there will be a problem. Therefore, it must be ensured that after Party A loses 100 yuan, Party B must have 100 yuan more, or it will remain the same. If it wants to change, it must change both.
(3) Characteristics of transactions:
1) Atomicity: a transaction is an indivisible smallest unit of operation, either all successful or all failed;
2) Consistency: when the transaction is completed, all data must be consistent;
3) Isolation: the isolation mechanism provided by the database system ensures that transactions run in an independent environment not affected by external concurrent operations;
4) Persistence: once a transaction is committed or rolled back, its changes to the data in the database are permanent.
(4) Functions used:
@@autocommit indicates whether to submit automatically. Generally, the default is 1. Auto submit, and 0 means to turn off auto submit
The commit function is a function that commits a transaction
start transaction means to start a transaction
Rollback means that the transaction will be rolled back in case of an exception
(5) Problems caused by concurrent transactions:
1) Dirty read: one transaction reads data that has not been committed by another transaction;
2) Non repeatable reading: a transaction reads the same record successively, but the data read twice is different;
3) Phantom reading: when a transaction queries data according to conditions, there is no corresponding data row, but when inserting data again, it is found that this row of data already exists, as if there was a phantom.
(6) Isolation level of transaction:
1) Read uncommitted: it is prone to dirty reading, non repeatable reading and unreal reading, but the efficiency is the highest
2) Read committed (Orcale default): it solves the problem of dirty reading, but there are two problems: non repeatable reading and unreal reading
3) Repeatable read (MySQL default): solves the two problems of dirty reading and non repeatable reading, which will lead to unreal reading
4) Serializable: all three problems are solved, but the efficiency is the lowest
To view the isolation level of a transaction:
SELECT @@TRANSACTION_ISOLATION;
Set transaction isolation level:
SET [SESSION|GLOBAL] TRANSACTION ISOLATION LEVEL {READ UNCOMMITTED|READ COMMITTED|REPEATABLE READ|SERIALIZABLE}
2, Environment construction of transaction operation
First, set up the basic code of the bank transfer scenario: lucy transfers 1000 yuan to mary
xml configuration file:
<?xml version="1.0" encoding="UTF-8"?> <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" 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"> <!-- Open component scanning and inject attributes with annotations --> <context:component-scan base-package="com.SSMStudy.Spring5.SpringTransactionStudy"></context:component-scan> <!-- Configure connection pool directly --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://127.0.0.1:3306/userdb"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> </bean> <!-- JdbcTemplate Object creation --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <!-- injection dataSource --> <property name="dataSource" ref="dataSource"></property> </bean> </beans>
java program:
/** * Dao Interface */ import org.springframework.stereotype.Repository; @Repository public interface StudentDao { void addMoney(); void reduceMoney(); } /** * dao Implementation class */ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository public class StudentDaoImp implements StudentDao{ @Autowired private JdbcTemplate jdbcTemplate; @Override public void addMoney() { String sql = "update account_list set user_money = user_money - ? where user_name = ?"; jdbcTemplate.update(sql, 1000, "lucy"); } @Override public void reduceMoney() { String sql = "update account_list set user_money = user_money + ? where user_name = ?"; jdbcTemplate.update(sql, 1000, "mary"); } } /** * Service Implementation class */ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class StudentService { @Autowired private StudentDao studentDao; public void accountMoney(){ studentDao.addMoney(); studentDao.reduceMoney(); } } /** * Test class */ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestService { @Test public void test01(){ ApplicationContext context = new ClassPathXmlApplicationContext("bean7.xml"); StudentService studentService = context.getBean("studentService", StudentService.class); studentService.accountMoney(); } }
Test results:
Before running the program:
After the program runs:
3, Transaction operation: (Spring transaction management)
1. Generally, transactions are added to the Service layer (business logic layer) in the three-tier structure of Java EE
2. Transaction management in Spring:
(1) There are two ways: programmatic transaction management and declarative transaction management (configuration file)
Declarative transaction management is generally used
3. Declarative transaction management:
(1) Annotation based approach (often used)
(2) xml based configuration file mode
4. For declarative transaction management in Spring, the underlying layer uses the principle of AOP (aspect oriented programming)
4, Spring transaction operation (annotation based)
1. Configure the transaction manager object in the Spring configuration file
<!-- Create transaction manager object --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- Such as data source --> <property name="dataSource" ref="dataSource"></property> </bean>
2. In the Spring configuration file, open the transaction annotation
<?xml version="1.0" encoding="UTF-8"?> <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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
3. Notes for opening transactions:
<!-- Open transaction annotation --> <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
4. On the service class (get the method in the service class and add the transaction annotation)
@Transactional
This annotation can be added to the class or annotation
Add to the class: add transaction annotations to all methods in the class,
If only one method is annotated, it means that the method has added transaction annotation
5, Spring transaction operation (based on annotation method: parameter setting of annotation)
Parameters can be added in the @ Transactional annotation:
Generally, the following parameters need to be configured
(1) Propagation: transaction propagation behavior
Multiple transaction methods are called directly. How are transactions managed in this process (that is, now, for example, if there are two transactions, one transaction calls the other, how to call the other? In addition, what if one transaction calls another method without transaction annotation)
(2) ioslation: transaction isolation level
In order to solve the problems caused by dirty reading, unrepeatable reading and unreal reading
(3) Timeout: timeout
1) The transaction needs to be committed within a certain period of time. If it has not been committed beyond the time set by the timeout parameter, roll back;
2) The default value is - 1, and the setting time is in seconds
(4) readOnly: read only
1) Read: query operation; Write: add modify delete operation
2) The default value of readOnly is false, which means you can query, add, modify or delete
3) If readOnly is set to true and truehi is set, you can only query
(5) Rollback for: rollback
1) Set the exceptions to roll back the transaction
(6) noRollbackFor: no rollback
1) Set which exceptions occur and do not roll back