Spring--声明式事务控制

spring中关于事务的API

在spring中提供了一些关于事务控制的接口,主要包括一下三个:

  • PlatformTransactionManager: 事务管理器–提供事务操作的方法
    其中提供了三个方法:
    提交事务:void commit(TransactionStatus status);
    回滚事务:void rollback(TransactionStatus status);
    获取事务状态信息:TransactionStatus getTransaction(TransactionDefinition definition);

  • TransactionDefinition: 事务的定义信息对象
    其中有以下五个方法:
    获取事务对象名称:String getName();
    获取事务的隔离级:int getIsolationLevel();
    获取事务的传播行为:int getPropagationBehavior();
    获取事务的超时时间:int getTimeout();
    获取事务是否只读:boolean isReadOnly();

  • TransactionStatus: 事务具体的运行状态
    包括六个具体操作:
    刷新事务:void flush();
    获取是否存在存储点:boolean hasSavepoint();
    获取事务是否完成:boolean isCompleted();
    获取事务是否为新的事务:boolean isNewTransaction();
    获取事务是否回滚:boolean isRollbackOnly();
    设置事务回滚:void setRollbackOnly();

有关事务的相关信息:

事务的隔离级别:
(1)DEFAULT 默认的隔离级别
(2)READ_UNCOMMITED 可以读取未提交的改变了的数据。
(3)READ_COMMITTED 只能读取已提交的数据,解决了脏读问题(Oracle的默认级别)
(4)REPEATABLE_READ 是否读取其他事务提交修改后的数据,解决不可重复读问题(MySQL默认级别)
(5)SERIALIZABLE 是否读取其他事务提交添加后的数据,解决幻读问题

事务的传播行为:
(1)REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
(2)SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
(3)MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
(4)REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
(5)NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
(6)NEVER:以非事务方式运行,如果当前存在事务,抛出异常
(7)NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作。

超时时间:
默认值是-1,没有超时限制。如果有,以秒为单位进行设置。
是否是只读事务:
只读一般对应查询操作,读写对应增删改操作,建议查询时设置为只读

基于注解的事务控制

基于注解的声明式事务控制,我们需要进行一下操作

  • 1、配置事务管理器
  • 2、开启spring对注解事务的支持
  • 3、在需要事务支持的地方使用@Transactional注解

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

    <!--配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.ly"></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.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/spring?serverTimezone=GMT%2B8&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false"></property>
        <property name="username" value="root"></property>
        <property name="password" value="520992"></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>

要想进行事务控制,我们应该在在业务层去实现,接下来配置账户的业务层

/**
 * @Author: Ly
 * @Date: 2020-08-05 18:57
 * 账户的业务层接口
 */
public interface IAccountService {
    /**
     * 转账
     * @param sourceName  转成账户名称
     * @param targetName  转入账户名称
     * @param money       转账金额
     */
    void transfer(String sourceName, String targetName, Float money);
}

/**
 * @Author: Ly
 * @Date: 2020-08-05 19:00
 * 账户的业务层实现类
 *
 */
@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)//只读型事务配置
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;


    //读写型事务配置
    @Transactional(propagation = Propagation.SUPPORTS,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);
        //int i=1/0;
        //2.4.转给账户加钱
        target.setMoney(target.getMoney()+money);
        //2.5.更新装出账户
        accountDao.updateAccount(source);
        //2.6.更新转入账户
        accountDao.updateAccount(target);
    }
}

配置账户的持久层:

/**
 * @Author: Ly
 * @Date: 2020-08-05 12:17
 */
public interface IAccountDao {

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

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


/**
 * @Author: Ly
 * @Date: 2020-08-05 12:20
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public Account findAccountByName(String accountName) {
        List<Account> accounts =jdbcTemplate.query("select * from account where name= ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
        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());
    }
}

测试代码:

/**
 * @Author: Ly
 * @Date: 2020-07-27 17:17
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    private IAccountService as;

    @Test
    public void testTransfer(){
        as.transfer("aaa","bbb",100f);
    }

}

基于XML的声明式事务控制我们只需要修改bean.xml配置文件即可:
配置步骤:

  • 1、配置事务管理器
  • 2、配置事务的通知:导入事务的约束,使用tx:advice标签配置事务通知
    属性:id:给事务通知起一个唯一标识
    transaction-manager:给事务通知提供一个事务管理器引用
  • 3、配置AOP中的通用切入点表达式
  • 4、建立事务通知和切入点表达式的对应关系
  • 5、在tx:advice标签的内部配置事务的属性

配置事务的属性:
isolation:用于指定事务的隔离级别。默认执行default:表示使用数据库的默认隔离级别
propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。
read-only:用于指定事务是否只读只有查询方法才能设置为true。默认值为false,表示读写
timeout:用于指定事务的超时时间。默认值为-1,表示永不超时。如果指定了数值,以秒为单位
rollback-for:用于指定一个异常,但产生该异常时,事务回滚。产生其他异常时,事务不回滚。没有默认值,表示任意异常都回滚
no-rollback-for:用于指定一个异常,但产生该异常时,事务不回滚。产生其他异常时,事务回滚。没有默认值,表示任意异常都回滚

<?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/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/cache
       http://www.springframework.org/schema/cache/spring-cache.xsd">

    <!--配置业务层-->
    <bean id="accountService" class="com.ly.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!--配置账户的持久层-->
    <bean id="accountDao" class="com.ly.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>

    <!--配置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.cj.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/spring?serverTimezone=GMT%2B8&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
  
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置事务的通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
       
        <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(* com.ly.service.impl.*.*(..))"/>
        <!--建立切入点表达式和事务通知的对应关系-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>
</beans>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring框架提供了两种事务管理方式:编程式事务管理和声明式事务管理。 1. 编程式事务管理: 编程式事务管理是通过编写代码来管理事务的提交和回滚。在这种方式下,开发人员需要手动编写事务的开始、提交和回滚的代码。Spring提供了`TransactionTemplate`和`TransactionDefinition`等类来简化编程式事务管理的操作。通过使用`TransactionTemplate`,可以在需要进行事务处理的代码块中对事务进行管理。 2. 声明式事务管理: 声明式事务管理是通过配置的方式来管理事务的提交和回滚,而不需要手动编写事务管理的代码。在这种方式下,开发人员只需要在需要进行事务处理的方法上使用注解或者XML配置文件来声明事务的属性,Spring框架就会根据配置自动实现事务管理。常见的注解方式是使用`@Transactional`注解。 两种事务管理方式各有优劣,编程式事务管理灵活性较高,适用于复杂的事务场景,但需要开发人员手动编写大量的事务管理代码;声明式事务管理简化了开发工作,通过配置即可实现事务管理,但对于一些复杂的业务场景可能不够灵活。 总的来说,对于大部分应用场景而言,推荐使用声明式事务管理,可以减少重复代码的编写,提高开发效率。而在一些特殊的业务场景下,如需要动态控制事务的提交和回滚,或者需要手动处理一些特殊情况,可以考虑使用编程式事务管理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙源lll

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值