一、事务
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) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部