创建ConnectionUtil类
public class ConnectionUtil {
// 存放和当前线程绑定的连接
private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
private DataSource dataSource;
/**
* 返回当前线程绑定的连接对象
* @return
*/
public Connection getCurrentThreadConn() throws SQLException {
Connection connection = threadLocal.get();
if(connection == null) {
connection = dataSource.getConnection();
threadLocal.set(connection);
}
return connection;
}
}
事务管理器:开启事务、提交事务、回滚事务等
@Component(“transactionManager”)
public class TransactionManager {
@Autowired
@Qualifier("connectionUtil")
private ConnectionUtil connectionUtil;
/**
* 开启事务(就是关闭连接的事务自动提交功能)
*/
public void beginTransaction() throws Exception {
connectionUtil.getCurrentThreadConn().setAutoCommit(false);
}
/**
* 提交事务
* @throws Exception
*/
public void commit() throws Exception{
connectionUtil.getCurrentThreadConn().commit();
}
/**
* 回滚事务
* @throws Exception
*/
public void rollback() throws Exception{
connectionUtil.getCurrentThreadConn().rollback();
}
/**
* 释放资源
* @throws Exception
*/
public void release() throws Exception{
// 关闭连接
connectionUtil.getCurrentThreadConn().close();
}
}
代理对象工厂
@Component(“proxyFactory”)
public class ProxyFactory {
@Autowired
@Qualifier("transactionManager")
private TransactionManager transactionManager;
public Object getProxy(Object object) {
return Proxy.newProxyInstance(this.getClass().getClassLoader(), object.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try{
// 开启事务(把事务的自动提交关闭即可)
transactionManager.beginTransaction();
// 业务逻辑代码
result = method.invoke(object,args);
// 提交事务
transactionManager.commit();
}catch (Exception e) {
e.printStackTrace();
// 回滚事务
transactionManager.rollback();
}finally {
// 释放资源
transactionManager.release();
}
return result;
}
});
}
}