Java EE - Spring learning notes 04 [transaction management of Spring]

Posted by congos on Sat, 19 Feb 2022 15:31:22 +0100

Java EE - Spring learning notes 01 [Ioc development model]

Java EE - Spring learning notes 02 [integration of Spring and Mybatis]

Java EE - Spring learning notes 03 [AOP development]

Java EE - Spring learning notes 04 [transaction management of Spring]

Java EE - Spring learning notes 05 [Mybatis's retrograde project]

catalogue

6, Transaction management of Spring (built-in AOP)

1. What is a transaction

2. Four characteristics of affairs (interview questions)

2.1 atomicity

2.2 consistency

2.3 isolation

2.4 persistence

3. Problems caused by transaction concurrency

3.1 dirty reading

3.2 unreal reading (virtual reading)

3.2 non repeatable

4. Solve the problem of reading

4.1 Read uncommitted: uncommitted

4.2 Read committed: read committed

4.3 Repeatable read: repeatable read

4.4 Serializable: serialized read

5. Seven communication behaviors of affairs

5.1 ensure that multiple operations are in the same transaction

5.2 ensure that multiple operations are not in the same transaction

5.3 nested transactions

6. API of spring transaction management

6.1 Platform Transaction Manager

6.2 transaction definition

6.3 transaction status

6.4 API management of transaction management

7. Spring transaction configuration (business layer)

7.1 declarative transaction management (xml mode)

7.2 annotated transaction management

7.3 programmed transaction management

8. Summary of spring

8.1 Ioc of spring

8.2 AOP of spring

8.3 integration of Spring and Mybatis

6, Transaction management of Spring (built-in AOP)

There is an exception in the remittance business. If the tenth five year plan management is not considered, it will lead to the loss of funds of the remitter, and the payee will collect the funds from the remitter. We need to design the program closely and use Spring's tenth five year management mechanism to solve the problems of transactions in the business layer.

1. What is a transaction

Database transaction is a sequence of database operations that access and operate various data items. These operations are either all executed or not executed. It is an inseparable work unit. A transaction consists of all database operations performed between the beginning and end of the transaction.

Database transactions are a series of operations, either all successful or all failed.

2. Four characteristics of affairs (interview questions)

2.1 atomicity

Transactions are inseparable, either all or none.

2.2 consistency

The transaction must change the database from one correct state to another (the data before and after the execution of the transaction must be consistent)

2.3 isolation

The execution of one transaction cannot be disturbed by other transactions.

2.4 persistence

After the transaction is executed, the data will be permanently saved.

3. Problems caused by transaction concurrency

Concurrency: simultaneous

3.1 dirty reading

Dirty read means that transaction A reads uncommitted data in transaction B.

3.2 unreal reading (virtual reading)

Unreal reading refers to the operation in a transaction that finds data that has not been manipulated.

3.2 non repeatable

A data is read twice in a transaction, and the read data is inconsistent.

4. Solve the problem of reading

Set the isolation level of transactions

4.1 Read uncommitted: uncommitted

No reading problem can be solved

4.2 Read committed: read committed

Dirty reading is solved, but non repeatable reading and virtual reading may also occur.

4.3 Repeatable read: repeatable read

It solves the problem of non repeatable reading, but phantom reading may exist

4.4 Serializable: serialized read

Solve all reading problems

5. Seven communication behaviors of affairs

5.1 ensure that multiple operations are in the same transaction

 5.1.1 PROPAGATION_REQUIRED

The default propagation behavior. If there is A transaction in A, the transaction in A will be used. If there is no transaction in A, A new transaction will be created to include the operation.

 5.1.2 PROPAGATION_SUPPORTS

Transactions are supported. If there are transactions in A, the transactions in A will be used. If there are no transactions in A, the transactions will not be used.

 5.1.3 PROPAGATION_MANDATORY

If there is a transaction in a, use the transaction in A. if there is no transaction in a, throw an exception.

5.2 ensure that multiple operations are not in the same transaction

 5.2.1 PROPAGATION_REQUIRES_NEW

If there is A transaction in A, suspend the transaction in A and create A new transaction containing only its own operations. If there is no transaction in A, create A new transaction containing its own operations!

 5.2.2 PROPAGATION_NOT_SUPPORTED

If there is A transaction in A, suspend the transaction in A and do not use the transaction.

 5.2.3 PROPAGATION_NEVER

If there is A transaction in A, report the difference

5.3 nested transactions

 5.3.1 PROPAGATION_NESTED

For nested transactions, if there are fifteen transactions in a, they will be executed according to the transactions in A. after execution, a savepoint will be set to execute the operations in B. if there are no exceptions, you can choose to rollback to the original location or this savepoint if there are exceptions.

6. API of spring transaction management

6.1 Platform Transaction Manager

Platform transaction manager, which is an interface, is another real object used by Spring to manage transactions

        1. Data source transaction manager: the underlying layer is JDK to manage transactions

        2. Hibernate transaction manager: the bottom layer is to use hibernate to manage transactions

6.2 transaction definition

Transaction definition: used to define transaction related information, isolation level, propagation behavior, readability, etc.

6.3 transaction status

Transaction status: used to record the transaction status object in the process of transaction management

6.4 API management of transaction management

When Spring carries out transaction management, the platform transaction manager first carries out transaction management according to the transaction definition information. In the process of transaction management, various states are generated and these state information is recorded in the object of transaction state.

7. Spring transaction configuration (business layer)

7.1 declarative transaction management (xml mode)

xml mode implemented through AOP of Spring

1) update POM XML file

-- add packages for AspectJ

-- add package of Cglib

2) configure platform transaction manager (import data source)

3) configuration is the propagation behavior, isolation level and entry point of transactions

