环境搭建导入
maven依赖
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
< dependency >
< groupId >org.springframework</ groupId >
< artifactId >spring-jdbc</ artifactId >
< version >5.0.2.RELEASE</ version >
</ dependency >
< dependency >
< groupId >com.mchange</ groupId >
< artifactId >c3p0</ artifactId >
< version >0.9.5.5</ version >
</ dependency >
< dependency >
< groupId >mysql</ groupId >
< artifactId >mysql-connector-java</ artifactId >
< version >5.1.48</ version >
</ dependency >
|
配置数据库相关信息
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
@Configuration
@ComponentScan ( "com.spring.tx" )
public class TxConfig {
/**
* 配置数据源
*/
@Bean
public DataSource dataSource() throws PropertyVetoException {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setUser( "root" );
comboPooledDataSource.setPassword( "root" );
comboPooledDataSource.setDriverClass( "com.mysql.jdbc.Driver" );
comboPooledDataSource.setJdbcUrl( "jdbc:mysql:///test" );
return comboPooledDataSource;
}
@Bean
public JdbcTemplate jdbcTemplate() throws PropertyVetoException {
return new JdbcTemplate(dataSource());
}
}
|
添加数据访问层、业务层
?
1
2
3
4
5
6
7
8
9
10
|
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void saveUser(String name, Integer age) {
String sql = "insert into user(name, age) values(?, ?)" ;
jdbcTemplate.update(sql, name, age);
}
}
|
?
1
2
3
4
5
6
7
8
9
10
11
|
@Service
public class UserService {
@Autowired
private UserDao userDao;
public void saveUser(){
String name = "jack11" ;
Integer age = 19 ;
userDao.saveUser(name, age);
}
}
|
添加测试类
?
1
2
3
4
5
6
7
8
|
public class TxTest {
@Test
public void test(){
ApplicationContext context = new AnnotationConfigApplicationContext(TxConfig. class );
UserService userService = (UserService) context.getBean( "userService" );
userService.saveUser();
}
}
|
事务问题
此时基本环境已经搭建好了,点击运行,数据可以成功插入但是还没有配置事务,没有事务回滚会造成某些情况下数据出错。在Spring注解中,可以在需要添加事务的方法或类上加@Transactional,并且开启事务管理功能,即@EnableTransactionManagement,代码如下:
修改UserService 的 saveUser 方法
?
1
2
3
4
5
6
7
8
|
@Transactional
public void saveUser(){
String name = "jack11" ;
Integer age = 19 ;
userDao.saveUser(name, age);
int i = 1 / 0 ;
}
|
在配置类加上@EnableTransactionManagement
?
1
2
3
4
5
6
|
@Configuration
@ComponentScan ( "com.spring.tx" )
@EnableTransactionManagement
public class TxConfig {
}
|
再次运行测试方法,会发现报错了,但不是我们模拟的异常报错,控制台提示找不到bean
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.transaction.PlatformTransactionManager' available
我们还需要注册一个事务管理器来管理事务,PlatformTransactionManager有很多实现类,在Spring 中 JdbcTemplate、Mybatis应该使用 DataSourceTransactionManager
在配置类中再注册一个组件,运行,事务生效
?
1
2
3
4
5
6
7
|
/**
* 注册事务管理器
*/
@Bean
public PlatformTransactionManager platformTransactionManager() throws PropertyVetoException {
return new DataSourceTransactionManager(dataSource());
}
|
|