Spring--声明式事务控制

    科技2022-07-12  115

    Spring–概念与模块Spring–快速入门Spring–基于IOC的CRUD操作Spring–整合JunitSpring–AOP面向切面编程Spring–基于注解的AOP配置Spring–JdbcTemplate基本使用Spring–AOP实现事务控制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+8&useUnicode=true&characterEncoding=utf-8&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+8&useUnicode=true&characterEncoding=utf-8&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>
    Processed: 0.011, SQL: 8