The use and configuration of transactions in Spring

Spring-transaction operations

1. The concept of affairs

a) What is a transaction

​ (1) Transaction is the most basic unit of database operations. Logically, a group of operations will either succeed. If one fails, all operations will fail.

​ (2) Typical scenario: Bank transfer Zhang San transfers 100 yuan to Li Si; Zhang Sanshao 100, Li Sidao 100

b) four transaction properties (the ACID (. 1) atom of (2) Consistency (3) isolation) (4) persistent view article described

2. Transaction operation (simulating transaction operation environment)

​ a) Create service, build dao, complete object creation and injection relationship

//(1)service 注入 dao,在 dao 注入 JdbcTemplate,在 JdbcTemplate 注入 DataSource
@Service
public class UserService {
    
    
 //注入 dao
 @Autowired
 private UserDao userDao;
}


@Repository
public class UserDaoImpl implements UserDao {
    
    
 @Autowired
 private JdbcTemplate jdbcTemplate;
}

​ b) Create two methods in dao: more money and less money method, create method in service (transfer method)

@Repository
public class UserDaoImpl implements UserDao {
    
    
 @Autowired
 private JdbcTemplate jdbcTemplate;
 //lucy 转账 100 给 mary
 //少钱
 @Override
 public void reduceMoney() {
    
    
 String sql = "update t_account set money=money-? where username=?";
 jdbcTemplate.update(sql,100,"lucy");
 }
 //多钱
 @Override
 public void addMoney() {
    
    
 String sql = "update t_account set money=money+? where username=?";
 jdbcTemplate.update(sql,100,"mary");
 }
}


@Service
public class UserService {
    
    
 //注入 dao
 @Autowired
 private UserDao userDao;
 //转账的方法
 public void accountMoney() {
    
    
 //lucy 少 100
 userDao.reduceMoney();
 //mary 多 100
 userDao.addMoney();
 }
}

/**
	上边代码正常执行没有问题,
	但是如果代码执行过程中出现异常,有问题,如下模拟异常!
*/
@Service
public class UserService {
    
    
    //这里执行后将会产生错误(异常),lucy 少 100后,mary不会多 100,这就不对了!!
    private UserDao userDao;
    //转账方法
    public void accountMoney(){
    
    
        userDao.reduceMoney();//lucy 少 100
        int x=10/0;
        userDao.addMoney(); //mary 多 100
    }
}

//解决上边的异常方法——【编程式事务(传统方法)】
//转账的方法
    public void accountMoney() {
    
    
        try {
    
    
            //第一步 开启事务

            //第二步 进行业务操作
            //lucy少100
            userDao.reduceMoney();

            //模拟异常
            int i = 10/0;

            //mary多100
            userDao.addMoney();

            //第三步 没有发生异常,提交事务
        }catch(Exception e) {
    
    
            //第四步 出现异常,事务回滚
        }
    }

3. Transaction operation (Introduction to Spring transaction management)

1. The transaction is added to the Service layer (business logic layer) in the JavaEE three-tier structure

2. Perform transaction management operations in Spring; two methods: programmatic transaction management, declarative transaction management (recommended)

3. Declarative transaction management (1) Based on annotation method (recommended) (2) Based on xml configuration file method

4. Declarative transaction management in Spring,Use AOP at the bottom principle

5. Spring transaction management API: Provides an interface that represents the transaction manager. This interface provides different implementation classes for different frameworks

4. Annotated declarative transaction management

<!--1、在 spring 配置文件配置事务管理器-->
<!--创建事务管理器-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 <!--注入数据源-->
 <property name="dataSource" ref="dataSource"></property>
</bean>
 <!--2、在 spring 配置文件,开启事务注解,引入名称空间!-->
<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: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">

<!--开启事务注解-->
<tx:annotation-driven transactionmanager="transactionManager"></tx:annotation-driven>
 <!--3、在 service 类上面(或者 service 类里面方法上面)添加事务注解-->
 <!--
    (1)@Transactional,这个注解添加到类上面,也可以添加方法上面
    (2)如果把这个注解添加类上面,这个类里面所有的方法都添加事务
    (3)如果把这个注解添加方法上面,为这个方法添加事务——@Transactional
	-->

5. Transaction operation (declarative transaction management parameter configuration)

Transactional (transaction propagation behavior)

