注解声明事务
# 使用示例
@Configuration
@EnableTransactionManagement
public class AppConfig {
@Bean
public DataSource dataSource() {
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:mysql://localhost:3306/oms");
config.setUsername("root");
config.setPassword("123456");
config.addDataSourceProperty("connectionTimeout", "1000"); // 连接超时:1秒
config.addDataSourceProperty("idleTimeout", "60000"); // 空闲超时:60秒
config.addDataSourceProperty("maximumPoolSize", "10"); // 最大连接数:10
return new HikariDataSource(config);
}
//给JdbTtemplate填充数据源
@Bean
public JdbcTemplate applicationDataConnection(){
return new JdbcTemplate(dataSource());
}
//配置事务管理器需要管理的数据源
@Bean
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
//事务管理器放入事务模板
@Bean
public TransactionTemplate transactionTemplate(){
return new TransactionTemplate(transactionManager());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@Autowired
private JdbcTemplate jdbcTemplate;
//在方法上使用注解声明使用事务
@Transactional
public int addUser(String userName) {
String sql = "insert into user(user_name)values(?)";
int update = jdbcTemplate.update(sql, userName);
System.out.println("affect row:"+update );
throw new RuntimeException();
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
执行该方法打印日志
2021-12-15 11:34:50,355 DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Executing prepared SQL update
2021-12-15 11:34:50,356 DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Executing prepared SQL statement [insert into user(user_name)values(?)]
2021-12-15 11:34:50,364 DEBUG [com.zaxxer.hikari.pool.HikariPool] - HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@408f98d0
2021-12-15 11:34:50,404 DEBUG [com.zaxxer.hikari.pool.HikariPool] - HikariPool-1 - Added connection com.mysql.cj.jdbc.ConnectionImpl@1b292eb
affect row:1
2021-12-15 11:34:50,407 DEBUG [org.springframework.jdbc.datasource.DataSourceTransactionManager] - Initiating transaction rollback
2021-12-15 11:34:50,407 DEBUG [org.springframework.jdbc.datasource.DataSourceTransactionManager] - Rolling back JDBC transaction on Connection [HikariProxyConnection@1815007437 wrapping com.mysql.cj.jdbc.ConnectionImpl@616ac46a]
2021-12-15 11:34:50,408 DEBUG [org.springframework.jdbc.datasource.DataSourceTransactionManager] - Releasing JDBC Connection [HikariProxyConnection@1815007437 wrapping com.mysql.cj.jdbc.ConnectionImpl@616ac46a] after transaction
Exception in thread "main" java.lang.RuntimeException
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
事务回滚成功。
编辑 (opens new window)
上次更新: 2023/04/09, 16:34:32