spring declarative transaction

1. Two kinds of transaction management supported by spring

1.1 programmatic transaction management

  • Embed transaction management code into business methods to control transaction commit and rollback
  • Disadvantages: additional transaction management code must be included in each transaction operation business logic

1.2 declarative transaction management

  • Generally, it works better than programmatic transactions.
  • The transaction management code is separated from the business method to realize the transaction management in a declarative way.
  • Transaction management is regarded as a crosscutting concern and modularized through aop method. Spring supports declarative transaction management through the Spring AOP framework.

2. Problems in testing non use transactions

2.1 environment construction

The environment is built in this blog: spring - integrate mybatis

2.2 add three methods in UserMapper

//Add a user
public int addUser(User user);
//Delete a user
public int deleteUser(int id);
//Test transaction
public void test();

2.3 write the corresponding usermapper xml

Note: the deleted Sql statement is intentionally written incorrectly here

<insert id="addUser" parameterType="user">
    insert into user(id,name,pwd) values (#{id},#{name},#{pwd})
</insert>

<delete id="deleteUser" parameterType="int">
    deletes from user where id = #{id}
</delete>

2.4 write the corresponding UserMapper implementation class

@Override
public int addUser(User user) {
    return getSqlSession().getMapper(UserMapper.class).addUser(user);
}
@Override
public int deleteUser(int id) {
    return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
}
@Override
public void test() {
    addUser(new User(5,"admin5","123456"));
    deleteUser(4);
}

2.5 register UserMapper in spring configuration file

<!--bean-->
<bean id="userMapper" class="com.lv.mapper.UserMapperImpl">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

2.6 testing

@Test
public void test(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
    userMapper.test();
}

2.7 implementation results

2.7.1 data before program execution

2.7.2 procedure execution results

2.7.3 data after program execution

Conclusion: comparing the data before and after, it is found that the data is increased, indicating that the added statement is still effective when the deletion statement is wrong

3 the test uses spring declarative transactions to solve this problem

3.1 add transaction configuration constraint in spring configuration file header

xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd

3.2 AOP constraints are also required

xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd

3.3 add the configuration of declarative transactions in the spring configuration file (key)

<!--Configure declarative transactions-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>
<!--combination AOP Implement transaction weaving-->
<!--Configure transaction notifications-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <!--Configure transactions for those methods-->
    <!--Configure the propagation properties of transactions. Default propagation="REQUIRED" There are seven configurations-->
    <tx:attributes>
        <tx:method name="add" propagation="REQUIRED"/>
        <tx:method name="delete" propagation="REQUIRED"/>
        <tx:method name="update" propagation="REQUIRED"/>
        <tx:method name="query" read-only="true"/>
        <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>
<!--Configure transaction entry-->
<aop:config>
    <aop:pointcut id="txPointCut" expression="execution(* com.lv.mapper.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>

3.4 delete the record just added and execute again

3.4.1 data before program execution

3.4.2 program execution results

3.4.3 data after program execution

Conclusion: the program execution is abnormal, and the data does not change before and after, indicating that when the deletion statement is wrong, the added statement does not take effect, and the transaction is started successfully

4 correct the program and execute it again

4.1 add usermapper The deletion statement in XML is modified correctly

<delete id="deleteUser" parameterType="int">
    delete from user where id = #{id}
</delete>

4.2 re execution

4.2.1 procedure execution results

4.2.2 data change

Conclusion: after the program is executed successfully, both statements take effect With the addition of declarative transactions, the effect of either success or failure is achieved

5 review transactions

5.1 description of the transaction

  • Transaction is very important in the project development process. It involves the problem of data consistency, which should not be careless
  • Transaction management is a necessary technology in enterprise application development to ensure data integrity and consistency
  • Transaction is to treat a series of actions as an independent unit of work, which are either completed or ineffective

5.2 four transaction attributes ACID

  • Atomicity: a transaction is an atomic operation consisting of a series of actions. The atomicity of a transaction ensures that the actions are either completely completed or completely ineffective
  • consistency: once all transaction actions are completed, the transaction will be committed. Data and resources are in a consistent state that meets business rules
  • isolation: multiple transactions may process the same data at the same time, so each transaction should be isolated from other transactions to prevent data corruption
  • Persistence: once the transaction is completed, no matter what error occurs in the system, the result will not be affected. Typically, the result of a transaction is written to persistent storage

6 supplement: spring transaction propagation feature

  • propagation_ Requisited: if there is no transaction at present, create a new transaction. If there is already a transaction, join it. This is the most common choice.
  • propagation_supports: supports the current transaction. If there is no current transaction, it will be executed in a non transaction method.
  • propagation_mandatory: use the current transaction. If there is no current transaction, an exception will be thrown.
  • propagation_required_new: create a new transaction. If there is a current transaction, suspend the current transaction.
  • propagation_not_supported: perform operations in a non transactional manner. If there is a transaction, suspend the current transaction.
  • propagation_never: execute the operation in a non transactional manner. If the current transaction exists, an exception will be thrown.
  • propagation_nested: if a transaction currently exists, it is executed within a nested transaction. If there are currently no transactions, execute and

Spring supports the above seven propagation features. The default transaction propagation behavior is PROPAGATION_REQUIRED, which is suitable for most situations.

Added by MissiCoola on Thu, 20 Jan 2022 08:44:29 +0200