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