jdbctemplate 没有回滚
时间: 2023-09-13 16:07:30 浏览: 183
在使用 JdbcTemplate 进行数据库操作时,如果遇到异常需要回滚事务,可以使用 Spring 提供的事务管理机制来实现自动回滚。
在 Spring 中,可以使用 @Transactional 注解来声明事务。当方法标注了 @Transactional 注解时,Spring 会在方法开始执行前开启事务,在方法执行结束后判断是否有异常抛出,如果有异常抛出,则会自动回滚事务。如果没有异常抛出,则会提交事务。
以下是一个使用 JdbcTemplate 和 @Transactional 注解实现自动回滚的示例代码:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
@Transactional(rollbackFor = Exception.class)
public void addUser(User user) {
String sql = "INSERT INTO user (name, age) VALUES (?, ?)";
jdbcTemplate.update(sql, user.getName(), user.getAge());
if (user.getName().equals("test")) {
throw new RuntimeException("Exception occurred");
}
}
}
```
在上面的示例中,如果插入的用户名称为 "test",则会抛出运行时异常,事务会自动回滚,数据库中不会插入该用户信息。如果插入的用户名称不是 "test",则会提交事务,数据库中会插入该用户信息。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)