springboot 声明式事物

Posted jony-it

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot 声明式事物相关的知识,希望对你有一定的参考价值。

关于事务处理机制ACID,记一下

原子、一致、隔离、持久,顾名思义不解释。

 

spring提供的事务处理接口:platformtransactionmanager,事务管理框架,名字好大。

使用@Transaction 注解声明事务(可以在类,也可以在方法上(方法会覆盖类上的注解属性))

它的属性比较重要,一般情况下不需要设置,包括

propagationtion(声明周期 默认REQUIRED 也就是说方法中调用其他方法如果出现异常,A、B方法都不会提交事物而会进行回滚操作)

isolation(隔离:默认DEFAULT 方法中即使调用其他方法也会保持事物的完整性,且方法A修改的数据在未提交前方法B不会读取到)

timeout:事物过期时间

readOnly:只读事物,默认false

rollbackFor:某个异常导致回滚

noRollbackFor:某个异常不会导致回滚

 

spingboot 会根据数据访问不同自动配置不同的访问事物实现bean(下面是源码)

@Bean
        @ConditionalOnMissingBean(PlatformTransactionManager.class)
        public DataSourceTransactionManager transactionManager(DataSourceProperties properties) 
            DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(this.dataSource);
            if (this.transactionManagerCustomizers != null) 
                this.transactionManagerCustomizers.customize(transactionManager);
            
            return transactionManager;
        

 

springboot 默认会自动配置事物处理接口

在使用过程中只要加上transaction注解即可

接口类

package com.duoke.demo.service;

import com.duoke.demo.bean.Person;

public interface PersonService 
    Person savePersonWithRollBack(Person person);

 

实现类

package com.duoke.demo.service.impl;

import com.duoke.demo.bean.Person;
import com.duoke.demo.service.IPersonRepository;
import com.duoke.demo.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PersonServiceImpl implements PersonService 
    @Autowired
    private IPersonRepository repository;

    @Transactional(rollbackFor = IllegalArgumentException.class)
    @Override
    public Person savePersonWithRollBack(Person person) 
        Person p = repository.save(person);
        if(person.getName().equals("王消费"))
            throw new IllegalArgumentException("已存储回滚");
        
        return p;
    

控制器

    @RequestMapping("rollback")
    public Person transation(Person person)
        person.setId("xxxx");
        return personService.savePersonWithRollBack(person);
    

 

访问rollback,如name值为指定名称则抛出异常,造成事务回滚

 

以上是关于springboot 声明式事物的主要内容,如果未能解决你的问题,请参考以下文章

springboot mybatis 事务管理

(转)SpringBoot非官方教程 | 第七篇:springboot开启声明式事务

SpringBoot事务注解@Transactional 事物回滚手动回滚事物

Spring-声明式事物

Spring 声明式事物

170110Spring 事物机制总结