转账案例演示事务问题

转账案例演示事务问题

0. 导入依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>

<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
</dependency>

1. 编写ConnectionUtils

连接的工具类,用于从数据源中获取一个连接,并且实现和线程的绑定

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class ConnectionUtils {
private ThreadLocal<Connection> tl = new ThreadLocal<>();
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.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 (SQLException e) {
throw new RuntimeException(e);
}
}
/**
* 把连接和线程解绑
*/
public void removeConnection(){
tl.remove();
}
}

2. 编写事务管理工具类

和事务管理相关的工具类,它包含了,开始事务,提交事务,回滚事务,和释放连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
public class TransactionManager {
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
/**
* 开启事务
*/
public void beginTransaction(){
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 回滚事务
*/
public void rollback(){
try {
connectionUtils.getThreadConnection().rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 释放连接
*/
public void release(){
try {
connectionUtils.getThreadConnection().close();//还回连接池中
connectionUtils.removeConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

3. 持久层和业务层的方法(部分)

持久层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public class AccountDaoImpl implements IAccountDao {
private QueryRunner runner;
private ConnectionUtils connectionUtils;

public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
public void setRunner(QueryRunner runner) {
this.runner = runner;
}
/*....*/

@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 (SQLException e) {
e.printStackTrace();
}
}

@Override
public Account findAccountByName(String accountName) {
try {
List<Account> accounts = runner.query(connectionUtils.getThreadConnection(), "select * from account where name = ?", new BeanListHandler<>((Account.class)), accountName);
if (accounts == null || accounts.size() == 0) {
return null;
}
if (accounts.size() > 1) {
throw new RuntimeException("结果集不唯一,数据有问题");
}
return accounts.get(0);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}

业务层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class AccountServiceImpl implements IAccountService {
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
/*....*/
@Override
public void transfer(String sourceName, String targetName, float money) {
// 2.执行操作
// 2.1根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
// 2.2根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
// 2.3转出账户减钱
source.setMoney(source.getMoney() - money);
// 2.4转入账户加钱
target.setMoney(target.getMoney() + money);
// 2.5更新转出账户
accountDao.updateAccount(source);
// int i = 1 / 0;
// 2.6更新转入账户
accountDao.updateAccount(target);
}
}

4. 修改spring的配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!--配置Service -->
<bean id="accountService" class="com.xzxj.service.Impl.AccountServiceImpl">
<!--注入dao-->
<property name="accountDao" ref="accountDao"/>
</bean>

<!--配置Dao-->
<bean id="accountDao" class="com.xzxj.dao.impl.AccountDaoImpl">
<!--注入QueryRunner-->
<property name="runner" ref="runner"/>
<!--注入ConnectionUtils-->
<property name="connectionUtils" ref="connectionUtils"/>
</bean>

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

<!--配置数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!--链接数据库的必备信息-->
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jdbcdb?useUnicode=true&amp;characterEncoding=utf8"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>

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

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

<!--配置AOP-->
<aop:config>
<!--配置通用切入点表达式-->
<aop:pointcut id="pt1" expression="execution(* com.xzxj.service.Impl.*.*(..))"/>
<aop:aspect id="txAdvice" ref="txManager">
<!--配置前置通知:开启事务-->
<aop:before method="beginTransaction" pointcut-ref="pt1"/>
<!--配置后置通知:提交事务-->
<aop:after-returning method="commit" pointcut-ref="pt1"/>
<!--配置异常通知:回滚事务-->
<aop:after-throwing method="rollback" pointcut-ref="pt1"/>
<!--配置最终通知:释放连接-->
<aop:after method="release" pointcut-ref="pt1"/>
</aop:aspect>
</aop:config>

5. 测试方法

1
2
3
4
5
6
7
8
9
10
11
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceImplTest {
@Autowired
IAccountService service;
@Test
public void testTransfer() {
service.transfer("aaa", "bbb", 100);
}

}

运行结果:aaa减钱,bbb加钱。

如果把业务层中的 int i = 1 / 0; 注释放开,造成异常。事务会回滚不会提交成功。

6. 注解版

修改spring的配置文件

1
2
3
4
5
6
<!--配置spring容器创建时要扫描的包-->
<context:component-scan base-package="com.xzxj"/>
<!--配置QueryRunner-->
<!--配置数据源-->
<!--开启spring对注解aop的支持-->
<aop:aspectj-autoproxy/>

持久层添加 @Repository 注解,业务层添加 @Service 注解啥的…懒得写了

在自定义的 TransactionManager 上添加注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@Component("txManager")
@Aspect
public class TransactionManager {
@Autowired
private ConnectionUtils connectionUtils;
//切入点表达式
@Pointcut("execution(* com.xzxj.service.impl.*.*(..))")
private void pt1(){}

/*中间都是一样的
开启事务添加@before("pt1()")
提交事务添加@AfterReturning("pt1()")
回滚事务添加@AfterThrowing("pt1()")("pt1()")
释放连接添加@After("pt1()")
*/
//也可以写个环绕通知
@Around("pt1()")
public Object aroundAdvice(ProceedingJoinPoint pjp){
Object obj = null;
try {
// 1.获取参数
Object[] args = pjp.getArgs();
// 2.开启事务
this.beginTransaction();
// 3.执行方法
obj = pjp.proceed(args);
// 4.提交事务
this.commit();
}catch (Throwable e){
// 5.回滚事务
this.rollback();
e.printStackTrace();
}finally {
// 6.释放资源
this.release();
}
return obj;
}
}
  • Copyrights © 2020-2023 夕子学姐
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信