这里写自定义目录标题
一、使用 transactionManager
1、向容器中注入事务管理器
@Configuration //配置类
public class SpringConfig {
@Bean
public 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;
}
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource) {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
2、使用 transactionManager 提交事务
@Override
public void buyBook1(Integer bookId, Integer userId) {
// 开启事务
TransactionDefinition definition = new DefaultTransactionDefinition();
TransactionStatus status = transactionManager.getTransaction(definition);
try {
//根据图书id查询图书价格
Integer price = bookDao.getBookPriceByBookId(bookId);
//更新图书表库存量 -1
bookDao.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 {
@Bean
public 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;
}
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource) {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
@Bean
public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {
return new TransactionTemplate(transactionManager);
}
}
2、开启事务
@Override
public void buyBook2(Integer bookId, Integer userId) {
transactionTemplate.execute(transactionStatus -> {
//根据图书id查询图书价格
Integer price = bookDao.getBookPriceByBookId(bookId);
//更新图书表库存量 -1
bookDao.updateStock(bookId);
System.out.println(1 / 0);
//更新用户表用户余额 -图书价格
bookDao.updateUserBalance(userId, price);
return null;
});
}