美文网首页
spring-8-事务

spring-8-事务

作者: blank_white | 来源:发表于2020-06-22 19:29 被阅读0次

    spring 配置文件中需要添加的配置

    <!--    声明事务管理器-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="myDataSource"/>
        </bean>
    <!--    事务注解驱动-->
        <tx:annotation-driven transaction-manager="transactionManager"/>
    
    <!--    配置文件配置事务 声明事务方法,指定事务属性-->
        <tx:advice id="advice" transaction-manager="transactionManager">
            <tx:attributes>
    <!--            方法名可使用通配符-->
                <tx:method name="bugGoods" propagation="REQUIRED" isolation="DEFAULT"
                           rollback-for="com.spyouth.ex.GoodsNotEnoughException,java.lang.NullPointerException"/>
                <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT"
                           rollback-for="java.lang.RuntimeException"/>
                <tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT"
                           rollback-for="java.lang.RuntimeException"/>
                <tx:method name="*" propagation="SUPPORTS" read-only="true" />
            </tx:attributes>
        </tx:advice>
    <!--    配置 aop 关联上面的-->
        <aop:config >
            <aop:pointcut id="servicePt" expression="execution(* *..service..*.*(..))"/>
            <aop:advisor advice-ref="advice" pointcut-ref="servicePt"/>
        </aop:config>
    

    注解方式

    public class BuyGoodsServiceImpl implements BuyGoodsService {
    
        GoodsDao goodsDao;
        SaleDao saleDao;
    
        @Transactional(propagation = Propagation.REQUIRED,
                timeout = 20,
                isolation = Isolation.DEFAULT,
                rollbackFor = {NullPointerException.class,GoodsNotEnoughException.class}
        )
        @Override
        public void bugGoods(Goods goods) throws NullPointerException,GoodsNotEnoughException{
    
            Sale sale=new Sale();
            sale.setGid(goods.getId());
            sale.setNums(goods.getNums());
            saleDao.addSale(sale);
    
    
            Goods repertoryGoods=goodsDao.selectGoodsById(goods.getId());
    
            if (repertoryGoods==null){
                //没有商品
                throw new NullPointerException("没有此商品");
            }
    
            if (repertoryGoods.getNums()<goods.getNums()){
                //库存不足
                throw new GoodsNotEnoughException("库存不足");
            }
    
            goodsDao.sellGoods(goods);
    
        }
    }
    

    相关文章

      网友评论

          本文标题:spring-8-事务

          本文链接:https://www.haomeiwen.com/subject/txbtghtx.html