添加配置
这里有 4 个配置,我们需要配置: DataSource
、DataSourceTransactionManager
、JdbcTemplate
TransactionTemplate
(JDBC 事务管理)
@Configuration @EnableTransactionManagement @Import({SummerMainService.class}) public class DataSourceConfig { @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource) { JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); return jdbcTemplate; } /** * JDBC 事务 * * @param transactionManager * @return */ @Bean public TransactionTemplate transactionTemplate(DataSourceTransactionManager transactionManager) { return new TransactionTemplate(transactionManager); } /** * 申明数据源 * * @return */ @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://127.0.0.1/summer_test?useUnicode=true&characterEncoding=utf-8&useSSL=false"); dataSource.setUsername("root"); dataSource.setPassword("root123"); return dataSource; } /** * 申明事务管理器 * * @return */ @Bean public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource) { DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(); dataSourceTransactionManager.setDataSource(dataSource); return dataSourceTransactionManager; } }
业务逻辑
下面的逻辑重要是插入一条数据,如果 id % 2 == 0
就进行事务的回滚。
public class SummerMainService { @Autowired private JdbcTemplate jdbcTemplate; /** * 编程式事务 例子: @Transactional */ @Transactional public void testCommit() { String uuid = UUID.randomUUID().toString().replace("-", ""); jdbcTemplate.update("insert into summer_main(`name`) value ('" + uuid + "')"); List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from summer_main where `name` = '" + uuid + "'"); Integer id = null; if (maps.size() > 0) { Map<String, Object> stringObjectMap = maps.get(0); id = Integer.parseInt(String.valueOf(stringObjectMap.get("id"))); if (id % 2 == 0) { throw new RuntimeException("system error transaction rollback!"); } } jdbcTemplate.update("update summer_main set remarks = 'WaKen Notes' where id = " + id); } }
程序调用
调用代码如下,我们同样还是分为三个步骤:创建容器,获取对象,调用方法。
public class TransactionTest { public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(DataSourceConfig.class); SummerMainService summerMainService = applicationContext.getBean(SummerMainService.class); summerMainService.testCommit(); } }
SQL 脚本
DROP TABLE IF EXISTS `summer_main`; CREATE TABLE `summer_main` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID', `name` varchar(200) DEFAULT NULL COMMENT '名称', `remarks` varchar(200) DEFAULT NULL COMMENT '备注', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; INSERT INTO `summer_main` (`id`, `name`, `remarks`) VALUES (1,'1af523e120ee4229aaedea1badd6af69','WaKen Notes'), (2,'16988516671447afa585dfc3a0069dd6',NULL), (3,'820708fb5daa469786272f21410b53c1','WaKen Notes'), (4,'c4247f97ed524d609e6afe2d7db461ff',NULL);