- Spring事务:在业务层保障一系列的数据库操作同成功同失败
转钱案例
转钱异常
AccountServiceImpl.java
package com.wangpeng.service.impl;
import com.wangpeng.dao.AccountDao;
import com.wangpeng.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
AccountDao accountDao;
@Override
public void transfer(String nameOne, String nameTwo, Integer num) {
// nameOne借进num
accountDao.borrow(nameOne, num);
// 此处发生转账异常
int num = 1 / 0;
// nameTwo借出num
accountDao.lend(nameTwo, num);
}
}
AccountDao.java
package com.wangpeng.dao;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
public interface AccountDao {
@Update("update account set money = money - #{money} where name = #{name}")
void borrow(@Param("name") String name, @Param("money") int money);
@Update("update account set money = money + #{money} where name = #{name}")
void lend(@Param("name") String name, @Param("money") int money);
}
ServiceTest.java
package com.wangpeng.service;
import com.wangpeng.config.SpringConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class ServiceTest {
@Autowired
private AccountService accountService;
@Test
public void test1() {
accountService.transfer("Tom", "Jack", 50);
}
}
这时候就会发生转账异常,程序被中断,nameOne的账户发生改变,而nameTwo的账户未发生改变。所以现在的解决问题就在于要添加事务在业务层接口方法上,方法中对数据库一系列操作同成功同失败。
添加事务
1.在业务层接口中添加Spring事务管理
2.设置事务管理器
@Bean
public PlatformTransactionManager getPlatformTransactionManager(DataSource dataSource) {
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
dataSourceTransactionManager.setDataSource(dataSource);
return dataSourceTransactionManager;
}
3.开启注解式事务驱动