JAVAEE框架之Spring
八.Spring事务
8.1 转账业务
AccountServiceImple 转账业务实现类代码
/** * 转账业务 * @param sourceId * @param targetId * @param money */ public void transfer(Integer sourceId, Integer targetId,Double money) { //1.根据id,查询转出账户 Account source=accountDao.selectAccount(sourceId); //2.根据id,查询转入账户 Account target=accountDao.selectAccount(targetId); //3.转出账户减钱 source.setMoney(source.getMoney()-money); //4.转入账户加钱 target.setMoney(target.getMoney()+money); //5.更新转出账户 accountDao.updateAccount(source); //6.更新转入账户 accountDao.updateAccount(target); }
8.2测试
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); //2.获取Spring的bean AccountService accountService = (AccountService) ac.getBean("accountService"); //3.2 测试转账业务 accountService.transfer(1,2,1111.0);
结果成功!!!
但是如果在转账业务类步骤5 6之间出现各种异常情况如何呢?(断点、异常代码等)
这里模拟int result=i/0;
问题发现转出账户已经扣钱了,而转入账户则没有得到相应的金额。
8.3 线程连接工具类
package com.aaa.util; import javax.sql.DataSource; import java.sql.Connection; /** * Created by 张晨光 on 2020/7/4 11:42 * 连接的工具类,用于从数据源中获取连接,并且实现和线程的绑定 */ public class ConnUtils { private ThreadLocal<Connection> threadLocal=new ThreadLocal<Connection>(); private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } /** * 获取线程上的连接 * @return */ public Connection getThreadConnection(){ try { //1.从threadLocal获取本地链接对象 Connection conn=threadLocal.get(); //2.判断当前线程上是否有链接; if(conn==null){ //3.从数据源中获取链接对象,存入threadLocal中 conn=dataSource.getConnection(); threadLocal.set(conn); } //4.返回当前线程上的链接; return conn; } catch (Exception e) { throw new RuntimeException(e); } } /** * 解绑连接对象和线程 */ public void removeConnection(){ threadLocal.remove(); } }
8.4 事务管理类
package com.aaa.util; import java.sql.SQLException; /** * Created by 张晨光 on 2020/7/4 11:53 */ public class TransactionManager { //调用连接管理类 private ConnUtils connUtils; public void setConnUtils(ConnUtils connUtils) { this.connUtils = connUtils; } /** * 设置开始的时候自动提交事务为false,变为手动提交; */ public void beginTransaction(){ try { connUtils.getThreadConnection().setAutoCommit(false); } catch (SQLException e) { e.printStackTrace(); } } /** * 自动提交事务 */ public void commit(){ try { connUtils.getThreadConnection().commit(); } catch (SQLException e) { e.printStackTrace(); } } /** * 回滚事务 */ public void rollback(){ try { connUtils.getThreadConnection().rollback(); } catch (SQLException e) { e.printStackTrace(); } } /** * 释放连接 */ public void release(){ try { connUtils.getThreadConnection().rollback(); connUtils.removeConnection(); } catch (SQLException e) { e.printStackTrace(); } } }
8.5 Spring自带事务类
<bean id="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven transaction-manager="tx"/>
转账业务类
@Service("accountService") @Transactional public class AccountServiceImpl implements AccountService