Spring添加事务

第一步:

在applicationContext_service.xml里面增加事务的配置

 <!--事务处理-->
    <!--1.添加事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--因为事务必须关联数据库处理,所以要配置数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
<!--2.添加事务的注解驱动-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

属性分析

        事务配置数据源是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 id="save" parameterType="accounts">
insert into  accounts values (#{aid},#{aname},#{acontent});
</insert>

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"));


    }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值