1. 導入驅動,鏈接池,jdbc和AOP的依賴java
<!-- c3p0數據庫鏈接池 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <!-- spring提供的jdbcTemplate模塊 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.12.RELEASE</version> </dependency> <!-- mysql連接驅動包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.44</version> <scope>runtime</scope> </dependency> <!-- AOP --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.12.RELEASE</version> </dependency>
2. 編寫配置類,@EnableTransactionManagement這個註解必定要開啓mysql
/** * description * * @author 70KG * @date 2018/12/19 */ @Configuration @ComponentScan("com.nmys.story.springCore.springaop.tx_sample") @EnableTransactionManagement // -- 開啓基於註解的事務管理 public class TxConfig { // -- 配置數據源 @Bean public DataSource dataSource() throws Exception { ComboPooledDataSource pool = new ComboPooledDataSource(); pool.setUser("root"); pool.setPassword("root"); pool.setDriverClass("com.mysql.jdbc.Driver"); pool.setJdbcUrl("jdbc:mysql://47.104.129.162:3306/usthe?useSSL=false"); return pool; } // -- 加入模板 @Bean public JdbcTemplate jdbcTemplate() throws Exception { JdbcTemplate template = new JdbcTemplate(dataSource()); return template; } // -- 配置事務管理器,它纔是用來提交回滾事務的主導者 @Bean public DataSourceTransactionManager txManager() throws Exception { DataSourceTransactionManager tx = new DataSourceTransactionManager(dataSource()); return tx; } }
3. Service類和Dao類spring
/** * description * * @author 70KG * @date 2018/12/19 */ @Service public class TxService { @Autowired private TxDao txDao; public void insertLog(){ txDao.insertSth(); } }
/** * description * * @author 70KG * @date 2018/12/19 */ @Repository public class TxDao { @Autowired private JdbcTemplate jdbcTemplate; // @Transactional僅代表它是一個事務方法,開啓事務僅有註解是不夠的,還須要配置事務管理器 @Transactional public void insertSth() { String sql = "INSERT into sys_log (username) VALUES(?);"; jdbcTemplate.update(sql, "lisi"); System.out.println("------>插入成功"); int i = 10/0; } }
4. 測試類sql
/** * description * * @author 70KG * @date 2018/12/19 */ public class Test01 { public static void main(String[] args) { AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(TxConfig.class); TxService bean = app.getBean(TxService.class); bean.insertLog(); } }
5 結果數據庫
出異常就回滾,不然入庫。app