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.


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


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

2. Programming transaction control related objects


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


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_COMMITTED read committed (can solve dirty read problem)

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


    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.


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

(2) Transaction manager notification configuration

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

// 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: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="*"/>


(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:advisor advice-ref="txAdvice" pointcut="execution(* com.lagou.servlet.impl.AccountServiceImpl.*(..))"/>

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)


  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

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

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

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
  <!--Before omitting datsSource,jdbcTemplate,Component scan configuration-->
  <!--Transaction manager-->
  <bean id="transactionManager"
    <property name="dataSource" ref="dataSource"></property>
  <!--Annotation support for transactions-->

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 {

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

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


Data source configuration class:

@PropertySource("") //Import properties file
public class DataSourceConfig {

    private String driver;
    private String url;
    private String username;
    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();
        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