zoukankan      html  css  js  c++  java
  • 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值为指定名称则抛出异常,造成事务回滚

  • 相关阅读:
    第十二章学习笔记
    UVa OJ 107 The Cat in the Hat (戴帽子的猫)
    UVa OJ 123 Searching Quickly (快速查找)
    UVa OJ 119 Greedy Gift Givers (贪婪的送礼者)
    UVa OJ 113 Power of Cryptography (密文的乘方)
    UVa OJ 112 Tree Summing (树的求和)
    UVa OJ 641 Do the Untwist (解密工作)
    UVa OJ 105 The Skyline Problem (地平线问题)
    UVa OJ 100 The 3n + 1 problem (3n + 1问题)
    UVa OJ 121 Pipe Fitters (装管子)
  • 原文地址:https://www.cnblogs.com/jony-it/p/11432083.html
Copyright © 2011-2022 走看看