步骤
* 环境搭建:
* 1、导入相关依赖
* 数据源、数据库驱动、Spring-jdbc模块
*
* 2、配置数据源、JdbcTemplate(Spring提供的简化数据库操作的工具)数据操作
* 3、 @Transactional表示当前方法为事务方法
* 4、 @EnableTransactionManagement开启事务管理功能
* 5、 配置事务管理器来管理事务
配置类
@EnableTransactionManagement
@ComponentScan("com.dwd.snail.testspring.test.tx")
@Configuration
public class TxConfig {
@Bean
public DataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource=new ComboPooledDataSource();
dataSource.setUser("root");
dataSource.setPassword("123456");
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/snailtest?characterEncoding=utf8");
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate() throws PropertyVetoException {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource());
return jdbcTemplate;
}
//一定要注册事务管理器在容器中
@Bean
public PlatformTransactionManager platformTransactionManager() throws PropertyVetoException {
return new DataSourceTransactionManager(dataSource());
}
}
service
@Service
public class UserService {
@Autowired
private UserDao userDao;
@Transactional
public void insertUser(){
userDao.insert();
System.out.println("======================插入成功===========================");
int i=10/0;
}
}
Dao
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void insert(){
String sql="INSERT INTO student_info (name,nickname,age) VALUES (?,?,?)";
String randomstr=UUID.randomUUID().toString().substring(0,2);
String name="黄"+ randomstr;
String nickname="蜗牛"+ randomstr;
int x=(int)(Math.random()*100);
jdbcTemplate.update(sql,name,nickname,x);
}
}
test
public class IocTest_tx {
AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(TxConfig.class);
@Test
public void test01(){
// printBeans(applicationContext);
// applicationContext.close();
UserService userService = applicationContext.getBean(UserService.class);
userService.insertUser();
applicationContext.close();
}
// private void printBeans(AnnotationConfigApplicationContext applicationContext){
// String[] names=applicationContext.getBeanDefinitionNames();
// for (String name:names){
// System.out.println(name);
// System.out.println(applicationContext.getBean(name));
// }
// }
}