<?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: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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--<import resource="classpath:spring/applicationContext-dao.xml"/>-->
    <!--Configure the manager for platform transactions-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--Configure data source-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--Configure the isolation level and propagation behavior of transactions-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>

    <!--Configuration and transaction manager pointcuts-->
    <aop:config>
        <aop:pointcut id="txService" expression="execution(* com.bjpowernode.service.*.*(..))"/>
        <!--Transactions use built-in facets-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txService"/>
    </aop:config>
</beans>


7.2 annotated transaction management

1) configure platform transaction manager

2) configure transaction drivers

<?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: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/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
       ">

    <!--Configure the manager for platform transactions-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--Configure data source-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--Turn on the driver of transaction annotation-->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>


3) use transaction annotation in business class

/**
 * Service Layer: interface implementation class of business method
 */
@Service
@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED)
public class AccountServiceImpl implements AccountService {

    /*Inject dao layer objects*/
    @Autowired
    private AccountMapper accountMapper;
    /**
     * Method for querying all account information
     * @return
     */
    @Override
    public List<Account> findAllAccounts() {
        return accountMapper.selectAllAccounts();
    }

    /**
     * Business method of querying account information list by name
     * @param name
     * @return
     */
    @Override
    public List<Account> findAccountsByName(String name) {
        return accountMapper.selectAccountsByName(name);
    }

    /**
     * Realize the business method of adding an account information
     * @param account
     */
    @Override
    public void addAccount(Account account) {

        accountMapper.insertAccount(account);
    }

    /**
     * Business method for deleting account information according to account id
     * @param id
     */
    @Override
    public void deleteAccount(Integer id) {

        accountMapper.deleteAccount(id);
    }

    /**
     * Business method for realizing transfer function
     * @param fromName: remitter
     * @param toName: payee
     * @param money: Amount of transaction
     */
    @Override
    public void transfer(String fromName, String toName, Integer money) {

        accountMapper.outMoney(fromName, money);
        /*Deliberately set exception*/
        int num = 100/0;
        accountMapper.inMoney(toName, money);
    }
}

7.3 programmed transaction management

Directly put transaction management into business code, and we are not encouraged to use it

1) create platform transaction manager: inject data source

2) build a transaction template: inject platform transaction manager

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--1,Configure the manager for platform transactions-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--Configure data source-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--2,Configure transaction template: inject platform transaction manager-->
    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="transactionManager"/>
    </bean>
</beans>


3) inject the template object of the transaction into the business layer code

/**
 * Service Layer: interface implementation class of business method
 */
@Service
public class AccountServiceImpl implements AccountService {

    /*Inject dao layer objects*/
    @Autowired
    private AccountMapper accountMapper;

    /*Template for injection transaction*/
    @Autowired
    private TransactionTemplate transactionTemplate;
    /**
     * Method for querying all account information
     * @return
     */
    @Override
    public List<Account> findAllAccounts() {
        return accountMapper.selectAllAccounts();
    }

    /**
     * Business method of querying account information list by name
     * @param name
     * @return
     */
    @Override
    public List<Account> findAccountsByName(String name) {
        return accountMapper.selectAccountsByName(name);
    }

    /**
     * Realize the business method of adding an account information
     * @param account
     */
    @Override
    public void addAccount(Account account) {

        accountMapper.insertAccount(account);
    }

    /**
     * Business method for deleting account information according to account id
     * @param id
     */
    @Override
    public void deleteAccount(Integer id) {

        accountMapper.deleteAccount(id);
    }

    /**
     * Business method for realizing transfer function
     * @param fromName: remitter
     * @param toName: payee
     * @param money: Amount of transaction
     */
    @Override
    public void transfer(String fromName, String toName, Integer money) {

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {

                accountMapper.outMoney(fromName, money);
                /*Deliberately set exception*/
                int num = 100/0;
                accountMapper.inMoney(toName, money);
            }
        });
    }
}

8. Summary of spring

8.1 Ioc of spring

Ioc means inversion of control in the Spring framework. Its core is to hand over the creation and management of objects to the Spring container for operation through DI dependency injection. There are two development modes: xml development and annotation development.

Xml development: using bean tags for object management

Annotation development: configure the annotation package scanner in the Spring container

8.2 AOP of spring

Enhance the function of business methods. The bottom layer is realized by dynamic agent, which is divided into JDK dynamic agent and Cglib dynamic agent.

  1. Section: auxiliary class
  2. Cut plane: target class
  3. Connection point: business method in target class
  4. Pointcut: the method that the target class is really enhanced
  5. Notice: pre, post, surround, exception, final
  6. Weaving in:

Application of transaction manager

  1. Declarative transaction: configure the platform transaction manager, configure propagation behavior and isolation level, and configure aspect and pointcut
  2. Annotated transaction: configure the platform transaction manager and the driver of annotated transaction
  3. Programming transaction: configure the platform transaction manager and configure the template of the transaction

8.3 integration of Spring and Mybatis

   1. dao layer

1) entity class corresponding to table

2) jdbc attribute file

3) dynamic agent of mybatis (interface and mapping file, main configuration file)

4) Spring handles the database connection pool, the factory object of mybatis and the container file of mybtais dynamic agent

-- load jdbc properties file

-- configure database connection pool technology (obtain mysql parameters and connection pool parameters)

-- configure the factory class object of mybatis

-- load data source

-- load the main configuration file of mybatis

-- configure alias package scanner

-- process of configuring mybatis dynamic agent

-- package of configuration mapping file

   2. service layer

1) business interface and implementation class

2) configure the container file of the business layer

-- configure the annotated package scanner

3) transaction management

-- configure platform transaction manager

-- load data source

-- configure isolation level and propagation behavior

-- configure tangent point and tangent plane

   3. test

Topics: JavaEE Spring