spring-声明式事务管理(常用)

一、概述

模拟银行转钱的案例,
在service中执行代码逻辑中是

  1. 根据名称查询转出账户
  2. 根据名称查询转入账户
  3. 转出账户减钱
  4. 转入账户加钱
  5. 更新转出账户
  6. 更新转入账户

当上述步骤中任何一步发生错误时,应该发生事务回滚的操作。

案例代码实现

文件架构
在这里插入图片描述

需要导入的依赖

 <dependencies>
        <!--spring相关依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!--spring的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.2.RELEASE</version>
        </dependency>
        <!--单元测试类-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!--连接mysql的数据库-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!--测试类-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

实体类

public class Account implements Serializable {
    private Integer id;
    private String  name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer 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 +
                '}';
    }
}

Bean.xml配置

里面的密码和用户名url需要自己设置

<?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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--    配置容器扫描时,要扫描的包-->
    <context:component-scan base-package="com.itheima"></context:component-scan>
    <!--配置JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <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/****"></property>
        <property name="username" value="*****"></property>
        <property name="password" value="*****"></property>
    </bean>
<!--    配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
<!--    开启spring对注解事务的支持-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

持久层

接口

public interface IAccountDao {
    /**
     * 根据id查询用户
     */
    Account findAccountById(Integer accountId);
    /**
     * 根据名称
     */
    Account findAccountByName(String name);
    /**
     * 更新
     */
    void updateAccount(Account account);

}

实体类

@Repository("accountDao")
public class AccountDaoImpl  implements IAccountDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    /**
     * 根据id查询用户
     */
    public Account findAccountById(Integer accountId){
        List<Account> accounts = jdbcTemplate.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
        return accounts.isEmpty()?null:accounts.get(0);
    }
    /**
     * 根据名称
     */
    public Account findAccountByName(String name){
        List<Account> accounts = jdbcTemplate.query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),name);
        if(accounts.isEmpty()){
            return null;
        }
        if (accounts.size()>1){
            throw new RuntimeException("结果不唯一");
        }
        return accounts.get(0);
    }
    /**
     * 更新
     */
    public void updateAccount(Account account){
        jdbcTemplate.update("update account set name=?,money=? where id =?",account.getName(),account.getMoney(),account.getId());
    }
}

service层(重点)

接口

public interface IAccountService {
    Account findAccountById(Integer accountid);

    void transfer(String sourceName,String targetName,Float money);
}

实现类

@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;

    public Account findAccountById(Integer id) {
        return  accountDao.findAccountById(id);
    }
@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer....");
        //2.1根据名称查询转出账户
        Account source = accountDao.findAccountByName(sourceName);
        //2.2根据名称查询转入账户
        Account target = accountDao.findAccountByName(targetName);
        //2.3转出账户减钱
        source.setMoney(source.getMoney()-money);
        //2.4转入账户加钱
        target.setMoney(target.getMoney()+money);
        int i=1/0;
        //2.5更新转出账户
        accountDao.updateAccount(source);
        //2.6更新转入账户
        accountDao.updateAccount(target);
    }
}

知识点

这里用到了管理事务的@Transactional的注解,他可以帮助我们管理事务。
@Transactional注解参数详解

事物传播行为介绍:

  1. @Transactional(propagation=Propagation.REQUIRED) :
    如果有事务, 那么加入事务, 没有的话新建一个(默认情况下)
  2. @Transactional(propagation=Propagation.NOT_SUPPORTED) :
    容器不为这个方法开启事务
  3. @Transactional(propagation=Propagation.REQUIRES_NEW) :
    不管是否存在事务,都创建一个新的事务,原来的挂起,新的执行完毕,继续执行老的事务
  4. @Transactional(propagation=Propagation.MANDATORY) :
    必须在一个已有的事务中执行,否则抛出异常
  5. @Transactional(propagation=Propagation.NEVER) :
    必须在一个没有的事务中执行,否则抛出异常(与Propagation.MANDATORY相反)
  6. @Transactional(propagation=Propagation.SUPPORTS) :
    如果其他bean调用这个方法,在其他bean中声明事务,那就用事务.如果其他bean没有声明事务,那就不用事务.

