上一篇已经实现了用户转帐功能,补充一个内容,使用事务要保证实用的是同一个connection连接,其中dao层和dao的实现类还有service接口内容不变,改变的是service的实现类AccountServiceImpl.java
package com.qianfeng.service.impl;
import java.sql.Connection;
import java.sql.SQLException;
import com.qianfeng.dao.AccountDao;
import com.qianfeng.dao.impl.AccountDaoImpl;
import com.qianfeng.domain.Account;
import com.qianfeng.service.AccountService;
import com.qianfeng.util.C3P0Util;
import com.qianfeng.util.ManagerThreadLocal;
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao = new AccountDaoImpl();
public void transfer(String fromname, String toname, int money) {
//Connection conn = null;
try {
//使用threadlocal、实现就不用c3p0的方法了
//conn = C3P0Util.getConnection();
//accountDao = new AccountDaoImpl(conn);
//conn.setAutoCommit(false);
//需要手动控制事务则是service 先得到Connection对象,否则是Dao先得到 Connection对象
//ManagerThreadLocal.startTransaction();
//得到转账人的信息
Account from = accountDao.findAccountByName(fromname);
//得到收钱人的信息
Account to = accountDao.findAccountByName(toname);
from.setMoney(from.getMoney()-money);
to.setMoney(to.getMoney()+money);
//转账
accountDao.updateAccount(from);
//int num = 5/0;
accountDao.updateAccount(to);
ManagerThreadLocal.commitTrancsaction();
} catch (Exception e) {
try {
ManagerThreadLocal.roolBackTransaction();
e.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}finally{
try {
ManagerThreadLocal.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
下面看一下threadlocal的使用
ManagerThreadLocal.java
package com.qianfeng.util;
import java.sql.Connection;
import java.sql.SQLException;
public class ManagerThreadLocal {
private static ThreadLocal<Connection> local = new ThreadLocal<Connection>();
public static Connection getConnection() throws SQLException
{
Connection conn = null;
conn = local.get();//从ThreadLocal中获取Connection 对象
if(conn==null){
conn = C3P0Util.getConnection();
local.set(conn);//把取到的Connection对象 放入ThreadLocal
}
return conn;
}
//开启事务
public static void startTransaction() throws SQLException
{
Connection conn = getConnection();
conn.setAutoCommit(false);
}
//提交事务
public static void commitTrancsaction() throws SQLException
{
getConnection().commit();
}
//回滚事务
public static void roolBackTransaction() throws SQLException
{
getConnection().rollback();
}
public static void close() throws SQLException
{
getConnection().close();//放回连接池
local.remove();//从ThreadLocal中删除
}
}