Connection的相关操作,防止业务层挂羊头卖狗肉

Connection的相关操作,防止业务层(service层含有java.sql.*),连接池类似!!!

原理:使用ThreadLocal,得到当前线程上的变量!!!!

package cn.viwiv.util;

import java.sql.Connection;
import java.sql.SQLException;

public class TransactionManager {
	private static final ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
	public static Connection getConnection() {
		Connection connection = threadLocal.get();//从当前线程上获取连接
		if(connection == null) {
			connection = DBUtils.getConnection();
			threadLocal.set(connection);
		}
		return connection;
	}
	
	public static void startTransaction() {
		Connection connection = getConnection();
		try {
			connection.setAutoCommit(false);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	public static void commit() {
		Connection connection = getConnection();
		try {
			connection.commit();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	public static void rollback() {
		Connection connection = getConnection();
		try {
			connection.rollback();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	public static void release() {
		Connection connection = getConnection();
		try {
			connection.close();
			threadLocal.remove();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}

发布了5 篇原创文章 · 获赞 0 · 访问量 121

猜你喜欢

转载自blog.csdn.net/qq_35867420/article/details/103129659