事物超时设置:  
 @Transactional(timeout=30) //默认是30秒

事务隔离级别:

  1. @Transactional(isolation = Isolation.READ_UNCOMMITTED):
    读取未提交数据(会出现脏读, 不可重复读) 基本不使用

  2. @Transactional(isolation = Isolation.READ_COMMITTED):
    读取已提交数据(会出现不可重复读和幻读)

  3. @Transactional(isolation = Isolation.REPEATABLE_READ):
    可重复读(会出现幻读)

  4. @Transactional(isolation = Isolation.SERIALIZABLE):
    串行化
      
    MYSQL: 默认为REPEATABLE_READ级别   
    SQLSERVER: 默认为READ_COMMITTED
    脏读 : 一个事务读取到另一事务未提交的更新数据
    不可重复读 : 在同一事务中, 多次读取同一数据返回的结果有所不同, 换句话说, 后续读取可以读到另一事务已提交的更新数据. 相反, "可重复读"在同一事务中多次 读取数据时, 能够保证所读数据一样, 也就是后续读取不能读到另一事务已提交的更新数据
    幻读 : 一个事务读到另一个事务已提交的insert数据

在这里插入图片描述在这里插入图片描述
注意事项
1、@Transactional 只能被应用到public方法上, 对于其它非public的方法,如果标记了@Transactional也不会报错,但方法没有事务功能.
2、用 spring 事务管理器,由spring来负责数据库的打开,提交,回滚.

  • 默认遇到运行期例外(throw new RuntimeException(“注释”);)会回滚,即遇到不受检查(unchecked)的例外时回滚;
  • 遇到需要捕获的例外(throw new Exception(“注释”);)不会回滚,即遇到受检查的例外(就是非运行时抛出的异常,编译器会检查到的异常叫受检查例外或说受检查异常)时,需我们指定方式来让事务回滚要想所有异常都回滚,要加上
    @Transactional( rollbackFor={Exception.class,其它异常})
    .如果让unchecked例外不回滚:
    @Transactional(notRollbackFor=RunTimeException.class)

3、@Transactional 注解应该只被应用到 public 可见度的方法上。 如果你在 protected、private 、package-visible 的方法上使用 @Transactional 注解,不会报错, 但是该方法将不会展示已配置的事务设置。

4、@Transactional 注解可以**被应用于接口定义接口方法类定义类的 public 方法**上。注意:只有@Transactional 注解的出现不足于开启事务行为,它仅仅 是一种元数据,能够被可以识别 @Transactional 注解和上述的配置适当的具有事务行为的beans所使用。

5、Spring团队的建议是你在具体的类(或类的方法)上使用 @Transactional 注解,而不要使用在类所要实现的任何接口上。你当然可以在接口上使用 @Transactional 注解,但是这将只能当你设置了基于接口的代理时它才生效。因为注解是不能继承的,这就意味着如果你正在使用基于类的代理时,那么事务的设置将不能被基于类的代理所识别,而且对象也将不会被事务代理所包装(将被确认为严重的)。还是接受Spring团队的建议并且在具体的类上使用 @Transactional 注解

测试

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
    @Autowired
    private IAccountService as;
    @Test
    public void testTransfer(){
        as.transfer("bbb","aaa",20f);
    }
}

结果
因为在service的实体类中,设置了异常 int i=1/0; 数据库没有发生变化
在这里插入图片描述
在这里插入图片描述

测试没有异常时的结果:
在这里插入图片描述
在这里插入图片描述
到此使用xml和注解相互配合的声明式事务案例,完成。
有问题或哪里写的不对的地方请大佬们多多指教

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值