Spring5 learning notes (14) - "spring5 declarative transaction management"

Posted by greensweater on Sat, 16 Oct 2021 21:00:21 +0200

1, Transaction operation

1. Transaction concept

2. Build a business environment


1. Create database tables and add records

2. Create a service, build a dao, and complete the object creation and injection relationship
(1) service is injected into dao, JdbcTemplate is injected into dao, and DataSource is injected into JdbcTemplate

@Service
public class UserService {
 //Injection dao
 @Autowired
 private UserDao userDao;
}
@Repository
public class UserDaoImpl implements UserDao {
 @Autowired
 private JdbcTemplate jdbcTemplate;
}

3. Create two methods in dao: the method of more money and the method of less money, and create a method in service (the method of transfer)

@Repository
public class UserDaoImpl implements UserDao {
	 @Autowired
	 private JdbcTemplate jdbcTemplate;
	 
	 //lucy transfers 100 to mary
	 //Less money
	 @Override
	 public void reduceMoney() {
	   String sql = "update t_account set money=money-? where username=?";
	   jdbcTemplate.update(sql,100,"lucy");
	 }
	 //More money
	 @Override
	 public void addMoney() {
	   String sql = "update t_account set money=money+? where username=?";
	   jdbcTemplate.update(sql,100,"mary");
	 } 
}
@Service
public class UserService {
	 //Injection dao
	 @Autowired
	 private UserDao userDao;
	 //Method of transfer
	 public void accountMoney(){
		 //lucy less than 100
		 userDao.reduceMoney();
		 //mary more than 100
		 userDao.addMoney();
 	} 
}

4. If the above code is executed normally, there is no problem, but if an exception occurs during code execution, there is a problem

(manually simulate an exception here)


resolvent:
Exception handling
Ensure that the money will be added after an exception occurs, and the operations with less money will not be executed (there will be no case where only one is executed)

2, Introduction to Spring transaction management

1. Transactions are added to the Service layer (business logic layer) in the three-tier structure of Java EE

2. There are two ways to perform transaction management operations in Spring:

  • Programming transaction management
  • Declarative transaction management (common)

3. Declarative transaction management
(1) Annotation based method (common)
(2) xml based configuration file mode

4. For declarative transaction management in Spring, the underlying layer uses AOP principle

5. Spring Transaction Management API
(1) An interface is provided to represent the transaction manager. This interface provides different implementation classes for different frameworks

3, Declarative transaction management (annotation based)

1. Configure the transaction manager in the spring configuration file

<!--Create transaction manager--> 
<bean id="transactionManager" 
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  
   <!--Injection data source-->
   <property name="dataSource" ref="dataSource"></property>
   
</bean>

2. In the spring configuration file, open the transaction annotation

<!--1.stay spring Profile import namespace tx-->
<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"> 

<!--2.Open transaction annotation--> 
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

3. Add a transaction annotation (@ Transactional) on the service class (or on the method in the service class)

(1) @ Transactional, this annotation can be added to classes or methods
(2) If you add this annotation to the class, all the methods in the class will add transactions
(3) If you add this annotation to the method, add transactions for the method

4, Declarative transaction management (parameter configuration)

1. Add the annotation @ Transactional on the service class, in which transaction related parameters can be configured
Mainly learn about the parameters in the red box:

Propagation: transaction propagation behavior

(1) Multiple transaction methods are called directly. How are transactions managed in this process

(2) The value of the propagation property

(3) Use: the default value of this property is required

ioslation: transaction isolation level

(1) Transactions have the characteristic of isolation, and multi transaction operations will not have an impact. There are many problems without considering isolation
(2) There are three reading problems: dirty reading, unrepeatable reading and virtual (illusory) reading

Dirty read: data read from one uncommitted transaction to another uncommitted transaction

Non repeatable read: one uncommitted transaction reads the modified data from another committed transaction

Virtual read: an uncommitted transaction reads and adds data to another committed transaction

Solution: set the transaction isolation level to solve the read problem

Usage: MySQL database defaults to REPEATABLE READ

Timeout: timeout

(1) The transaction needs to be committed within a certain period of time. If it is not committed, it will be rolled back
(2) The default value is - 1, and the set time is calculated in seconds

readOnly: read only

(1) Read: query, write: add, modify, delete
(2) The default value of readOnly is false, which means that you can query, add, modify and delete operations
(3) Set the readOnly value to true. After it is set to true, you can only query

Rollback for: rollback

(1) Set which exceptions occur for transaction rollback

noRollbackFor: do not rollback

(1) Set which exceptions occur without transaction rollback

5, Declarative transaction management (xml based)

1. Configure in the spring configuration file
The steps are as follows:

Step 1: configure the transaction manager
Step 2 configure notifications
Step 3 configure pointcuts and facets

<!--1 Create transaction manager--> <bean id="transactionManager" 
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	 <!--Injection data source-->
	 <property name="dataSource" ref="dataSource"></property>
</bean>

<!--2 Configure notifications--> <tx:advice id="txadvice">
	 <!--Configure transaction parameters-->
	 <tx:attributes>
	 <!--Specify which rule method to add transactions to-->
	 <tx:method name="accountMoney" propagation="REQUIRED"/>
	 <!--<tx:method name="account*"/>-->
	 </tx:attributes>
</tx:advice>

<!--3 Configure pointcuts and facets--> <aop:config>
	 <!--Configure pointcuts-->
	 <aop:pointcut id="pt" expression="execution(* 
	com.atguigu.spring5.service.UserService.*(..))"/>
	 <!--Configure section-->
	 <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config>

6, Declarative transaction management (full annotation)

It is usually simplified directly with Springboot, which can be learned later.

1. Create a configuration class and use the configuration class instead of the xml configuration file

@Configuration //Configuration class
@ComponentScan(basePackages = "com.atguigu") //Component scan
@EnableTransactionManagement //Open transaction
public class TxConfig {

	 //Create database connection pool and use Bean annotation!!!
	 @Bean
	 public DruidDataSource getDruidDataSource() {
	 DruidDataSource dataSource = new DruidDataSource();
	 dataSource.setDriverClassName("com.mysql.jdbc.Driver");
	 dataSource.setUrl("jdbc:mysql:///user_db");
	 dataSource.setUsername("root");
	 dataSource.setPassword("root");
	 return dataSource;
	 }
	 
	 //Create a JdbcTemplate object (parameter transfer required)
/*
put questions to:
  Why is the parameter type of the following method DateSource instead of the DruidDataSource above?
Answer:
  DateSource Built in API for java,
  Ali's Druid datasource implements this interface
*/
	 @Bean
	 public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
	 //Go to the ioc container and find the dataSource by type
	 JdbcTemplate jdbcTemplate = new JdbcTemplate();
	 //Inject dataSource
	 jdbcTemplate.setDataSource(dataSource);
	 return jdbcTemplate;
	 }
	 
	 //Create transaction manager (parameter transfer required)
	 @Bean
	 public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource) {
	 
	 DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
	
	 transactionManager.setDataSource(dataSource);
	 return transactionManager;
 	} 
}

Topics: Java Database Spring