springboot有关事务的实现

一、事务
1.事务的概念

事务是指一组操作,这些操作要么全部成功,要么全部失败。如果在一组操作中有一个操作失败了,那么整个事务都应该回滚,即撤销已经执行的操作,从而保证数据的一致性和完整性。

2.事务的四个特性(ACID 特性)
  • Atomicity(原子性):事务的所有操作要么全部成功,要么全部失败。
  • Consistency(一致性):事务执行前后,数据的完整性和一致性保持不变。
  • Isolation(隔离性):事务的执行不受其他事务的干扰,即并发执行的事务之间应该相互隔离。
  • Durability(持久性):事务提交后,它的结果应该永久保存在数据库中。
3.Spring Boot 中的事务

在 Spring Boot 中,我们可以使用事务管理器来管理事务。事务管理器可以确保一系列操作要么全部成功,要么全部失败,从而保证数据的一致性和完整性。

Spring Boot 中的事务管理器是通过 AOP(面向切面编程)实现的,它可以拦截带有 @Transactional 注解的方法,并在方法执行前后自动开启和提交事务。如果方法执行过程中发生异常,事务管理器会自动回滚事务,从而保证数据的一致性和完整性。

二、IDEA具体实现(在springBoot进行事务管理)

1.开启事务

@EnableTransactionManagement

2.设置事务

@Transactional(isolation = Isolation.DEFAULT)

@Transactional(propagation = Propagation.REQUIRED)

1.在启动类中添加开始事务注解@EnableTransactionManagement
复制代码
@SpringBootApplication
@EnableTransactionManagement
public class SpringbootCenter01TxApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootCenter01TxApplication.class, args);
    }

}
2.在需要开启事物的方法上面添加设置事务注解@Transactional
复制代码
@Service
public class CustomerServiceImp  implements ICustomerService{

    @Autowired
    CustomerMapper dao;

    @Transactional
    @Override
    public void add() {
        dao.insert(new Customer("西安","五星级","ypp"));
        int a=10/0;
        dao.insert(new Customer("宝鸡","五星级","kyz"));
    }
}
3.Controller层代码
复制代码
@RestController
//@Controller
public class CustomerController {
    @Autowired
    ICustomerService service;
    
    //@ResponseBody
    @RequestMapping("/add")
    public String add() {
        service.add();
        return "成功";
    }
}
相关推荐
小羊没烦恼!3 天前
微服务化的基石——持续集成
java·大数据·word·powerpoint·.net
俊昭喜喜里3 天前
java中的继承和多态的区别
java
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
譕痕3 天前
JSONObject与JSONArray封装数据格式区别
java·json
胡写代码3 天前
别再前后端各写一套表单校验了
java·后端
小鱼能吃糖3 天前
缺陷修复总览 · mall电商项目:5类缺陷,1个病根,4个业务域
java·电商
此时不提桶,更待何时3 天前
01-06-A-JVM排查实战详解
java·jvm
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
这个DBA有点耶3 天前
MVCC深入:Read View、版本链与快照读——InnoDB并发控制的内核
数据库·mysql·架构
vipxieliang3 天前
ValidX 在 DDD 领域驱动设计中的实践
java·spring boot