一、Spring中的事务控制
1.Spring中事务控制的API介绍:
------PlatformTransactionManager:平台事务管理器是Spring真正管理事务的对象,是一个接口。常用实现类有如下两个:
DataSourceTransactionManager :针对JDBC和mybatis事务管理
HibernateTransactionManager :针对Hibernate事务管理
TransactionDefinition:事务定义的对象
TransactionStatus:事务状态信息的对象
Spring框架进行事务的管理,首先使用TransactionDefinition对事务进行定义。通过PlatformTransactionManager根据TransactionDefinition的定义信息进行事务的管理。在事务管理过程中产生一系列的状态:保存到TransactionStatus中。
事务的Demo
要求:模仿转账,如果出现了异常,事务回滚,金额不变
//实体类
public class Account {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
//账户的业务层接口:
public interface IAccountService {
void transfer(String sourceName,String targetName,Float money);
}
//账户的业务层实现类:
public class AccountServiceImpl implements IAccountService {
//注入AccountDaoImpl
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
//通过账户名称查询账户
Account source = accountDao.queryAccountByName(sourceName);
Account target = accountDao.queryAccountByName(targetName);
//修改金额
source.setMoney(source.getMoney()-money);
target.setMoney(target.getMoney()+money);
//执行修改
accountDao.updateAccount(source);
accountDao.updateAccount(target);
}
//持久层接口:
public interface IAccountDao {
Account queryAccountByName