Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Anorm and SQL connection

Play 2.0 in Scala with anorm framework provides two methods to interact with the database:

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

It is now clear to me that the withConnection acquire and closes the connection every time it is called.

Why both methods create and close the connection every time? Isn't that an expensive process ?

like image 259
Edmondo1984 Avatar asked Dec 19 '25 13:12

Edmondo1984


1 Answers

em...there is no problem since we can retrieve connection from connection pool. so close() method just return the connection to the pool, not actually closed.

like image 94
user1266054 Avatar answered Dec 22 '25 04:12

user1266054



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!