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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With