这里写自定义目录标题
- 一、使用 transactionManager
- 1、向容器中注入事务管理器
- 2、使用 transactionManager 提交事务
- 3、测试
- 二、使用TransactionTemplate
- 1、向容器中注入 TransactionTemplate
- 2、开启事务
一、使用 transactionManager
1、向容器中注入事务管理器
@Configuration //配置类
public class SpringConfig {@Beanpublic DataSource getDataSource() {DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");dataSource.setUsername("root");dataSource.setPassword("houchen");dataSource.setUrl("jdbc:mysql://192.168.239.11:3306/atguigu_spring6?characterEncoding=utf8&useSSL=false");return dataSource;}@Beanpublic DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource) {DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();dataSourceTransactionManager.setDataSource(dataSource);return dataSourceTransactionManager;}
2、使用 transactionManager 提交事务
@Overridepublic void buyBook1(Integer bookId, Integer userId) {// 开启事务TransactionDefinition definition = new DefaultTransactionDefinition();TransactionStatus status = transactionManager.getTransaction(definition);try {//根据图书id查询图书价格Integer price = bookDao.getBookPriceByBookId(bookId);//更新图书表库存量 -1bookDao.updateStock(bookId);System.out.println(1 / 0);//更新用户表用户余额 -图书价格bookDao.updateUserBalance(userId, price);// 提交事务transactionManager.commit(status);} catch (Exception e) {transactionManager.rollback(status);}}
3、测试
发起请求后,报错了,但是数据库的数据并没有发生修改
二、使用TransactionTemplate
1、向容器中注入 TransactionTemplate
@Configuration //配置类
@ComponentScan("com.atguigu.spring6.tx")
public class SpringConfig {@Beanpublic DataSource getDataSource() {DruidDataSource dataSource = new DruidDataSource();dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");dataSource.setUsername("root");dataSource.setPassword("houchen");dataSource.setUrl("jdbc:mysql://192.168.239.11:3306/atguigu_spring6?characterEncoding=utf8&useSSL=false");return dataSource;}@Beanpublic DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource) {DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();dataSourceTransactionManager.setDataSource(dataSource);return dataSourceTransactionManager;}@Beanpublic TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {return new TransactionTemplate(transactionManager);}
}
2、开启事务
@Overridepublic void buyBook2(Integer bookId, Integer userId) {transactionTemplate.execute(transactionStatus -> {//根据图书id查询图书价格Integer price = bookDao.getBookPriceByBookId(bookId);//更新图书表库存量 -1bookDao.updateStock(bookId);System.out.println(1 / 0);//更新用户表用户余额 -图书价格bookDao.updateUserBalance(userId, price);return null;});}