Transactional transaction based on XML - spring learning 07

Posted by leeandrew on Tue, 08 Mar 2022 04:03:38 +0100

Transaction management in Spring

Before understanding the business: say a lie and withdraw money, such as you go ATM There are generally two steps to withdraw 1000 yuan by machine: first, enter the password amount and deduct 1000 yuan from the bank card; then ATM Pay 1000 yuan. Both steps must be performed or neither. If the bank card deducts 1000 yuan, but ATM If you fail to pay, you will lose 1000 yuan; If the bank card fails to deduct money, but ATM But out of 1000 yuan, the bank will lose 1000 yuan. Therefore, if one step succeeds and the other fails, it is not good for both sides. If no matter which step fails, the whole withdrawal process can be rolled back, that is, all operations can be cancelled completely, which is excellent for both sides. 
Transactions are used to solve similar problems. A transaction is a series of actions. When they are combined together, they are a complete unit of work. These actions must be completed. If one fails, the transaction will roll back to the initial state as if nothing had happened. 
In enterprise application development, transaction management is an essential technology to ensure the integrity and consistency of data.

Characteristics of transactions:

  • Atomicity: do it all or don't do it all.
  • Consistency: once the transaction is completed (whether successful or failed), the system must ensure that the business it models is in a consistent state, rather than partial completion and partial failure. In reality, data should not be destroyed.
  • Isolation: many 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 system error occurs, its result should not be affected, so it can recover from any system crash. Typically, the result of a transaction is written to persistent storage.
1. Core interface of transaction management

The jar package of spring contains a jar package named spring-tx-4.3.6 release. This package is a dependency package provided by spring for transaction management. At the package's org springframework. The transaction package contains three core interfaces for transaction management.

  • PlatformTransactionManager interface:

Provides a platform transaction manager for managing transactions.

TransactionStatus getTransaction (TransactionDefinition): used to obtain transaction status information. Spring encapsulates the transaction details configured in xml into the object TransactionDefinition, then obtains the transaction status (TransactionStatus) through the getTransaction() method of the transaction manager, and carries out the next operation on the transaction.

void commit (transactionstatus): used to commit transactions.

void rollback (transactionstatus): used to rollback transactions.

  • TransactionDefinition interface
    The TransactionDefinition interface is the object of transaction definition (description). It provides methods to obtain transaction related information, including five operations, as follows.
  1. String getName(): get the name of the transaction object.
  2. int getIsolationLevel(): get the isolation level of the transaction.
  3. int getPropagationBehavior(): get the propagation behavior of the transaction.
  4. int getTimeout(): get the timeout of the transaction.
  5. boolean isReadOnly(): gets whether the transaction is read-only.
  • TransactionStatus interface
    The TransactionStatus interface is the status of a transaction. It describes the status information of a transaction at a certain point in time. It contains six operations
    1. void flush(); Refresh transaction
    2. boolean hasSavepoint(); Gets whether a savepoint exists
    3. boolean isCompleted(); Gets whether the transaction is complete
    4. boolean isNewTransaction(); Gets whether it is a new transaction
    5. boolean isRollbackOnly(); Get whether to roll back
    6. void setRollbackOnly(); Transaction rollback settings
2. Declarative transaction management:

2.1: XML based approach:

Interface class

 //outUser remitter inUser payee   
    public void transfer(String outUser,String inUser,Double money);
}

Implementation class

public void transfer(String outUser, String inUser, Double money) {

    this.jdbcTemplate.update("update account set balance = balance +?"+
            "where username = ?",money,inUser);

    this.jdbcTemplate.update("update account set balance = balance -?"+
            "where username = ?",money,outUser);
}

Control class

@Controller
public class AccountController {
}

Entity class

public class Account {
    private Integer id;
    private String username;
    private Double balance;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Double getBalance() {
        return balance;
    }

    public void setBalance(Double balance) {
        this.balance = balance;
    }

    public String toString() {
        return "Account [id=" + id + ", "
                + "username=" + username + ", "
                + "balance=" + balance + "]";
    }
}

Test class

public class TransactionTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
        AccountDao accountDao = (AccountDao) applicationContext.getBean("accountDao");
        accountDao.transfer("Tom", "man", 1000.0);
        System.out.println("Transfer succeeded----------");
    }
}

Configuration code based on transaction management -- "key points" (learn the code comments inside)

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
          http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.3.xs
">
    <!-- 1.Configure data source-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <!--Database driven-->
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <!--Connection to database url-->
        <property name="url" value="jdbc:mysql://localhost:3306/spring"/>
        <!--User name to connect to the database-->
        <property name="username" value="root"/>
        <!--Password to connect to the database-->
        <property name="password" value="123456"/>
    </bean>

    <!--  2.to configure JDBC Template-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--Data source must be used by default-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--  3.definition id by accountDao of Bean-->
    <bean id="accountDao" class="com.lz.jiaotong.dao.impl.AccountDaoImpl">
        <!--take jdbcTempla Inject into accountDao Instance-->
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
    <!--  4.Transaction manager, dependent on data source-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--  5.Write notifications and enhance transactions. You need to write entry points and specific transaction details-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" isolation="DEFAULT" read-only="false"/>
        </tx:attributes>
    </tx:advice>
    <!--  6.to write aop Give Way spring The automatic generation agent for the target needs to be used AspectJ Expression for-->
    <aop:config>
        <aop:pointcut expression="execution(* com.lz.jiaotong.dao.impl.*.*(..))" id="txPointcut"/>
<!--  Aspect: integrate entry points with notifications-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
</beans>

Topics: Java Spring