Two transactions in Spring

Posted by drayarms on Wed, 09 Mar 2022 08:58:05 +0100

16.Spring transactions

1. Transaction control in spring

Spring's transaction control can be divided into programmatic transaction control and declarative transaction control.

Programming

Developers directly couple the transaction code and business code, which is not needed in actual development.

Declarative

Developers use configuration to realize transaction control, decouple business code and transaction code, and use AOP idea.

2. Programming transaction control related objects

2.1PlatformTransactionManager

PlatformTransactionManager interface is the transaction manager interface of spring, which provides our common methods of operating transactions.

2.2TransactionDefinition

The TransactionDefinition interface provides transaction definition information (transaction isolation level, transaction propagation behavior, etc.)

(1) Transaction isolation level

Setting the isolation level can solve the problems caused by transaction concurrency, such as dirty reading, non repeatable reading and virtual reading (phantom reading).

Note: the database default level is used. If the database is mysql, it is repeatable by default, and oracle is read submitted.

  • ISOLATION_DEFAULT uses the database default level

  • ISOLATION_READ_UNCOMMITTED read uncommitted

  • ISOLATION_READ_COMMITTED read committed (can solve dirty read problem)

  • ISOLATION_REPEATABLE_READ repeatable reading (dirty reading and non repeatable reading can be solved)

  • ISOLATION_SERIALIZABLE serialization

    Can solve:

(2) Transaction propagation behavior

Transaction propagation behavior refers to how to control transactions when a business method is called by another business method.

a key:

  • Read only: it is recommended to set it as read-only when querying
  • Timeout: the default value is - 1. There is no timeout limit. If yes, set in seconds

2.3 TransactionStatus

The TransactionStatus interface provides the specific running status of a transaction.

We can simply understand the relationship between the three: the transaction manager manages transactions by reading transaction definition parameters, and then generates a series of transaction states.

Transaction control in Spring is mainly realized through these three API s

  • Platform transaction manager is responsible for transaction management. It is an interface, and its subclasses are responsible for specific work
  • Transaction definition defines some parameters related to a transaction
  • TransactionStatus represents a real-time status of transaction operation

Understand the relationship between the three: the transaction manager manages transactions by reading transaction definition parameters, and then generates a series of transaction states.

3. Declarative transaction control based on XML [key]

In the Spring configuration file, declarative transaction processing is used instead of code transaction processing. The bottom layer is realized by AOP.

Explicit matters of declarative transaction control:

  • Core business code (target object) (who is the entry point?)
  • Transaction enhancement code (Spring has provided a transaction manager) (who is the notification?)
  • Section configuration (how to configure the section?) (aspect = entry point + notification)

3.1 quick start

Use spring declarative transaction to control the transfer business.

Steps:

  1. Introduce tx namespace
  2. Transaction manager notification configuration
  3. Transaction manager AOP configuration
  4. Test transaction control transfer business code

(1) Introduce tx namespace

<?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
">

(2) Transaction manager notification configuration

  <!--Transaction manager object-->
    <!--<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>--> 


// Notification enhancement
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
       //Define some attributes of the transaction * indicates that the methods with any name currently follow the default configuration

     <!--
            name: Tangent point method name
            isolation: Isolation level of transaction
            propagation: Propagation behavior of transactions
            read-only: Read only
            timeout: Timeout
        -->

        <tx:attributes>
            <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" timeout="-1"/>
            //CRUD common configuration
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*"/>

        </tx:attributes>
    </tx:advice>
        
        

(3) Transaction manager AOP configuration

  • When using spring to manage transactions declaratively, you should use aop:advisor to configure aop!
//aop configuration: configure aspect   
<aop:config>  
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.lagou.servlet.impl.AccountServiceImpl.*(..))"/>
    </aop:config>-->

Details of transaction parameter configuration:

<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED"
timeout="-1" read-only="false"/>

  • Name: tangent point method name
  • Isolation: isolation level of transaction
  • Propagation: propagation behavior of transactions
  • Timeout: timeout
  • Read only: read only

4. Annotation based declarative transaction control (key)

Steps:

  1. Modify the service layer and add transaction annotation
  2. Modify the spring core configuration file and enable transaction annotation support

4.1 modify the service layer and add transaction annotations

@Service
public class AccountServiceImpl implements AccountService {
  @Autowired
  private AccountDao accountDao;
    
    @Transactional(propagation = Propagation.REQUIRED, isolation =
Isolation.REPEATABLE_READ, timeout = -1, readOnly = false)
  @Override
  public void transfer(String outUser, String inUser, Double money) {
    accountDao.out(outUser, money);
    int i = 1 / 0;
    accountDao.in(inUser, money);
 }
}

4.2 modify the spring core configuration file and enable transaction annotation support

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w2.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">
  <!--Before omitting datsSource,jdbcTemplate,Component scan configuration-->
 
  <!--Transaction manager-->
  <bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
  </bean>
 
  <!--Annotation support for transactions-->
  <tx:annotation-driven/>
</beans

4.3 annotation only

Core configuration class:

@Configuration  // Declare this class as the core configuration class
@ComponentScan("com.lagou")  // Packet scanning
@Import(DataSourceConfig.class) //Import other configuration classes
@EnableTransactionManagement //Annotation driven transactions
public class SpringConfig {

    @Bean
    public JdbcTemplate getJdbcTemplate(@Autowired DataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }

    @Bean
    public PlatformTransactionManager getPlatformTransactionManager(@Autowired DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
        return dataSourceTransactionManager;
    }


}

Data source configuration class:

@PropertySource("classpath:jdbc.properties") //Import properties file
public class DataSourceConfig {

    @Value("${jdbc.driverClassName}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;



    @Bean //The return value object of the current method will be put into the IOC container
    public DataSource getDataSource(){

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }



}

Knowledge summary:

  • Platform transaction manager configuration (xml, annotation mode)
  • Configuration of transaction notification (@ Transactional annotation configuration)
  • Transaction annotation driven configuration < TX: annotation driven / >, @ EnableTransactionManagement

Topics: Java Spring xml