Spring中使用动态代理实现事务控制

这是个很好的案例,能让你对事务,动态代理,Spring中IOC容器有一个更为深刻的理解。
文章目录
0.实体类
1.持久层接口
2.持久层实现类
3.业务层接口
4.业务层实现类
5.获取连接工具类
6.事务管理工具类
7.创建AccountService代理对象的工厂
8.bean.xml配置文件
9.测试类
0.实体类

//实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {
    private Integer id;
    private String name;
    private Float money;
}

1.持久层接口

//账户的持久层接口
public interface AccountDao {
    //查询所有
    List<Account> findAllAccount();
    //查询一个
    Account findAccountById(Integer id);
    //保存
    void saveAccount(Account account);
    //更新
    void updateAccount(Account account);
    //删除
    void deleteAccount(Integer id);
    //根据名称查询账户
    Account findAccountByName(String accountName);
}

2.持久层实现类

//持久层实现类
public class AccountDaoImpl implements AccountDao {
    private QueryRunner runner;
    private ConnectionUtils connectionUtils;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    public List<Account> findAllAccount() {
        try {
            return runner.query(connectionUtils.getConnection(),"select * from account",new BeanListHandler<Account>(Account.class));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Account findAccountById(Integer id) {
        try {
            return runner.query(connectionUtils.getConnection(),"select * from account where id=?",new BeanHandler<Account>(Account.class),id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void saveAccount(Account account) {
        try {
            runner.update(connectionUtils.getConnection(),"insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void updateAccount(Account account) {
        try {
            runner.update(connectionUtils.getConnection(),"update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public void deleteAccount(Integer id) {
        try {
            runner.update(connectionUtils.getConnection(),"delete from account where id=?",id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public Account findAccountByName(String accountName) {
        try {
            List<Account> accounts = runner.query(connectionUtils.getConnection(),"select * from account where name=?", new BeanListHandler<Account>(Account.class), accountName);
            if (accounts == null || accounts.size() == 0) {
                return null;
            }
            if (accounts.size() > 1) {
                throw new RuntimeException("结果集不唯一");
            }
            return accounts.get(0);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

3.业务层接口

public interface AccountService {
    //查询所有
    List<Account> findAllAccount();
    //查询一个
    Account findAccountById(Integer id);
    //保存
    void saveAccount(Account account);
    //更新
    void updateAccount(Account account);
    //删除
    void deleteAccount(Integer id);
    //转账
    void transfer(String sourceName,String targetName,Float monry);
}

4.业务层实现类

//业务层实现类,业务层调用持久层
public class AccountServiceImpl implements AccountService{

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

    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    public Account findAccountById(Integer id) {
       return accountDao.findAccountById(id);
    }
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    public void updateAccount(Account account) {
        accountDao.updateAccount(account );
    }

    public void deleteAccount(Integer id) {
        accountDao.deleteAccount(id);
    }
    public void transfer(String sourceName, String targetName, Float money) {
            //根据名称查询转出账户
            Account source = accountDao.findAccountByName(sourceName);
            //根据名称查询转入账户
            Account target = accountDao.findAccountByName(targetName);
            //转出账户减钱
            source.setMoney(source.getMoney()-money);
            //转入账户加钱
            target.setMoney(target.getMoney()+money);
            //更新装出账户
            accountDao.updateAccount(source);

         //   int i=1/0;

            //更新转入账户
            accountDao.updateAccount(target);
    }
}

5.获取连接工具类

//从数据源中获取一个链接,并且实现和线程的绑定
public class ConnectionUtils {
    private ThreadLocal<Connection> t = new ThreadLocal<Connection>();
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    public Connection getConnection(){
        try {
            //先从线程上获取
            Connection conn = t.get();
            //判断当前线程上是否有链接
            if(conn==null){
                //从数据源中获取一个链接,并且存入线程中
                conn = dataSource.getConnection();
                t.set(conn);
            }
            return conn;
        } catch (SQLException e) {
           throw new RuntimeException(e);
        }
    }
    //把连接和线程解绑
    public void removeConnection(){
        t.remove();
    }
}

6.事务管理工具类

//和事务管理相关的工具类
public class TransactionManager {
    private ConnectionUtils connectionUtils;

    public void setConnectionUtils(ConnectionUtils connectionUtils) {
        this.connectionUtils = connectionUtils;
    }

    public void beginTransaction(){
        //开启事务
        try {
            connectionUtils.getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public void commit(){
        //提交事务
        try {
            connectionUtils.getConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public void rollback(){
        //回滚事务
        try {
            connectionUtils.getConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public void release(){
        //释放链接
        try {
            connectionUtils.getConnection().close();//把conn还回连接池中
            connectionUtils.removeConnection();//将conn和线程解绑
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

7.创建AccountService代理对象的工厂

//用于创建AccountService代理对象的工厂
public class BeanFactory {
    private AccountService accountService;
    private TransactionManager transactionManager;

    public final void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    //获取AccountService代理对象
    public AccountService getAccountService(){
        AccountService proxy  = (AccountService)Proxy.newProxyInstance(
                accountService.getClass().getClassLoader(),
                accountService.getClass().getInterfaces(),
                /**
                 * 添加事务的支持
                 */
                new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        try {
                            //1.开启事务
                            transactionManager.beginTransaction();
                            //2.执行操作
                            Object result = method.invoke(accountService, args);
                            //3.提交事务
                            transactionManager.commit();
                            //4.返回结果
                            return result;
                        } catch (Exception e) {
                            //5.回滚事务
                            transactionManager.rollback();
                            throw new RuntimeException(e);
                        } finally {
                            //6.释放资源
                            transactionManager.release();
                        }
                    }
                });
        return proxy;
    }
}

8.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: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">
    <!--Spring在创建容器时,要扫描的包-->
    <context:component-scan base-package="com.hh"/>
    <!--配置代理的ServiceAccount-->
    <bean id="proxyAccountService"
          factory-bean="beanFactory"
          factory-method="getAccountService"/>

    <!--配置beanFactory-->
    <bean id="beanFactory" class="com.hh.factory.BeanFactory">
        <!--注入AccountService-->
        <property name="accountService" ref="accountService"/>
        <!--注入事务管理器-->
        <property name="transactionManager" ref="transactionManage"/>
    </bean>

    <!--配置AccountDao-->
    <bean id="accountDao" class="com.hh.dao.AccountDaoImpl">
        <property name="connectionUtils" ref="connectionUtils"/>
        <property name="runner" ref="queryRunner"/>
    </bean>

    <!--配置AccountService-->
    <bean id="accountService" class="com.hh.service.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"/>
    </bean>

    <!--配置事务管理器-->
    <bean id="transactionManage" class="com.hh.utils.TransactionManager">
        <property name="connectionUtils" ref="connectionUtils"/>
    </bean>

    <!--配置QueryRunner-->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
    </bean>

    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"/>
        <property name="user" value="root"/>
        <property name="password" value="123"/>
    </bean>

    <!--配置ConnectionUtils工具类-->
    <bean id="connectionUtils" class="com.hh.utils.ConnectionUtils">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

9.测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
    @Autowired
    @Qualifier("proxyAccountService")
    private AccountService accountService;

    @Test
    public void testTransfer(){
        accountService.transfer("aaa","bbb",100f);
    }
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值