3

Play 2.0 in Scala with anorm 框架提供了两种与数据库交互的方法:

def withConnection[A](name: String)(block: Connection => A): A = {
    val connection = new AutoCleanConnection(getConnection(name))
    try {
      block(connection)
    } finally {
      connection.close()
    }
  }

  /**
   * Execute a block of code, in the scope of a JDBC transaction.
   * The connection and all created statements are automatically released.
   * The transaction is automatically committed, unless an exception occurs.
   *
   * @param name The datasource name.
   * @param block Code block to execute.
   */
  def withTransaction[A](name: String)(block: Connection => A): A = {
    withConnection(name) { connection =>
      try {
        connection.setAutoCommit(false)
        val r = block(connection)
        connection.commit()
        r
      } catch {
        case e => connection.rollback(); throw e
      }
    }
  }

我现在很清楚,每次调用 withConnection 时都会获取并关闭连接。

为什么这两种方法每次都创建和关闭连接?这不是一个昂贵的过程吗?

4

1 回答 1

2

em...没有问题,因为我们可以从连接池中检索连接。所以 close() 方法只是将连接返回到池中,而不是实际关闭。

于 2013-06-24T12:55:09.577 回答