spring中的事务管理
在springboot中,使用事务非常的简单,因为springboot已经帮我们配置好了,只需要加上注解@Transactional即可
在spring中我们需要做一些配置:主要有三点:
- @Transactional:在相应的方法上加上这个注解
- @EnableTransactionManagement:在配置类中加上,开启事务管理
- 需要在配置类中加入PlatformTransactionManager
PlatformTransactionManager接口定义了两个方法commit和rollback
public interface PlatformTransactionManager { TransactionStatus getTransaction(TransactionDefinition var1) throws TransactionException; void commit(TransactionStatus var1) throws TransactionException; void rollback(TransactionStatus var1) throws TransactionException; }
首先创建一个配置类:MainTxConfig
@EnableTransactionManagement //开启事务管理 @ComponentScan("com.springTx") //扫描组件,这里扫描UserDao和UserService @Configuration public class MainTxConfig { /** * 配置数据源 * @return * @throws Exception */ @Bean public DataSource dataSorce() throws Exception { ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource(); comboPooledDataSource.setUser("root"); comboPooledDataSource.setPassword("123456"); comboPooledDataSource.setDriverClass("com.mysql.jdbc.Driver"); comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/study"); return comboPooledDataSource; } /** * jdbc模板操作数据库,这里需要获取到数据源,dataSorce()是从容器中获取已有的组件,而不是重新又创建一个数据源 * @return * @throws Exception */ @Bean public JdbcTemplate jdbcTemplate() throws Exception { return new JdbcTemplate(dataSorce()); } @Bean public PlatformTransactionManager platformTransactionManager() throws Exception { return new DataSourceTransactionManager(dataSorce()); } }
UserService
@Service public class UserService { @Autowired private UserDao userDao; @Transactional public void insertUser(){ userDao.insert(); int n = 1/0; System.out.println("插入成功"); } }
UserDao:
@Repository public class UserDao { @Autowired private JdbcTemplate jdbcTemplate; public void insert(){ String sql = "insert into user (name,age) value(?,?)"; String name = UUID.randomUUID().toString().substring(1,7); jdbcTemplate.update(sql,name, 20); } }
测试:
public class Txtest { @Test public void test(){ //创建容器 AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainTxConfig.class); UserService userService = applicationContext.getBean(UserService.class); userService.insertUser(); applicationContext.close(); } }
当出现异常时,事务会进行回滚操作。