Spring入门知识 ———— 使用注解的方式实现事务

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38111957/article/details/83958013

一、引言

上一个章节当中,我们为学习事务准备了一个生活案例,可以回顾一下,点这里

上个案例,成功了购买了商品,并且账户金额也减少了,这是没任何问题的,现在我们对这个方法进行一个修改。

在我们修改商品库存的时候,抛出一个异常,导致的结果就是,账户的钱减少了,但是商品库存没减少

那么,这就是个问题了,这两个事件必须是要么全部完成,要么全部不完成,这个时候就的使用事务了。

    public int updateStory(int id) {
        //加上这么一个操作,只是为了抛出一个异常
        System.out.println(100/0);
        String sql = "update tb_commodity set stock = stock - 1 where id = ?";
        return jdbcTemplate.update(sql, id);
    }

二、配置事务

首先,在使用事物之前,我们先的来配置事务管理。由于我们先来学习注解的方式,也需要开启事务支持注解。

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">


    <!--引入外部属性文件-->
    <context:property-placeholder location="db.properties"></context:property-placeholder>

    <!--扫描注解的包-->
    <context:component-scan base-package="com.spring.five"></context:component-scan>

    <!--配置阿里巴巴连接池-->
    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="driverClassName" value="${jdbc.driver}"></property>
    </bean>

    <!--配置JdbcTemp laTemplate-->
    <bean class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="druidDataSource"></property>
    </bean>

    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="druidDataSource"></property>
    </bean>

    <!--启用事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

三、实现事务

在我们Service层的方法,加上@Transactional注解,标识这个方法会被事务管理,这个时候,方法中对数据库操作的步骤,如果有某一个方法出现问题,则整个事务进行回滚操作。

不信,你试试吧,嘿嘿嘿~~~~

    /**
     * 购物操作
     * @param userid 用户编码,减去该用户账户相对应的购买商品金额
     * @param cid 商品编码,查询该商品的价格,以及购买成功是库存-1
     * @return
     */
    @Transactional
    public int goShopping(int userid,int cid){

        //查询商品
        Commodity commodity =  dataBaseDao.selectCommodityByid(cid);

        //减去用户账户金额
        dataBaseDao.updateAccount(userid,commodity.getPrice());

        //减去该商品的库存
        dataBaseDao.updateStory(cid);

        return 1;
    }

猜你喜欢

转载自blog.csdn.net/weixin_38111957/article/details/83958013