public class TransactionsUtil {
//创建线程
private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
//获取连接
public static Connection getConnection() throws PropertyVetoException, SQLException {
Connection conn = threadLocal.get();//获取链接,如果没有自动创建副本
if (conn == null) {
//c3p0数据源
conn = ComboPooledDataSourceUtil.getDataSourceByxml().getConnection();
threadLocal.set(conn);
}
return conn;
}
//开启事务
public static void begin() throws PropertyVetoException, SQLException {
Connection conn = getConnection();//先获取链接
if (conn != null) conn.setAutoCommit(false);//手动提交/开启事务
}
//提交事务
public static void commit() throws PropertyVetoException, SQLException {
Connection connection = getConnection();
if (connection != null) connection.commit();
}
//事务回滚
public static void rollback() throws PropertyVetoException, SQLException {
Connection connection = getConnection();
if (connection == null) connection.rollback();
}
//关闭线程和连接
public static void close() throws PropertyVetoException, SQLException {
Connection conn = getConnection();
if (conn != null) conn.close();
threadLocal.remove();
}
}