Spring的事务管理

141 阅读5分钟

文章目录


1. API介绍

  • PlatformTransactionManager:接口,提供事务操作的方法,包含有3个具体的操作:
  • 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版本进行持久化数据时使用
  • TransactionDefinition :事务的定义信息对象,包含如下方法:
  • String getName():获取事务名称
  • int getIsolationLevel():获取事务的隔离级别
  • int getPropagationBerhavior():获取事务的传播行为
  • int getTimeout():获取事务的超过时间
  • boolean isReadOnly():获取事务是否只读
  • TransactionStatus:接口,描述某个时间点上事务对象的状态信息,包含6个具体的操作:
  • void flush():刷新事务
  • boolean hasSavepoint():获取是否存在存储点
  • boolean isCompleted():获取事务是否完成
  • boolean isNewTransaction():获取事务是否是新的事务
  • boolean isRollbackOnly():获取事务回滚
  • void setRollbackOnly():设置事务回滚

TransactionStatus的实现源码:

	  public interface TransactionStatus extends SavepointManager, Flushable {
	  
	  	/**
	  	 * Return whether the present transaction is new (else participating
	  	 * in an existing transaction, or potentially not running in an
	  	 * actual transaction in the first place).
	  	 */
	  	boolean isNewTransaction();
	  
	  	/**
	  	 * Return whether this transaction internally carries a savepoint,
	  	 * that is, has been created as nested transaction based on a savepoint.
	  	 * <p>This method is mainly here for diagnostic purposes, alongside
	  	 * {@link #isNewTransaction()}. For programmatic handling of custom
	  	 * savepoints, use SavepointManager's operations.
	  	 * @see #isNewTransaction()
	  	 * @see #createSavepoint
	  	 * @see #rollbackToSavepoint(Object)
	  	 * @see #releaseSavepoint(Object)
	  	 */
	  	boolean hasSavepoint();
	  
	  	/**
	  	 * Set the transaction rollback-only. This instructs the transaction manager
	  	 * that the only possible outcome of the transaction may be a rollback, as
	  	 * alternative to throwing an exception which would in turn trigger a rollback.
	  	 * <p>This is mainly intended for transactions managed by
	  	 * {@link org.springframework.transaction.support.TransactionTemplate} or
	  	 * {@link org.springframework.transaction.interceptor.TransactionInterceptor},
	  	 * where the actual commit/rollback decision is made by the container.
	  	 * @see org.springframework.transaction.support.TransactionCallback#doInTransaction
	  	 * @see org.springframework.transaction.interceptor.TransactionAttribute#rollbackOn
	  	 */
	  	void setRollbackOnly();
	  
	  	/**
	  	 * Return whether the transaction has been marked as rollback-only
	  	 * (either by the application or by the transaction infrastructure).
	  	 */
	  	boolean isRollbackOnly();
	  
	  	/**
	  	 * Flush the underlying session to the datastore, if applicable:
	  	 * for example, all affected Hibernate/JPA sessions.
	  	 * <p>This is effectively just a hint and may be a no-op if the underlying
	  	 * transaction manager does not have a flush concept. A flush signal may
	  	 * get applied to the primary resource or to transaction synchronizations,
	  	 * depending on the underlying resource.
	  	 */
	  	@Override
	  	void flush();
	  
	  	/**
	  	 * Return whether this transaction is completed, that is,
	  	 * whether it has already been committed or rolled back.
	  	 * @see PlatformTransactionManager#commit
	  	 * @see PlatformTransactionManager#rollback
	  	 */
	  	boolean isCompleted();
	  
	  }

2. 事务隔离级别

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

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

3. 事务的传播行为

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

4. 超过时间

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


5. 基于XML事务控制

5.1 环境配置

导入坐标

<packaging>jar</packaging>

    <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>8.0.20</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>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
    </dependencies>

创建实体类:

public class Account implements Serializable {
    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 +
                '}';
    }
}

持久层接口和接口的实现类:

public class IAccountImpl extends JdbcDaoSupport implements IAccountDao {

    public List<Account> findAll() {
        List<Account> accounts = getJdbcTemplate().query("select * from account",
                new BeanPropertyRowMapper<Account>(Account.class));
        return accounts;
    }

    public Account findByName(String name){
        List<Account> accounts = super.getJdbcTemplate().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) {
        getJdbcTemplate().update("update account set name=?,money=? where id=?",
                account.getName(),account.getMoney(),account.getId());
    }
}

业务层接口和接口的实现类:

public interface IAccountService {

    List<Account> findAll();
    void transfer(String sourceName, String targetName, Float money);
}
public class IAccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

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

    public List<Account> findAll() {
        try {
            List<Account> accounts = accountDao.findAll();
            return accounts;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public void transfer(String sourceName, String targetName, Float money) {
       try{
           Account source = accountDao.findByName(sourceName);
           Account target = accountDao.findByName(targetName);
           source.setMoney(source.getMoney() - money);
           target.setMoney(target.getMoney() + money);

           accountDao.updateAccount(source);
           accountDao.updateAccount(target);
       } catch (Throwable t){
           throw new RuntimeException(t);
       }
    }
}

创建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">

    <bean id="accountService" class="dyliang.service.impl.IAccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <bean id="accountDao" class="dyliang.dao.impl.IAccountImpl">
        <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/sql_store?serverTimezone=GMT"></property>
        <property name="username" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>

    <aop:config>
        <aop:pointcut id="pt" expression="execution(* dyliang.service.impl.*.*(..))"></aop:pointcut>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"></aop:advisor>
    </aop:config>
</beans>

5.2 事务管理配置

  • 首先配置事务管理器:
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<property name="dataSource" ref="dataSource"></property>
</bean>
  • 配置事务的通知引用事务管理器
<tx:advice id="txAdvice" transaction-manager="transactionManager"></tx:advice>
  • 配置事务属性
<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="pt" expression="execution(* dyliang.service.impl.*.*(..))"></aop:pointcut>
    <!--建立切入点表达式和事务通知的对应关系 -->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"></aop:advisor>
</aop:config>

5.3 测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountTest {
    @Autowired
    private IAccountService as;

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

6. 基于注解的事务控制

事务控制主要在业务层,使用@Transactional配置事务管理。该注解的属性和xml中的属性含义一致。该注解可以出现在接口上,类上和方法上:

  • 出现接口上,表示该接口的所有实现类都有事务支持
  • 出现在类上,表示类中所有方法有事务支持
  • 出现在方法上,表示方法有事务支持

以上三个位置的优先级:方法 > 类 > 接口

@Service("accountService")
@Transactional(propagation= Propagation.SUPPORTS,readOnly=true)//只读型事务的配置
public class IAccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

    @Override
    public List<Account> findAll() {
        try {
            List<Account> accounts = accountDao.findAll();
            return accounts;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    @Override
    public void transfer(String sourceName, String targetName, Float money) {
       try{
           Account source = accountDao.findByName(sourceName);
           Account target = accountDao.findByName(targetName);
           source.setMoney(source.getMoney() - money);
           target.setMoney(target.getMoney() + money);

           accountDao.updateAccount(source);
           accountDao.updateAccount(target);
       } catch (Throwable t){
           throw new RuntimeException(t);
       }
    }
}

如果完全不用xml配置文件,可以在主程序类上使用@EnableTransactionManagement开启事务管理。