这篇博客使用spring框架书写一个账户A转账给账户B的简单案例来认识一下事务的开启和回滚.
第一步:创建项目,添加依赖
- 涉及到的依赖有:
序号 | 作用 |
---|---|
1 | spring注解的依赖 |
2 | Dbutils工具类 |
3 | mysql数据库驱动依赖 |
4 | c3p0 |
5 | junit单元测试 |
6 | 事务代理 |
7 | AOP |
8 | spring整合jdbc |
<dependencies>
<!-- Spring注解 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- MySQl数据库连接 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!-- c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- pring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- AOPJAR -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
</dependencies>
第二步:建表,创建实体类
第三步:实现dao层的代码书写
- 写dao接口
- 因为要获取连接对象,所以写获取连接对象的工具类:
package com.offcn.Utils;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionUtil {
private static ThreadLocal<Connection> threadLocal=new ThreadLocal<>();
public static Connection getConn(){
Connection connection=threadLocal.get();
if (connection == null){
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/java1026?characterEncoding=utf8&serverTimezone=UTC", "root", "root");
threadLocal.set(connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
return connection;
}
}
- 书写实现类
package com.offcn.dao;
import com.offcn.Utils.ConnectionUtil;
import org.apache.commons.dbutils.QueryRunner;
import java.sql.SQLException;
public class AccountDaoImpl implements AccountDao {
private QueryRunner queryRunner;
@Override
public int withdrawMoney(String account, double money) throws SQLException {
String sql="update accountbank set money=money-? where username=?";
return queryRunner.update(ConnectionUtil.getConn(),sql,money,account);
}
@Override
public int saveMoney(String account, double money) throws SQLException {
String sql="update accountbank set money=money+? where username=?";
return queryRunner.update(ConnectionUtil.getConn(),sql,money,account);
}
}
第四步:实现service层代码:
package com.offcn.service;
import com.offcn.Utils.ConnectionUtil;
import com.offcn.dao.AccountDao;
import com.offcn.dao.AccountDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.sql.SQLException;
@Repository
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDaoImpl accountDao;
@Override
public boolean tranfer(String accountFrom, String accountTo, double money) throws SQLException {
//开启事务
ConnectionUtil.getConn().setAutoCommit(false);
//accountFrom取钱
int i = 0;
int i1 = 0;
try {
i = accountDao.withdrawMoney(accountFrom, money);
int a = 1/0;
//accountTo存钱
i1 = accountDao.saveMoney(accountTo, money);
} catch (Exception e) {
System.out.println("出现异常,准备执行回滚操作");
//回滚事务
ConnectionUtil.getConn().rollback();
System.out.println("数据恢复完成...");
}
//提交事务
ConnectionUtil.getConn().commit();
if (i>0&&i1>0){
return true;
}
return false;
}
}
第五步:测试代码:
@Test
public void m1() throws SQLException {
ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
AccountServiceImpl bean = context.getBean(AccountServiceImpl.class);
boolean tranfer = bean.tranfer("zhangsan", "lisi", 10000);
if (tranfer){
System.out.println("成功");
}else{
System.out.println("失败");
}
}
上述代码中没有涉及到使用spring框架来帮助我们进行事务的管理,因为我们发现,我们的service层中出现了和业务逻辑毫不相干的代码:开启事务,所以我们接下来要去除这些和service层没有关系的代码,让spring来帮助我们进行事务的开启和关闭
Spring中事务的管理
第一步:容器中配置事务管理器:
第二步:添加事务管理通知:
第三步:配置织入(就是精确指定那个方法进行事务管理)
第四步:测试代码
@Test
public void m1() throws SQLException {
ApplicationContext context=new ClassPathXmlApplicationContext("bean.xml");
AccountService accountService =(AccountService) context.getBean("accountService");
boolean tranfer = accountService.tranfer("zhangsan", "lisi", 10000);
if (tranfer){
System.out.println("成功");
}else{
System.out.println("失败");
}
}
这个贴上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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.offcn"></context:component-scan>
<context:property-placeholder location="db.properties"></context:property-placeholder>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driver}"></property>
<property name="jdbcUrl" value="${url}"></property>
<property value="${name}" name="user"/>
<property value="${pwd}" name="password"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:advice id="txadvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="tranfer" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:advisor advice-ref="txadvice" pointcut="execution(* com.offcn..service.*Impl.*(..))"></aop:advisor>
</aop:config>
<bean id="accountService" class="com.offcn.service.AccountServiceImpl"></bean>
</beans>
这个是最终我们在service层的代码:
package com.offcn.service;
import com.offcn.Utils.ConnectionUtil;
import com.offcn.dao.AccountDao;
import com.offcn.dao.AccountDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import java.sql.SQLException;
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDaoImpl accountDao;
@Override
public boolean tranfer(String accountFrom, String accountTo, double money) throws SQLException {
int i = 0;
int i1 = 0;
i = accountDao.withdrawMoney(accountFrom, money);
i1 = accountDao.saveMoney(accountTo, money);
if (i>0&&i1>0){
return true;
}
return false;
}
}
使用注解改写上面的案例:
- 在容器中定义标签
- 在方法上定义注解: