Spring注解方式处理事务

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring注解方式处理事务

少年啊!   2022-09-29 我要评论

Spring有专门的类来处理事务,在这之前我们先要理解Spring处理事务中的几个概念:

1.接口:

事务管理器是PlatformTransactionManager接口,在接口中定义了事务的主要函数:commit(); 事务提交
rollback();事务回滚

2.事务管理器接口的实现类:

1)DataSourcTransactionManager:使用jdb或者mybatis访问数据库时使用的
<bean id=”myDataSource” class=“xx包.DataSourceTransactionManager”>
必须指定数据源
</bean>
2)HibernateTransactionManager:使用Hibernate框架时,使用的实现类
3)事务超时:TIMEOUT,秒为单位,默认是-1,使用数据库的默认超时时间
超时:指事务的最长执行时间,也就是一个函数最长的执行时间.当时间到了,函数没有
执行完毕,Spring会回滚该函数的执行(回滚事务)

3.事务的传播行为:事务在函数之间传递,函数怎么使用事务。通过传播行为指定函数怎么使用事务

有7个传播行为:
事务的传播行为常量都是以PROPAGATION_开头,形如:PROPAGATION_XXX
PROPAGATION_REQUIRED 指定的函数必须在事务内执行。若当前存在事务,就加入到当前事务中, 若当前没事务,就创建一个新事务。Spring默认的事务传播行为
PROPAGATION_REQUIES_NEW 总是新建一个新事务,若当前存在事务,就将当前事务挂起来,直 到新事务执行完毕
PROPAGATION_SUPPORTS 指定的函数支持当前事务,但若当前没事务,也可以使用非事务方式执 行
PROPAGATION_MANDATORY
PROPAGATION_NESTED
PROPAGATION_NEVER
PROPAGATION_NOT_SUPPORTED

我们了解了Spring处理事务的一些概念以及一些常用的类,那么现在在Spring中使用事务

项目目录:

要spring使用事务的注解就需要在application-config.xml(Spring核心配置文件)添加头部信息:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
 http://www.springframework.org/schema/tx
 http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

<!--声明事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="myDataSource"/>
</bean>
<!--声明事务的注解驱动
  transaction-manager:事务管理器对象的id
-->
<tx:annotation-driven transaction-manager="transactionManager"/>

BuyGoodsServiceImpl文件:

/**使用注解来设值事务的属性(传播行为,隔离等级,超时,当哪些异常发生的时候触发回滚事务)
 * 注意:该注解必须使用在公有函数上,而且抛出的异常必需继承RuntimeException
 * */
@Transactional(propagation = Propagation.REQUIRED,
isolation = Isolation.DEFAULT,timeout = 20,
rollbackFor = {NullPointerException.class,NotEnoughException.class})
public void buyGoods(int goodsId, int nums)
        throws NullPointerException, NotEnoughException{
    /**生成销售的订单
     * */
    Sale sale=new Sale();
    sale.setGid(goodsId);
    sale.setNum(nums);
    saleDao.insertSale(sale);

    /**修改库存
     * */
    Goods goods=goodsDao.selectGoodsById(goodsId);
    if(goods==null){
        throw new NullPointerException(goodsId+"没有该商品");
    }
    if(goods.getAmount()<nums){
        throw new NotEnoughException(goodsId+"库存不足");
    }

    /**操作库存
     * */
    goods.setAmount(nums);
    goodsDao.updateGoods(goods);
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们