3
播放2.0 Scala中與ANORM框架提供了兩種方法來與數據庫進行交互:播放ANORM和SQL連接
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獲取和每次調用的時候關閉連接。
爲什麼兩種方法每次都創建和關閉連接?這不是一個昂貴的過程?