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 "成功";
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值