Spring之初识事务管理
一、编写转账功能代码
1.编写Service接口与实现
//接口
public interface IAccountService {
/**
* 转账
* @param sourceName 转出账户名称
* @param targetName 转入账户名称
* @param money 转账金额
*/
void transfer(String sourceName,String targetName,BigDecimal money);
//接口实现
public class AccountServiceImpl implements IAccountService{
@Autowired
private IAccountDao accountDao;
@Override
public void transfer(String sourceName, String targetName, BigDecimal money) {
//1根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//2根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//3转出账户减钱
source.setMoney(source.getMoney().subtract(money));
//4转入账户加钱
target.setMoney(target.getMoney().add(money));
//5更新转出账户
accountDao.updateAccount(source);
// int i=1/0;
//6更新转入账户
accountDao.updateAccount(target);
}
}
2.编写Dao接口与实现
public interface IAccountDao {
/**
* 修改账户信息
* @param account
*/
void updateAccount(Account account);
/**
* 查询账户
* @param accountName
* @return
*/
Account findAccountByName(String accountName);
}
@Repository
public class AccountDaoImpl implements IAccountDao {
@Autowired
private QueryRunner runner;
@Override
public void updateAccount(Account account) {
try{
runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Account findAccountByName(String accountName) {
try{
return runner.query("select * from account where name = ? ",new BeanHandler<Account>(Account.class),accountName);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
3.配置spring.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: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/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置扫描包-->
<context:component-scan base-package="cn.ybzy"></context:component-scan>
<!--配置QueryRunner-->
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<!--注入数据源-->
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--配置数据库的连接信息-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/demo"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
/beans>
4.执行测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountTest {
@Autowired
private IAccountService accountService;
@Test
public void testTransfer(){
accountService.transfer("A","B", BigDecimal.valueOf(100));
}
}
1.测试一
每个账户初始金额500,A向B转账100,执行成功.
2.测试二
在Service层接口实现中,制造一个 int i=1/0; 异常,再次执行A向B转账,由于 int i=1/0;异常,更新转入账户代码未执行,此时数据库中数据出现异常,不满足事务的一致性。
二、添加统一事务管理
以上转账案例中,事务是作用在Dao层,每次与数据库交互都获取了一个新的连接,每个连接都有独立的事务,在int i=1/0;之前代码都成功执行,之后代码由于异常未执行,造成了事务的不一致。
为了解决这个问题,需要将事务作用到Service层,使用ThreadLocal对象把Connection对象和当前线程绑定,从而使一个线程中只能有一个事务对象。
1.创建连接工具类
用于从数据源中获取一个连接,并且实现和线程的绑定
@Component
public class ConnectionUtils {
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
@Autowired
private DataSource dataSource;
/**
* 获取与当前线程绑定的连接
* @return
*/
public Connection getThreadConnection() {
try{
//1.先从当前线程ThreadLocal上获取
Connection conn = tl.get();
//2.判断当前线程上是否有连接
if (conn == null) {
//3.没有则从数据源中获取一个连接,并与当前线程ThreadLocal绑定
conn = dataSource.getConnection();
tl.set(conn);
}
//4.有则返回当前线程上的连接
return conn;
}catch (Exception e){
throw new RuntimeException(e);
}
}
/**
* 把连接和线程解绑
*/
public void removeConnection(){
tl.remove();
}
}
若不使用注解方式将对象交由Spring管理,需要在Spring.xml中进行如下配置
<bean id="connectionUtils" class="cn.ybzy.utils.ConnectionUtils">
<!-- 注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
2.创建事务管理工具类
@Component
public class TransactionManager {
@Autowired
private ConnectionUtils connectionUtils;
/**
* 开启事务
*/
public void beginTransaction(){
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 回滚事务
*/
public void rollback(){
try {
connectionUtils.getThreadConnection().rollback();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 关闭连接
*/
public void close(){
try {
connectionUtils.getThreadConnection().close();//还回连接池中
connectionUtils.removeConnection();
}catch (Exception e){
e.printStackTrace();
}
}
}
若不使用注解方式将对象交由Spring管理,需要在Spring.xml中进行如下配置
<bean id="txManager" class="cn.ybzy.utils.TransactionManager">
<!-- 注入ConnectionUtils -->
<property name="connectionUtils" ref="connectionUtils"> </property>
</bean>
3.改造Service层实现类
public class AccountServiceImpl implements IAccountService{
@Autowired
private IAccountDao accountDao;
@Autowired
private TransactionManager txManager;
@Override
public void updateAccount(Account account) {
try {
//1.开启事务
txManager.beginTransaction();
//2.执行操作
accountDao.updateAccount(account);
//3.提交事务
txManager.commit();
}catch (Exception e){
//4.回滚操作
txManager.rollback();
}finally {
//5.释放连接
txManager.close();
}
}
@Override
public void transfer(String sourceName, String targetName, BigDecimal money) {
try {
//开启事务
txManager.beginTransaction();
//1根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//2根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//3转出账户减钱
source.setMoney(source.getMoney().subtract(money));
//4转入账户加钱
target.setMoney(target.getMoney().add(money));
//5更新转出账户
accountDao.updateAccount(source);
int i=1/0;
//6更新转入账户
accountDao.updateAccount(target);
//提交事务
txManager.commit();
}catch (Exception e){
//回滚操作
txManager.rollback();
e.printStackTrace();
}finally {
//释放连接
txManager.close();
}
}
}
若不使用注解方式将对象交由Spring管理,需要在Spring.xml中进行如下配置
<bean id="accountService" class="cn.ybzy.service.impl.AccountServiceImpl">
<!-- 注入dao -->
<property name="accountDao" ref="accountDao"></property>
</bean>
4.改造Dao层实现类
@Repository
public class AccountDaoImpl implements IAccountDao {
@Autowired
private QueryRunner runner;
@Autowired
private ConnectionUtils connectionUtils;
@Override
public void updateAccount(Account account) {
try{
runner.update(connectionUtils.getThreadConnection(),"update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Account findAccountByName(String accountName) {
try{
return runner.query(connectionUtils.getThreadConnection(),"select * from account where name = ? ",new BeanHandler<Account>(Account.class),accountName);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
若不使用注解方式将对象交由Spring管理,需要在Spring.xml中进行如下配置
<bean id="accountDao" class="cn.ybzy.dao.impl.AccountDaoImpl">
<!-- 注入QueryRunner -->
<property name="runner" ref="runner"></property>
<!-- 注入ConnectionUtils -->
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
5.执行测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountTest {
@Autowired
private IAccountService accountService;
@Test
public void testTransfer(){
accountService.transfer("A","B", BigDecimal.valueOf(100));
}
}
各账号初始金额500,执行A向B转账100,制造int i=1/0;异常,执行测试,发现事务得到统一管理。
三、使用动态代理实现事务控制
在上述改造Service层实现类中,每个方法都有重复性的事务管理方法,使用动态代理简化开发,提升效率,统一维护。
1.创建动态代理工厂类
@Component
public class BeanFactory {
@Autowired
private IAccountService accountService;
@Autowired
private TransactionManager txManager;
/**
* 获取Service代理对象
* @return
*/
@Bean("proxyAcountService")
public IAccountService getAccountService() {
return (IAccountService)Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
accountService.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnValue = null;
try {
//1.开启事务
txManager.beginTransaction();
//2.执行操作
returnValue= method.invoke(accountService, args);
//3.提交事务
txManager.commit();
//4.返回结果
return returnValue;
} catch (Exception e) {
//5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
} finally {
//6.释放连接
txManager.close();
}
}
});
}
}
若不使用注解方式将对象交由Spring管理,需要在Spring.xml中进行如下配置
<!--配置动态代理的service-->
<bean id="proxyAcountService" factory-bean="beanFactory" factory-method="getAccountService"></bean>
<!--配置beanfactory-->
<bean id="beanFactory" class="cn.ybzy.factory.BeanFactory">
<!-- 注入service -->
<property name="accountService" ref="accountService"></property>
<!-- 注入事务管理器 -->
<property name="txManager" ref="txManager"></property>
</bean>
2.执行测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountTest {
@Autowired
@Qualifier("proxyAcountService")
private IAccountService accountService;
@Test
public void testTransfer(){
accountService.transfer("A","B", BigDecimal.valueOf(100));
}
}
各账号初始金额500,执行A向B转账100,制造int i=1/0;异常,执行测试,发现事务得到统一管理。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/137133.html