​ a) Add the annotation @Transactional to the service class, and you can configure transaction-related parameters in this annotation

​ b)propagation (transaction propagation behavior): multiple transaction methods are directly called, how are transactions managed in this process

​ c) There are seven kinds of spring framework transaction propagation behaviors: only two commonly used propagation behaviors are introduced below

@Transactional(propagation = Propagation.REQUIRED,)			//事务一
public void add(){
     
     
    //调用update方法
    update();
}

					  
public void update(){
     
      	//事务二
    
}

​ (1) REQUIRED : If the add method itself has a transaction, after calling the update method, update uses the transaction in the current add method;

​ If the add method itself has no transaction, after calling the update method, create a new transaction

​ (2) REQUIRED_NEW : Use add to call the update method, regardless of whether the add method has a transaction, a new transaction will be created.


Insert picture description here

ioslation (transaction isolation level)

​ a) Transaction has the characteristic to become isolation, and there will be no impact between multi-transaction operations. There are many problems without considering isolation

b) There are three problems to read: dirty reads, non-repeatable reads imaginary (phantom) Read view presented here

Dirty read: An uncommitted transaction reads data from another uncommitted transaction

Non-repeatable read: An uncommitted transaction reads to another committed transaction to modify data

Virtual read: An uncommitted transaction reads to another committed transaction to add data

​ c)) Solve: solve the read problem by setting the transaction isolation level

@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ)

timeout: timeout period

(1) The transaction needs to be committed within a certain period of time. If it is not committed, it will be rolled back. (2) The default value is -1 (no timeout), and the set time is calculated in seconds

readOnly: Whether read-only

(1) Read: query operation, write: add, modify, delete operation

(2) The default value of readOnly is false, which means it can be queried and can be added, modified and deleted.

(3) Set the readOnly value to true, after setting it to true, you can only query

rollbackFor: rollback

​ Set which exceptions occur for transaction rollback

noRollbackFor: no rollback

​ Set which exceptions occur without transaction rollback

6. Transaction operation (XML declarative transaction management)

a) Configure in the spring configuration file: the first step is to configure the transaction manager, the second step is to configure the notification, the third step is to configure the entry point and aspect

<!--1 创建事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 <!--注入数据源-->
 <property name="dataSource" ref="dataSource"></property>
</bean>
<!--2 配置通知-->
<tx:advice id="txadvice">
 <!--配置事务参数-->
 <tx:attributes>
 <!--指定哪种规则的方法上面添加事务-->
 <tx:method name="accountMoney" propagation="REQUIRED"/>
 <!--<tx:method name="account*"/>-->
 </tx:attributes>
</tx:advice>
<!--3 配置切入点和切面-->
<aop:config>
 <!--配置切入点-->
 <aop:pointcut id="pt" expression="execution(*
com.atguigu.spring5.service.UserService.*(..))"/>
 <!--配置切面-->
 <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
</aop:config>

7. Transaction operation (fully annotated declarative transaction management)

//1、创建配置类,使用配置类替代 xml 配置文件
@Configuration //配置类
@ComponentScan(basePackages = "com.atguigu") //组件扫描
@EnableTransactionManagement //开启事务
public class TxConfig {
    
    
 //创建数据库连接池
 @Bean
 public DruidDataSource getDruidDataSource() {
    
    
 DruidDataSource dataSource = new DruidDataSource();
 dataSource.setDriverClassName("com.mysql.jdbc.Driver");
 dataSource.setUrl("jdbc:mysql:///test");
 dataSource.setUsername("root");
 dataSource.setPassword("root");
 return dataSource;
 }
 //创建 JdbcTemplate 对象
 @Bean
 public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
    
    //从IOC容器中拿到配置注入的数据源
 //到 ioc 容器中根据类型找到 dataSource
 JdbcTemplate jdbcTemplate = new JdbcTemplate();
 //注入 dataSource
 jdbcTemplate.setDataSource(dataSource);
 return jdbcTemplate;
 }
 //创建事务管理器
 @Bean
 public DataSourceTransactionManager
getDataSourceTransactionManager(DataSource dataSource) {
    
    
 DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
 transactionManager.setDataSource(dataSource);
 return transactionManager;
 }
}

Guess you like

Origin blog.csdn.net/weixin_45496190/article/details/107103027