Author of Spring affairs: Wow, big mouth is so handsome (I love big mouth)
I love big mouth, so handsome(I love big mouth net) I love big mouth, so handsome(I love big mouth net)
1. Transaction characteristics (ACID)
1. Atomicity
2. Consistency
3. Isolation
4. Durability
1. Atomicity
For example, Zhang San gives Li Si 5 yuan, and Li Si gives Zhao Si 3 yuan. Atomicity means that these steps are either executed or not executed. If there is a problem with a step, it will be rolled back and revoked.
2. Consistency
Data assurance is business correct
3. Isolation
The execution of the two transactions shall not affect or interfere with each other,
4. Durability
Once the transaction is committed successfully, the data will be persisted in the database, that is, the data will be saved.
Spring transaction management mechanism
Spring transactions are encapsulated and extended on the basis of database transactions. The main features are as follows
1. Support the isolation level of original database transactions and add the concept of transaction propagation
2. Provide the function of merging or isolating National Anthem affairs
3. Provide declarative transactions to separate business code from transactions and make transactions easier to use (AOP)
Spring provides transaction related interfaces
Spring transaction management high-level abstraction mainly includes three interfaces, and spring transactions are mainly completed through them
TransactionDefinition
Transaction definition: transaction definition information (isolation, propagation, read-only, timeout)
PlatformTransactionManager
The transaction manager is mainly used to manage platform related transactions
TransactionStatus
Gets the running state of the transaction
1.1 introduction to platform transaction manager
Reference documents: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/transaction/PlatformTransactionManager.html
The commit method commits the transaction
getTransaction obtains the transaction state. The TransactionDefinition in the transaction state is the definition of the transaction. The state is obtained through the transaction definition information
Rollback rollback
Spring provides different interface implementations of PlaformTransactionManaeg for different persistence layer frameworks
affair | explain |
---|---|
org.springframework.jdbc.datasource.DataSourceTransactionManager | Used when using Spring JDBC or iBatis to persist data |
org.springframework.orm.hibernate5.HibernateTransactionManager | Used when using hibernate 5.0 to persist data |
org.springframework.orm.jpa.JpaTransactionManager | Used when using JPA for persistence |
org.springframework.jdo.JdoTransactionManager | Used when the persistence mechanism is Jdo |
org.springframework.trasanction.jta.JtaTransactionManager | A JTA implementation is used to manage transactions, which must be used when a transaction spans multiple resources |
The DatasourceTransactionManager uses connection for transaction management for transaction control of JdbcTemplate and Mybatis
Start the transaction connection.setAutoCommit(false). Only when this is false can the transaction connection.commit() and rollback connection.rollback();
1.2 transaction definition information
Reference documents: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/transaction/TransactionDefinition.html
**getIsolationLevel * * get isolation level
getName gets the nickname of the current transaction
getPropagationBehavior get transaction propagation behavior
getTimeout gets the timeout. The default value is - 1. - 1 means no timeout
isReadOnly determines whether the transaction is read-only
Common transaction isolation levels
Isolation Leavel | meaning |
---|---|
DEFAULT | Use the default isolation type of back-end database (option in Spring) |
READ_UNCOMMITED | Allows you to read unchanged data that has not been submitted. It may cause dirty reading, unreal reading and non repeatable reading |
READ_COMMITTED | Allow reading after concurrent transactions have been committed. It can prevent dirty reading, but phantom reading and non repeated reading can still occur |
REPEATABLE_READ | Multiple reads of the same bullet are consistent unless the data is changed by the transaction itself. It can prevent dirty and unrepeatable reading, but phantom reading can still occur |
SERIALIZABLE | 100% obey the isolation level of ACID to ensure that dirty reading, phantom reading and non repeatable reading do not occur. This is the slowest of all isolation levels. It is typically done by completely locking the data table designed in the transaction sheet. |
DEFAULT is to select the DEFAULT isolation level of your database based on the database you select
For example, the default isolation level of Mysql is REPEATABLE_READ
Oracle default isolation level READ_COMMITTED
propagation behavior
7 transaction propagation levels
Transaction propagation behavior type | explain |
---|---|
PROPAGATION_REQUIRED | Support the current transaction. If it does not exist, create one |
PROPAGATION_SUPPORTS | The current transaction is supported. If it does not exist, the transaction will not be used |
PROPAGATION_MANDATORY | The current transaction is supported. If it does not exist, an exception is thrown |
PROPAGATION_REQUIRES_NEW | If a transaction exists, suspend the current transaction and create a new transaction |
PROPAGATION_NOT_SUPPORTED | Run in a non transactional manner. If a transaction exists, suspend the current transaction |
PROPAGATION_NEVER | Run in a non transaction method. Throw an exception if a transaction exists |
PROPAGATION_NESTED | If the current transaction exists, the nested transaction is executed only for the DataSourceTransactionManager |
It is mainly divided into three categories:
PROPAGATION_REQUIRED(default) ,PROPAGATION_SUPPORTS ,PROPAGATION_MANDATORY
The current transaction is supported. A calls B. If a transaction still exists, A and B are in the same transaction. The default propagation level of the transaction is REQUIRED
PROPAGATION_REQUIRES_NEW,PROPAGATION_NOT_SUPPORTED,PROPAGATION_NEVER
The original transaction will not be supported. For example, A calls B. If A transaction exists, B will not be in the same transaction with A.
Common transaction propagation behavior: Requirements_ NEW
PROPAGATION_NESTED not commonly used
Nested transactions are only valid for DatasourcetransactionManager. The underlying layer uses the SavePoint mechanism of JDBC, allowing savepoints to be set and rolled back in the same transaction
Common transaction propagation behavior: NESTED
REQUIRED NESTED REQUIRES_ Differentiation of new
required only one transaction (default, recommended)
requires_new has two transactions. If the transaction exists, suspend the transaction and restart a new transaction
nested transactions. Transactions can set savepoints, roll back to savepoints, and select commit or rollback
2.Spring transaction management
2.1 programmatic transactions
Programming transaction is to control the transaction through pure code, commit and rollback manually
2.1.1 xml configuration
<!--Transaction manager--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--Template for transaction management--> <bean id="transactionTemplate" class="org.springframework.transaction,support.TransactionTemplate"> <property name="transactionManager" ref="transactionManager"></property> </bean>
2.1.2 annotation configuration
@ComponentScan("com.dazuizui") public class TransactionConfig{ /** * Transaction manager */ @Bean public TransactionTemple transactionTemplate(DataSourceTransactionManager dataSourceTransactionManager){ TransactionTemplate transactionTemplate = new TransactionTemplate(); transactionTemplate.setTransactionManager(transactionTemplate); return transactionTemplate; } @Bean public DataSourceTransactionManager transactionManager(DataSource dataSource){ DataSourceTransactionManager dm = new DataSourceTransactionManager(); dm.setDataSource(dataSource); return dm; } @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource){ JdbcTemplate jdbcTemplate = new JdbcTemplate(); jdbcTemplate.setDtaSource(dataSource); return jdbcTemplate; } @Bean public DtaSource dataSource(){ BasicDataSource ds = new BasicDataSource(); ds.seturl("url"); ds.setDriverClassName("com.mysql.jdbc.Driver") ds.setUsername("username"); ds.setPassowrd("password"); return ds; } }
2.1.3 realization
/** * Using xml configuration */ @Test public void test1(){ ApplicationContext ca = new CLassPathXmlApplicationContext("applicationContext.xml"); UserSerivce userBean = ca.getBean(UserSerivce.class); bean.test1();//Perform database operations } /** * Execute annotation profile mode */ public void test2(){ AnnotationConfigApplicationContext ac= new AnnotationConfigApplicationContext(TransactionConfig.class); UserSerivce userBean = ca.getBean(UserSerivce.class); bean.test1();//Perform database operations }
Write the calling database transaction in the transactiontemplate.execute() method through Lambda expression for transaction management
@Autowired private TransactionTemplate transactiontemplate //Transaction manager public void test1(){ transactiontemplate.execute(status - > { userMapper.zhuanqian(); //Call the database to transfer money from Xiao Zhang to Xiao Ming int x = 10086; if(x==10086) throw new RuntimeException("error"); userDao.income(); //Xiao Ming's income is the money transferred by Xiao Zhang return null; }); }
2.2 declarative transactions
2.2.1 configuration method based on AspectJ xml
Use this statement to delete the configuration in the transaction management template in the configuration file.
That's it
<!--Transaction manager--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean>
Add a transaction definition configuration and AOP configuration
<!--Transaction manager--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <!--Enhanced transaction attribute configuration--> <td:attributes> <!-- isolation: default,Transaction isolation level propagation: Transaction propagation behavior read-onlu: fase,Read only timeout: -1, overtime-1 Is the default no-rollback-for: Those exceptions do not roll back rollback-for: What abnormal transactions occur --> <tx:method name="Method name" isolation="DEFAULT" propagation="REQUIRED"> <!--save All the methods at the beginning are enhanced--> <tx:method name="save*" isolation="DEFAULT" propagation="REQUIRED"> </tx:method> </td:attributes> </tx:advice> <!--aop Configure and define tangent plane and tangent point information--> <aop:config> <!--Define tangent point:The methods of those classes should be strengthened--> <aop:pointct expression="excution(* com.dazuizui.beans.service..*.*(..))" id="mypointct"/> <!--Define section--> <aop:advisor advice-ref="txAdvice" pointcut-ref="mypointcut"></aop:advisor> </aop:config>
Let's talk about the configuration of Spring transactions:
The first method is the XML based configuration method, which needs to configure the transaction manager, and then configure the enhancement of the transaction
Transaction definitions are mainly configured, including transaction isolation level, transaction propagation behavior, read-only, timeout, exceptions that do not roll back, and exceptions that roll back transactions
Then set the aspect and pointcut through aop: config
2.2.2 annotation method declarative transaction
@ComponentScan("com.dazuizui") @EnableTransactionManagement //Open annotation transaction public class TransactionConfig{ @Bean public DataSourceTransactionManager transactionManager(DataSource dataSource){ DataSourceTransactionManager dm = new DataSourceTransactionManager(); dm.setDataSource(dataSource); return dm; } @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource){ JdbcTemplate jdbcTemplate = new JdbcTemplate(); jdbcTemplate.setDtaSource(dataSource); return jdbcTemplate; } @Bean public DtaSource dataSource(){ BasicDataSource ds = new BasicDataSource(); ds.seturl("url"); ds.setDriverClassName("com.mysql.jdbc.Driver") ds.setUsername("username"); ds.setPassowrd("password"); return ds; } }
If you want to use transactions, add * * @ Transactional * * to the Service class, which means that all methods under the current class are subject to transaction management. If you use methods, this method is subject to transaction management.
Let's talk about the configuration of Spring transactions:
Based on annotations, add * * @ Transactional on classes or methods**
3.Spring propagation features
3.1 what are propagation characteristics? What is propagation charecteristics?
When A transaction method is called by another transaction method (method A calls method B), how should this transaction method proceed.
for example:
@Service public class test1{ @Transactional public void function1(){ System.out.println("funcion 1 method"); function2(); } @Transactional public void function2(){ System.out.println("function 2 medhod"); } }
3.2 propagation characteristics of spring
Propagation | Describe |
---|---|
PROPAGATION_REQUIRED | Default transaction type. If not, create a new transaction; If so, join the current transaction. |
PROPAGATION_SUPPORTS | If there is no transaction, the non transaction is executed. If there is a transaction, the current transaction is used |
PROPAGATION_MANDATORY | Throw an exception if there is no transaction, and use the current transaction if there is |
PROPAGATION_REQUIRES_NEW | If no transaction is executed on a non transaction basis, all transactions are suspended |
PROPAGATION_NOT_SUPPORTED | The operation is performed in a non transactional manner. If there is a current transaction, the current transaction is suspended. |
PROPAGATION_NEVER | If there is a transaction, throw an exception. If there is no transaction, execute the non transaction |
PROPAGATION_NESTED | If there is no transaction, create a transaction; If so, nest other transactions in the current transaction type |
3.2.1 explain seven propagation characteristics in detail
Use annotations to set propagation properties, such as
@Transaction(propagation=Propagation.SUPPORTS)
@Transaction(propagation=Propagation.NEVER)
3.2.1.1 PROPAGATION_NEVER
If there is a transaction in function 1 or function 2, an exception is thrown directly
for example
@Service public class test1{ @Transactional public void function1(){ System.out.println("funcion 1 method"); function2(); } @Transactional public void function2(){ System.out.println("function 2 medhod"); } }
This will report an error
@Service public class test1{ public void function1(){ System.out.println("funcion 1 method"); function2(); } public void function2(){ System.out.println("function 2 medhod"); } }
So you won't report an error
3.2.1.2 PROPAGATION_NOT_SUPPORTED
If the called method finds that the method calling it has a transaction, it suspends the transaction (I put you aside and I do my thing),
for example
@Service public class test1{ @Transactional public void function1(){ System.out.println("funcion 1 method"); function2(); } public void function2(){ System.out.println("function 2 medhod"); } }
It can be said that promotion_ NOT_ SUPPORTED and PROPAGATION_ Never wants to die
3.2.1.3 PROPAGATION_SUPPORTED
If you have a business, I will use it to execute it. If you don't have a business, I won't execute it according to it.
It can be said that propagation_not_supported is a dispensable transaction
3.2.1.4 propagation_requires_new
Whether there is a transaction or not, a transaction must be created. If there is a transaction, the original transaction will be suspended. I create a new one
for example
@Service public class test1{ @Transactional public void function1(){ System.out.println("funcion 1 method"); function2(); } @Transactional public void function2(){ System.out.println("function 2 medhod"); } }
Function2 no matter whether there is a transaction in function1 or not, I must create a transaction in function2. When my transaction is finished, I will go to the transaction in function1
You can achieve the effect that the child affects the parent, but the parent does not affect the child
3.2.1.5 propagation_nested
for example
@Service public class test1{ @Transactional public void function1(){ System.out.println("funcion 1 method"); function2(); } @Transactional public void function2(){ System.out.println("function 2 medhod"); } }
If an exception occurs in function2, function1 will also be rolled back
3.2.1.6 propagation_required (default)
If there is no transaction, I will create a transaction. If there is a transaction, I will use your transaction
3.2.1.7 propagation_mandatory
If there is no business, I will report an error. If there is a business, I will use yours
propagation_mandatory and dissemination_ Required and propagation_nested and propagation_requires_new must have a transaction