1. 为什么需要事务?
Service层在每次调用dao层的的方法时都会创建一个connection。所以每个方法执行过程是不相关的。如果在实际中执行一系列有关联的操作,就无法确保一致性。故需要事务。
2. 如何实现事务?
使用ThreadLocal对象把Connection和当前线程绑定,从而使一个线程中只有一个Connection对象。
1)编写一个ConnectionUtils用ThreadLocal绑定一个connection
这里的DataSource用于创建connection,通过spring依赖注入实例化。
public class ConnectionUtils {
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Connection getThreadConnection(){
try {
Connection connection = tl.get();
if(connection == null){
connection = dataSource.getConnection();
tl.set(connection);
}
return connection;
}catch (SQLException sqlException) {
throw new RuntimeException();
}
}
public void releaseConnection(){
tl.remove();
}
}
2) 编写TransactionManager实现事务的基本操作(创建事务,提交事务,回滚事务,关闭事务)
这里的connectionUtils 也是通过Spirng依赖注入实例化。
public class TransactionManager {
private ConnectionUtils connectionUtils;
public TransactionManager(ConnectionUtils connectionUtils){
this.connectionUtils = connectionUtils;
}
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
public void beginTransaction(){
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
public void close(){
try {
connectionUtils.getThreadConnection().close();
connectionUtils.releaseConnection();
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
public void rollback(){
try {
connectionUtils.getThreadConnection().rollback();
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
}
3)修改Dao层方法
@Override
public void updateAccount(Account account) {
try {
queryRunner.update(connectionUtils.getThreadConnection(),"update account set money = ? where id = ?", account.getMoney(), account.getId());
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
此时的queryRunner由于初始化的时候没有注入dataSource。所以这里connectionUtils.getThreadConnection()获取存在ThreadLocal中的connection。
4)修改Service,添加事务操作。
public void transfer(String source, String to, float money) {
try {
// 1. 开启事务
tsManager.beginTransaction();
// 2. 执行sql语句
Account sourceAccount = accountDao.getAccountByName(source);
Account toAccount = accountDao.getAccountByName(to);
sourceAccount.setMoney(sourceAccount.getMoney() - money);
toAccount.setMoney(toAccount.getMoney() + money);
accountDao.updateAccount(sourceAccount);
System.out.println(1/0);
accountDao.updateAccount(toAccount);
// 3. commit
tsManager.commit();
}catch (Exception e){
tsManager.rollback();
e.printStackTrace();
throw new RuntimeException();
}finally {
// 4.关闭连接
tsManager.close();
}
}
5)修改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:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
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/util http://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.xzp"></context:component-scan>
<bean id="accountService" class="com.xzp.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"></property>
<property name="tsManager" ref="tsManager"></property>
</bean>
<bean id="accountDao" class="com.xzp.dao.impl.AccountDaoImpl">
<property name="queryRunner" ref="queryRunner"></property>
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
<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>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring01"></property>
<property name="user" value="root"></property>
<property name="password" value="a8t9f5j8"></property>
</bean>
<bean id="connectionUtils" class="com.xzp.utils.ConnectionUtils">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="tsManager" class="com.xzp.utils.TransactionManager">
<property name="connectionUtils" ref="connectionUtils"></property>
</bean>
</beans>