Spring框架学习 day04 基于 XML 的声明式事务控制(配置方式)案例

基于 XML 的声明式事务控制(配置方式)案例


记录对于转账进行事务管理的基于 XML 的声明式事务控制(配置方式)案例

src下创建的包、类:
在这里插入图片描述

pom.xml 引入jar包

<dependencies>
        <!-- spring核心配置 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!-- jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!-- spring事务 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.3.RELEASE</version>
        </dependency>
        <!-- spring测试环境 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!-- 切入点表达式解析依赖 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>
        <!-- Mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

domain 层

Account 实体类:

public class Account {

    private int id;
    private String name;
    private float money;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getMoney() {
        return money;
    }

    public void setMoney(float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

dao 层

AccountDao:

public interface AccountDao {

    /**
     * 根据name查询账户
     * @param name
     * @return
     */
    Account findAccountByName(String name);

    /**
     * 更新账户方法
     * @param account
     */
    void updateAccount(Account account);
}

AccountDaoImpl :

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

    /**
     * 根据name查询账户
     * @param name
     * @return
     */
    public Account findAccountByName(String name) {
        List<Account> accounts = super.getJdbcTemplate().query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), name);
        if (accounts == null) {
            return null;
        }
        if (accounts.size() > 1) {
            throw new RuntimeException("数据不唯一");
        }
        return accounts.get(0);
    }

    /**
     * 更新账户方法
     * @param account
     */
    public void updateAccount(Account account) {
        super.getJdbcTemplate().update("update account set money = ? where id = ? ",account.getMoney(),account.getId());
    }
}

Service 层

AccountService:

/**
 * 账户的业务层接口
 */
public interface AccountService {

    /**
     * 转账方法
     * @param resourceName 转账账户姓名
     * @param transName    收款账户姓名
     * @param money     金额
     */
    void transfer(String resourceName, String transName , float money);
}

AccountServiceImpl :

/**
 * 账户的业务层实现类
 */
public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    /**
     * 转账方法
     * @param resourceName 转账账户姓名
     * @param transName    收款账户姓名
     * @param money     金额
     */
    public void transfer(String resourceName, String transName, float money) {

        //查询转账账户
        Account resource = accountDao.findAccountByName(resourceName);

        //查询收款用户
        Account trans = accountDao.findAccountByName(transName);

        //设置金额
        resource.setMoney(resource.getMoney() - money);
        trans.setMoney(trans.getMoney() + money);

        //更新账户
        accountDao.updateAccount(resource);

//        int i = 7/0;

        accountDao.updateAccount(trans);
    }
}

配置 bean.xml

bean.xml:

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--配置AccountService-->
    <bean id="accountService" class="cn.itcast.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!-- 配置dao -->
    <bean id="accountDao" class="cn.itcast.dao.impl.AccountDaoImpl">
        <!-- 注入dataSource -->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/spring01"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

    <!-- Spring中基于XML的声明式事务配置步骤
        1.配置事务管理器
        2.配置事务的通知
            此时我们需要导入事务的约束 tx名称空间和约束,同时也需要aop的
            使用tx:advice标签配置事务通知
                属性:
                    id:给事务通知起一个唯一表亲啊
                    transaction-manager:给事务通知提供一个事务管理器引用
       3.配置AOP的通用切入点表达式
       4.建立事务通知和切入点表达式的对应关系
       5.配置事务的属性
            是在四和五的通知tx:advice标签内部
    -->
    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 配置事务的属性
                isolation:用于指定事务的隔离级别。默认是DEFAULT,表示使用数据库的默认隔离级别
                propagation:用于指定事务的传播行为,默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS
                read-only:用于指定事务是否只读。只有查询方法才能设置为true。默认值为false,表示读写
                timeout:用于指定事务的超时时间,默认值是-1,表示永不超时,如果指定了数值,以秒为单位
                rollback-for:用于指定一个异常,当产生改异常时,事务回滚。产生其他异常时,事务不回滚,没有默认值。表示任何异常都回滚
                no-rollback-for:用于指定一个异常,当产生该异常时,事务不会回滚,产生其他异常时事务回滚,没有默认值,表示任何异常都回滚
        -->
        <!-- 配置属性 -->
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
        </tx:attributes>
    </tx:advice>

    <!-- 配置aop -->
    <aop:config>
        <!-- 配置切入点的表达式 -->
        <aop:pointcut id="pt1" expression="execution(* cn.itcast.service.impl.*.*(..))"></aop:pointcut>
        <!-- 建立切入点和事务通知的对应关系 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>

</beans>
发布了17 篇原创文章 · 获赞 0 · 访问量 143

猜你喜欢

转载自blog.csdn.net/weixin_46539792/article/details/105373040