第一步:
在applicationContext_service.xml里面增加事务的配置
属性分析
事务配置数据源是applicationContext_mapper.xml里面的数据源
添加事务的注解驱动的annotation-driven的最后必须是tx
事务验证
1.在service层中增加
1.创建接口
public interface AccountsService {
int save(Accounts accounts);
}
2.创建实现类
注解说明
@Transactional(propagation = Propagation.REQUIRED)事务的传播特性
@Transactional(propagation = Propagation.REQUIRED,noRollbackFor = "")添加指定发生什么异常不回滚。noRollbackFor = ""异常的类型
@Transactional(propagation = Propagation.REQUIRED,noRollbackForClassName = "") 添加指定的事务错误不回滚。noRollbackForClassName = ""异常的名称
当有多个异常不回滚时noRollbackForClassName ={"",""}
rollbackFor = "" 指定发生什么异常必须回滚
rollbackForClassName = "" 指定发生什么异常必须回滚
timeout = -1 连接超时设置,默认值是-1,表示永不超时
readOnly = false 默认是false,如果是查询操作,必须设置为true
isolation = Isolation.DEFAULT 使用数据库自己的隔离级别
@Service
@Transactional(propagation = Propagation.REQUIRED) //必须加入这个注解事务才可以正常运行,不然测试类创建的是实现类本身不是动态代理
public class AccountsServiceImpl implements AccountsService {
//切记切记
//一定会有数据访问层的对象
@Autowired
AccountsMapper accountsMapper;
@Override
public int save(Accounts accounts) {
int num=0;
num=accountsMapper.save(accounts);
System.out.println("增加账户成功!num="+num);
//手工抛出异常
System.out.println(1/0);
return num;
}
}
2.在mapper层中增加
1.增加接口
public interface AccountsMapper {
//增加账户
int save(Accounts accounts);
}
2.增加实现类的.xml
insert into accounts values (#{aid},#{aname},#{acontent});
3.测试
@Test
public void test1(){
//创建容器并启动
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext_service.xml");
AccountsService accountsService= (AccountsService) ac.getBean("accountsServiceImpl");
System.out.println(accountsService.getClass());
accountsService.save(new Accounts(203, "张三1", "账户安全1"));
}



