1. 导入驱动,连接池,jdbc和AOP的依赖
<!-- 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这个注解一定要开启
/** * 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类
/** * 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. 测试类
/** * 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 结果
出异常就回滚,否则入库。
原文地址:https://www.cnblogs.com/zhangjianbing/p/10142237.html
时间: 2024-11-08 23:14:43