Spring学习笔记-05. Spring事务的使用

配置HikariDataSource测试环境

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Configuration
public class RzConfig {
@Bean
public DataSource dataSource() {
//此处也可以写到配置文件中
final HikariConfig cpConfig = new HikariConfig();
cpConfig.setDriverClassName("com.mysql.cj.jdbc.Driver");
cpConfig.setJdbcUrl("jdbc:mysql://localhost:3306/rzframe?characterEncoding=utf8&useSSL=true&autoReconnect=true&failOverReadOnly=false&serverTimezone=UTC");
cpConfig.setUsername("root");
cpConfig.setPassword("abc12345");
cpConfig.setMaximumPoolSize(10);
HikariDataSource hikariDataSource = new HikariDataSource(cpConfig);
return hikariDataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(){
return new JdbcTemplate(dataSource());
}
}

编写事务代码和执行

  1. @Configuration增加@EnableTransactionManagement注解

  2. 注册PlatformTransactionManager

1
2
3
4
5
@Bean
public PlatformTransactionManager platformTransactionManager(){
return new DataSourceTransactionManager(dataSource());
}

  1. 写一个Service主动抛出异常
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

@Service
public class MenuService {
@Autowired
JdbcTemplate jdbcTemplate;

@Transactional
public void insertMenu() throws Exception {
String sql = "insert into `rz_menu` (`menu_name`, `menu_src`, `menu_icon`, `menu_status`, `parentmenu_id`, `create_time`, `dataChange_lastTime`) values('test','/','fa-desktop','0','0',now(),now());";
jdbcTemplate.execute(sql);
int i = 1 / 0;

}
}

执行Service 程序运行报错,数据也无法正常的插入。