1.什么是事务?
事务是数据库操作最基本的单元,逻辑上的一组操作,要么都成功,要么都失败。
应用场景:如转账,A向B转账,如果中间出现网络问题等异常,不能出现A减少了钱而B的钱并未增加,也就是说要么转账成功,要么转账失败
事务特性(ACID):
原子性:不可分割,要么都成功,要么都失败
一致性:操作前后总量不变
隔离性:操作时不会产生互相影响
持久性:提交后数据库中的数据会发生变化
事务一般添加到service层中
具体操作如下
1.创建accountDao接口以及实现类,实现转账和取钱两个操作
public interface accountDao {
void add();
void reduce();
}
@Repository
public class accountDaoImpl implements accountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void add() {
String sql = "update t_account set money=money+? where username =?";
jdbcTemplate.update(sql,100,"tom");
}
@Override
public void reduce() {
String sql = "update t_account set money=money-? where username =?";
jdbcTemplate.update(sql,100,"mike");
}
}
2.在service层中对方法进行调用,并开启事务
@Service
@Transactional //开启事务
public class accountService {
@Autowired
private accountDao accountDao;
public void accountMoney() {
accountDao.add();
//模拟异常
int i = 1 / 0;
accountDao.reduce();
}
}
3.创建配置类,代替XML文件,并注入相关的属性
@Configuration //配置类
@ComponentScan(basePackages = "com.atguigu")
@EnableTransactionManagement //开启事务
public class TXconfig {
//创建数据库连接池
@Bean
public DruidDataSource getDruidDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=Asia/Shanghai");
dataSource.setPassword("lmz0521");
dataSource.setUsername("root");
return dataSource;
}
//创建jdbcTemplate
@Bean
public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
//到IOC容器中根据类型找到dataSource
JdbcTemplate jdbcTemplate = new JdbcTemplate();
//注入dataSource
jdbcTemplate.setDataSource(dataSource);
return jdbcTemplate;
}
//创建事务管理器对象
@Bean
public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource) {
DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource);
return transactionManager;
}
}
4.进行测试
@Test
public void test2(){
ApplicationContext context = new AnnotationConfigApplicationContext(TXconfig.class);
accountService accountService = context.getBean("accountService", accountService.class);
accountService.accountMoney();
}
事务操作(声明式事务管理参数配置)@Transactional中的参数
propagation:事务传播行为
多事务方法之间进行调用,这个过程中事务如何进行管理
默认为REQUIRED
ioslation:事务隔离级别
MySQL中默认为REPEATABLE READ
timeout:超时时间
事务需要在一定时间内进行提交,如果不提交则回滚
默认为-1(不回滚),可以设置,秒为单位
readOnly:是否只读
读:查询操作;写:增删改操作
默认值为false,可以增删改查
可以设置为true:只能查
rollbackFor:回滚
设置出现哪些异常进行事务回滚
NoRollbackFor:不回滚
设置出现哪些异常不进行事务回滚