UTF-8
4.12
0.9.5.2
5.1.38
5.0.8.RELEASE
1.8.10
org.aspectj
aspectjweaver
${aspect.version}
org.aspectj
aspectjrt
${aspect.version}
org.springframework
spring-context
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-test
${spring.version}
test
mysql
mysql-connector-java
${mysql.version}
com.mchange
c3p0
${c3p0.version}
junit
junit
${junit.version}
test
public class Account {
private int id;
private String name;
private double money;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
}
public interface AccountDao {
//减钱操作
public void reduce(int id,double money);
//加钱操作
public void increase(int id,double money);
}
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao{
//减钱操作
@Override
public void reduce(int id, double money) {
String sql = "update t_account set money=money-? where id=?";
this.getJdbcTemplate().update(sql, money,id);
}
//加钱操作
@Override
public void increase(int id, double money) {
String sql = "update t_account set money=money+? where id=?";
this.getJdbcTemplate().update(sql, money,id);
}
}
public interface AccountService {
//转账
public void transfer(int id1, int id2, double money);
}
//@Transactional开启事务管理,在类前面表示整个的所有方法都开启事务管理
@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,readOnly=false)
public class AccountServiceImpl implements AccountService{
@Resource(name="accountDao")
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void transfer(int id1, int id2, double money) {
//先减钱
accountDao.reduce(id1,money);
//增加异常
//int a = 1/0;
//再加钱
accountDao.increase(id2, money);
}
}
开启注解即可
)
aop的隔离级别和传播行为
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-transaction.xml")
public class TestTransaction {
@Resource(name="accountService")
private AccountService accountService;
@Test
public void test1() {
//转账50
accountService.transfer(1, 2, 50);
}
}
int a=1/0;
),没有增加事务管理的话会出现A给B转钱,A扣了钱,B 却没有收到钱;增加事务管理后出现异常数据库会回滚,所以不会发生丢钱的结果: