2

ScalikeJDBC's ConnectionPool docs page says:


Borrowing Connections

Simply just call #borrow method.

import scalikejdbc._
val conn: java.sql.Connection = ConnectionPool.borrow()
val conn: java.sql.Connection = ConnectionPool('named).borrow()

Be careful. The connection object should be released by yourself.


However there's no mention of how to do it.

I can always do Connection.close() but by 'releasing' Connection, I understand that I'm supposed to return the Connection back to the ConnectionPool and not close it (otherwise the purpose of having a ConnectionPool would be defied).


My doubts are:

  1. In general, what does 'releasing' a Connection (that has been borrowed from ConnectionPool) mean?
  2. In ScalikeJDBC, how do I 'release' a Connection borrowed from ConnectionPool?
y2k-shubham
  • 10,183
  • 11
  • 55
  • 131

2 Answers2

3

Calling close is fine. As per the Oracle docs: Closing a connection instance that was obtained from a pooled connection does not close the physical database connection.. The DBConnection in scalikejdbc just wraps the java.sql.Connection and delegates calls to close. The usual way of doing this with scalikejdbc is with the using function which is essentially an implementation of Java's try-with-resources.

See Closing JDBC Connections in Pool for a similar discussion on JDBC.

Dennis Hunziker
  • 1,293
  • 10
  • 19
  • While I've added an answer specific to `ScalikeJdbc`, I'm accepting this answer because it is generic and uncovers the underlying details of `JDBC` *Connection-Pooling* – y2k-shubham May 21 '18 at 09:30
1

Upon a second look into the docs, ScalikeJdbc does provide a using method implementing the loan-pattern that automatically returns the connection to the ConnectionPool.

So you can borrow a connection, use it, and return it to the pool as follows:

import scalikejdbc.{ConnectionPool, using}
import java.sql.Connection

using(ConnectionPool.get("poolName").borrow()) { (connection: Connection) =>
    // use connection (only once) here
}
// connection automatically returned to pool
y2k-shubham
  • 10,183
  • 11
  • 55
  • 131