我应该使用 ThreadLocal 来存储连接吗?

Should I use ThreadLocal to store connections?

我编写了我的测试项目,禁止在那里使用 Spring 和 Hibernate。

我想从服务层管理我的交易。 为此,我创建了一个 class,它从池中获取一个连接并将其放入 ThreadLocal。

这是字段和方法的示例。

  private static ThreadLocal<Connection> threadLocalConnection;
  private ComboPooledDataSource comboPooledDataSource ;

  public boolean createConnectionIfAbsent() {

    boolean isConnectionCreated = false;

    try {
      Connection currentConnection = threadLocalConnection.get();
      if(currentConnection == null) {
        Connection conn = this.comboPooledDataSource.getConnection();
        conn.setAutoCommit(false);
        threadLocalConnection.set(conn);
        isConnectionCreated = true;
      }

    } catch (SQLException e) {
      e.printStackTrace();
    }
    return isConnectionCreated;
  }

class 也有关闭、回滚方法。

这是我如何在服务层中管理连接的示例。

public BigDecimal getTotalOrdersCount() {
    boolean connectionCreated = DBManager.getInstance().createConnectionIfAbsent();

    BigDecimal ordersCount = BigDecimal.ZERO;
    try {
        ordersCount = orderDao.getRowNumber();
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    } finally {
        if (connectionCreated) DBManager.getInstance().closeConnection();
    }
    return ordersCount;
}

Dao 只是使用它来获取连接。

Connection connection = DBManager.getInstance().getConnection();

我发现没有其他方法可以从服务层管理 Servlet 项目中的连接,请问是否可以?如果不是 - 它有什么缺点,我应该用什么代替。

更新:

请注意此服务方式。让我们假设 DAO 中的每个方法都从池中获取连接并关闭它。 我知道我需要 connection.setAutoCommit(false);开始交易,但在这种情况下该怎么办? 当单个方法调用 2 个 DAO 时。 只是放弃交易处理?

void setStatusDeclinedAndRefund() {
// sets Order status to DECLINED
// refund money to user's balance
}

没有

不要再猜测连接池。以标准方式使用它:获取连接、使用它、关闭它。

无需为给定线程中的每个数据库交互使用相同的连接。此外,如果您为每个线程分配一个连接,您将遇到严重的活跃性问题,因为请求处理线程通常比池中的连接多得多。