Spring系列第9篇:Spring中的编程式事物

前言

编程式事物代码耦合度过高,实际开发中应使用声明式事物

一、TransactionTemplate

1.编程式事物控制实现步骤

1.配置事物管理器,并且注入spring内置数据源DriverManagerDataSource
2.配置事物模板对象,并注入事物管理器
3.事物控制在业务层用TransactionTemplate.execute(并且创建TransactionCallback的匿名内部类)

2.案例

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
      https://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/tx
      https://www.springframework.org/schema/tx/spring-tx.xsd
      http://www.springframework.org/schema/aop
      https://www.springframework.org/schema/aop/spring-aop.xsd
      http://www.springframework.org/schema/context
      https://www.springframework.org/schema/context/spring-context.xsd">
  <context:component-scan base-package="com.ming"></context:component-scan>
  <!--配置账户的持久层-->
  <bean id="accountDao" class="com.ming.dao.dbcteplate.impl.AccountDaoImpl">
      <!-- <property name="jdbcTemplate" ref="jdbcTemplate"></property>-->
      <property name="dataSource" ref="dataSource"></property>
  </bean>
  <!--配置账户的业务层-->
  <bean id="accountService" class="com.ming.service.jdbctemplate.impl.AccountServiceImpl">
      <property name="accountDao" ref="accountDao"></property>
      <property name="transactionTemplate" ref="transcationTemplate"></property>
  </bean>
<!--配置spring内置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
	<property name="url" value="jdbc:mysql://localhost:3307/test"></property>
	<property name="username" value="liming"></property>
	<property name="password" value="liming"></property>
</bean>
<!--配置事物管理器-->
<bean id="transcationManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置事物模板对象-->
<bean id="transcationTemplate" class="org.springframework.transaction.support.TransactionTemplate">
	<property name="transactionManager" ref="transcationManager"></property>
</bean>
</beans>

业务层代码

package com.ming.service.jdbctemplate;

import com.ming.model.Account;

public interface IAccountService {
    /**
     * 根据id查询账户
     * @param accountId
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 根据账户名称查询账户
     * @param accountName
     * @return
     */
    Account findAccountByName(String accountName);

    /**
     * 转账
     * @param sourceName 转出账户
     * @param targetName 转入账户
     * @param money 金额
     */
    void transfer(String sourceName,String targetName,Float money);
}

package com.ming.service.jdbctemplate.impl;

import com.ming.dao.dbcteplate.IAccountDao;
import com.ming.model.Account;
import com.ming.service.jdbctemplate.IAccountService;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;


public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

    private TransactionTemplate transactionTemplate;

    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

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

    @Override
    public Account findAccountById(Integer accountId) {
        return transactionTemplate.execute(new TransactionCallback<Account>() {
            @Override
            public Account doInTransaction(TransactionStatus status) {
                return accountDao.findAccountById(accountId);
            }
        });

    }

    @Override
    public Account findAccountByName(String accountName) {
        return accountDao.findAccountByName(accountName);
    }

    //需要的是读写型事物配置
    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        transactionTemplate.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {
                //1.根据名称查询转出账户
                Account sourceAccount = accountDao.findAccountByName(sourceName);
                //2.根据名称查询转入账户
                Account targetAccount = accountDao.findAccountByName(targetName);
                //3.转出账户减钱
                sourceAccount.setMoney(sourceAccount.getMoney() - money);
                //4.转入账户加钱
                targetAccount.setMoney(targetAccount.getMoney() + money);
                //5.更新账户
                accountDao.updateAccount(sourceAccount);
                int a = 2 / 0;
                accountDao.updateAccount(targetAccount);
                return null;
            }
        });
    }
}

持久层

package com.ming.dao.dbcteplate;

import com.ming.model.Account;

/**
 * 基于jdbcTemplate的持久层
 */
public interface IAccountDao {

    /**
     * 根据id查询账户
     * @param accountId
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 根据账户名称查询账户
     * @param accountName
     * @return
     */
    Account findAccountByName(String accountName);
    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);


}

package com.ming.dao.dbcteplate.impl;

import com.ming.dao.dbcteplate.IAccountDao;
import com.ming.model.Account;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.util.List;

/**
 * 基于jdbcTemplate的账户持久层实现类
 */

public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {

    @Override
    public Account findAccountById(Integer accountId) {

        List<Account> accountList = super.getJdbcTemplate().query("select * from account where id = ? ", new BeanPropertyRowMapper<Account>(Account.class), accountId);
        return accountList.isEmpty() ? null : accountList.get(0);
    }

    @Override
    public Account findAccountByName(String accountName) {
        List<Account> accountList = super.getJdbcTemplate().query("select * from account where name = ? ",
                new BeanPropertyRowMapper<Account>(Account.class), accountName);
        if (accountList.isEmpty()) {
            return null;
        }
        if (accountList.size() > 1) {
            throw new RuntimeException("结果集不为1");
        }
        return accountList.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        super.getJdbcTemplate().update("update account set name = ? , money = ? where id = ? ", account.getName(), account.getMoney(), account.getId());
    }
}

二、声明式事物学习中

1.欢迎各位大佬指导,谢谢

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值