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);
		}
	}
}

發佈了4 篇原創文章 · 獲贊 1 · 訪問量 1316
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章