数据准备
CREATE TABLE `account` (
`id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`money` decimal(7,2) NOT NULL,
`create_time` datetime(6) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into account values(1,"steven",10000,"2022-12-07 00:00:00");
insert into account values(2,"sherry",10000,"2022-12-07 00:00:00");
搭建工程
1.引入项目使用的依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
2.编写db配置文件db.properties
在项目目录“/src/main/resources”下新建db.properties文件,具体代码如下。
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/study?useSSL=false
username=root
password=admin123
3.编写Spring框架核心配置文件applicationContext.xml
在项目目录“/src/main/resources”下新建applicationContext.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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1.开启注解扫描 -->
<context:component-scan base-package="com.steven.*"/>
<!-- 2.引入properties -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 3.配置DataSource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${url}"/>
<property name="driverClass" value="${driver}"/>
<property name="user" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<!-- 4.配置queryRunner -->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<constructor-arg name="ds" ref="dataSource"/>
</bean>
</beans>
4.编写工具类
在项目目录“/src/main/java/com/steven”下新建utils目录,并在utils目录下新建获取数据库连接工具类ConnectionUtils和事务管理工具类TransactionManager类,具体代码如下。
(1).ConnectionUtils
@Component
public class ConnectionUtils {
@Autowired
private DataSource dataSource;
private ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
/**
* 获取当前线程上绑定连接
* 如果获取到的连接为空,就要从数据源中获取连接,并放到ThreadLocal中(绑定到当前线程)
*/
public Connection getThreadConnection() {
//1.先从ThreadLocal上获取连接
Connection connection = threadLocal.get();
//2.判断当前线程中是否有Connection
if (connection == null) {
//3.从数据源中获取一个连接,并且存入ThreadLocal中
try {
connection = dataSource.getConnection();
threadLocal.set(connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
return connection;
}
/**
* 解除当前线程的连接绑定
*/
public void removeThreadConnection() {
threadLocal.remove();
}
}
(2).TransactionManager
@Component
public class TransactionManager {
@Autowired
private 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().setAutoCommit(true);
//将连接归还到连接池
connectionUtils.getThreadConnection().close();
//解除线程绑定
connectionUtils.removeThreadConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
5.dao层
在项目目录“/src/main/java/com/steven”下新建dao目录,并在dao目录下新建IAccountDao接口和AccountDaoImpl实现类,具体代码如下。
public interface IAccountDao {
//转出操作
void out(String outUser, Double money);
//转入操作
void in(String inUser, Double money);
}
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private QueryRunner queryRunner;
@Autowired
private ConnectionUtils connectionUtils;
public void out(String outUser, Double money) {
String sql = "update account set money = money - ? where name = ?";
try {
queryRunner.update(connectionUtils.getThreadConnection(), sql, money, outUser);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void in(String inUser, Double money) {
String sql = "update account set money = money + ? where name = ?";
try {
queryRunner.update(connectionUtils.getThreadConnection(), sql, money, inUser);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
6.service层
在项目目录“/src/main/java/com/steven”下新建service目录,并在service目录下新建IAccountService接口和AccountServiceImpl实现类,具体代码如下。
public interface IAccountService {
void transfer(String outUser,String inUser,Double money);
}
@Service
public class AccountServiceImpl implements IAccountService {
@Autowired
private IAccountDao accountDao;
@Autowired
private TransactionManager transactionManager;
public void transfer(String outUser, String inUser, Double money) {
try {
//1.开启事务
transactionManager.beginTransaction();
//2.业务操作
accountDao.out(outUser, money);
int i = 1 / 0;
accountDao.in(inUser, money);
//3.提交事务
transactionManager.commit();
} catch (Exception e) {
e.printStackTrace();
//4.回滚事务
transactionManager.rollback();
} finally {
//5.释放资源
transactionManager.release();
}
}
}
7.编写测试类
在项目目录“/src/main/java/com/steven”下新建Test类,具体代码如下。
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
IAccountService accountService = (IAccountService) context.getBean("accountServiceImpl");
accountService.transfer("steven", "sherry", 100d);
}
}
程序执行成功,查看数据库数据,steven和sherry的10000元数额未发生变化。
上面代码,虽然可以实现事务控制,但是业务层方法和事务控制方法耦合在一起,违背了面向对象的开发思想。
将业务代码和事务代码进行拆分,通过动态代理的方式,对业务方法进行事务的增强。这样
就不会对业务层产生影响,解决耦合性的问题。
8.工程目录