springboot 声明式事物

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

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

 

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

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

它的属性比较重要,通常状况下不须要设置,包括ide

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

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

timeout:事物过时时间code

readOnly:只读事物,默认falseorm

rollbackFor:某个异常致使回滚blog

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值为指定名称则抛出异常,形成事务回滚

相关文章
相关标签/搜索