【Spring】基础入门篇(十二) Spring中的事务控制

Spring·基础入门篇(十二) Spring中的事务控制


1. Spring 中事务控制的 API 介绍

1.1 PlatformTransactionManager

此接口是 spring 的事务管理器,它里面提供了我们常用的操作事务的方法:

  • 获取事务状态信息
    TransactionStatus getTransaction(TransactionDefinition definition)
  • 提交事务
    void commit(TransactionStatus status)
  • 回滚事务
    void rollback(TransactionStatus status)

真正管理事务的实现类:

  • org.springframework.jdbc.datasource.DataSourceTransactionManager
    使用 Spring JDBC 或 iBatis 进行持久化数据时使用

  • org.springframework.orm.hibernate5.HibernateTransactionManager
    使用Hibernate 版本进行持久化数据时使用

1.2 TransactionDefinition

它是事务的定义信息对象,里面有如下方法:

  • 获取事务对象名称
    String getName()
  • 获取事务隔离级别
    int getIsolationLevel()
  • 获取事务传播行为
    int getPropagationBehavior()
  • 获取事务超时时间
    int getTimeout()
  • 获取事务是否只读
    boolean isReadOnly();

读写型事务:增删改开启事务
只读型事务:增删改查都会开启事务

1.3 事务的隔离级别

事务隔离级别反映事务提交并发访问时的处理态度

  • ISOLATION_DEFAULT
    默认级别,归属下列某一种
  • ISOLATION_READ_UNCOMMITTED
    可以读取未提交数据
  • ISOLATION_READ_COMMITTED
    只能读取已提交数据,解决脏读问题(Oracle默认级别)
  • ISOLATION_REPEATABLE_READ
    是否读取其他事务提交修改后的数据,解决不可重复读问题(MySQL默认级别)
  • ISOLATION_SERIALIZABLE
    是否读取其他事务添加后的数据,解决幻影读问题

1.4 事务的传播行为

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

1.5 超时时间

默认值是-1,没有超时限制。如果有,以秒为单位进行设置。

1.6 是否是只读事务

建议查询时设置为只读

1.7 TransactionStatus

此接口提供描述了某个时间点上事务具体的运行状态,包含6个操作:

  • 刷新事务
  • 获取是否存在存储点
    void flush()
  • 获取事务是否完成
    boolean hasSavepoint();
  • 获取事务是否为新的事务
    boolean isCompleted()
  • 获取事务是否回滚
    boolean isNewTransaction()
  • 设置事务回滚
    boolean isRollbackOnly()

2. 基于 XML 的声明式事务控制

2.1 环境搭建

第一步:创建普通Maven工程
第二部:导入jar包
<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>commons-dbutils</groupId>
        <artifactId>commons-dbutils</artifactId>
        <version>1.4</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.8.7</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>5.0.2.RELEASE</version>
    </dependency>
</dependencies>
第三步:修改 Spring 的配置文件导入约束

此处需要导入 aop 和 tx 两个名称空间]

<?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">
</beans>
第四步:准备数据库表和实体类

创建表:

create table account(
	id int primary key auto_increment,
	name varchar(40),
	money float
)character set utf8 collate utf8_general_ci;

实体类:

**
 * @author: LzCc
 * @blog: https://blog.csdn.net/qq_41744145
 * @description: 账户的实体类
 */
public class Account implements Serializable {
    private Integer id;
    private String name;
    private Float money;
    //getter、setter...
    //toString...
}
第五步:编写 Dao 接口和实现类
/**
 * @author: LzCc
 * @blog: https://blog.csdn.net/qq_41744145
 * @description: 账户的持久层接口
 */
public interface IAccountDao {
    /**
     * 根据 id 查询账户信息
     * @param id
     * @return
     */
    Account findAccountById(Integer id);
    /**
     * 根据名称查询账户信息
     * @return
     */
    Account findAccountByName(String name);
    /**
     * 更新账户信息
     *
     * @param account
     */
    void updateAccount(Account account);
}
/**
 * @author: LzCc
 * @blog: https://blog.csdn.net/qq_41744145
 * @description: 账户的持久层实现类
 */
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
    @Override
    public Account findAccountById(Integer id) {
        List<Account> list = getJdbcTemplate().query("select * from account where id = ? ", new AccountRowMapper(), id);
        return list.isEmpty() ? null : list.get(0);
    }
    @Override
    public Account findAccountByName(String name) {
        List<Account> list = getJdbcTemplate().query("select * from account where name = ? ", new AccountRowMapper(), name);
        if (list.isEmpty()) {
            return null;
        }
        if (list.size() > 1) {
            throw new RuntimeException("结果集不唯一,不是只有一个账户对象");
        }
        return list.get(0);
    }
    @Override
    public void updateAccount(Account account) {
        getJdbcTemplate().update("update account set money = ? where id = ? ", account.getMoney(), account.getId());
    }
}
/**
 * @author: LzCc
 * @blog: https://blog.csdn.net/qq_41744145
 * @description: 账户的封装类 RowMapper 的实现类
 */
public class AccountRowMapper implements RowMapper<Account> {
    @Override
    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
        Account account = new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getFloat("money"));
        return account;
    }
}
第六步:编写业务层接口和实现类
/**
 * @author: LzCc
 * @blog: https://blog.csdn.net/qq_41744145
 * @description: 账户的业务层接口
 */
public interface IAccountDao {
    /**
     * 根据 id 查询账户信息
     * @param id
     * @return
     */
    Account findAccountById(Integer id);//查
    /**
     * 转账
     * @param sourceName 转出账户名称
     * @param targeName 转入账户名称
     * @param money 转账金额
     */
    void transfer(String sourceName,String targeName,Float money);//增删改
}

第七步:编写Spring配置文件
<!-- 配置 service -->
<bean id="accountService" class="top.lzchao.service.impl.AccountServiceImpl">
    <property name="accountDao" ref="accountDao"></property>
</bean>
<!-- 配置 dao -->
<bean id="accountDao" class="top.lzchao.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:///test"></property>
    <property name="username" value="root"></property>
    <property name="password" value="123456"></property>
</bean>

2.2 配置事务

第一步:配置事务管理器
 <!-- 配置一个事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!-- 注入 DataSource -->
    <property name="dataSource" ref="dataSource" />
</bean>
第二步:配置事务的通知引用事务管理器
<!-- 事务的配置 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager"></tx:advice>
第三步:配置事务的属性
<!--在 tx:advice 标签内部 配置事务的属性 -->
<tx:attributes>
    <!-- 指定方法名称:是业务核心方法
        read-only:是否是只读事务。默认 false,不只读。
        isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。
        propagation:指定事务的传播行为。
        timeout:指定超时时间。默认值为:-1。永不超时。
        rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。没有默认值,任何异常都回滚。
        no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚。没有默认值,任何异常都回滚。
    -->
    <tx:method name="*" read-only="false" propagation="REQUIRED"/>
    <tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
</tx:attributes>
第四步:配置 AOP 切入点表达式
<!-- 配置 aop -->
<aop:config>
    <!-- 配置切入点表达式 -->
    <aop:pointcut expression="execution(* top.lzchao.service.impl.*.*(..))" id="pt1"/>
</aop:config>
第五步:配置切入点表达式和事务通知的对应关系
<!-- 在 aop:config 标签内部:建立事务的通知和切入点表达式的关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>

3. 基于注解的配置方式

3.1 环境准备

在业务层实现类和持久层实现类使用注解交给Spring管理

3.2 注解配置

修改业务层,加上用@Transactional 注解
@Service("accountService")
@Transactional(readOnly=true,propagation=Propagation.SUPPORTS)
public class AccountServiceImpl implements IAccountService { 
	@Autowired
	private IAccountDao accountDao;
}
在配置文件中开启 spring 对注解事务的支持
<!-- 开启 spring 对注解事务的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>

3.3 纯注解方式配置

@Configuration
@EnableTransactionManagement
public class SpringTxConfiguration {
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值