I have a legacy Java application, and would like to reuse its database connection handling when extending the app with scala.
The existing application does this to use the database (with try/catch omitted):
Connection dbConn = NewConnectionPool.getRemotePool().getConnection();
PreparedStatement ps = dbConn.prepareStatement(someQuery);
in the scala code I tried:
class Rules {
val connHandle = NewConnectionPool.getRemotePool.getConnection
val session = connHandle.unwrap(classOf[java.sql.Connection])
def loadTagRulesFromDb(name: String = "rules"): tagRuleSet = {
//val tagRules = NamedDB('remotedb) readOnly { implicit session =>
val tagRules = DB readOnly { implicit session =>
sql"select * from databasename.messaging_routing_matchers".map(
rs => tagRule(
rs.long("id"),
rs.string("description"),
rs.long("ruleid"),
rs.string("operator"),
rs.string("target")
)
).list.apply
}
for (tr <- tagRules) {
println(tr)
}
tagRuleSet(name,DateTime.now(),tagRules)
}
}
and call it like:
Rules rr = new Rules();
rr.loadTagRulesFromDb("testing");
and I get this error (both with DB and the NamedDB version) "Connection pool is not yet initialized.(name:'
" with name either default or remotedb):
java.lang.IllegalStateException: Connection pool is not yet initialized.(name:'default)
at scalikejdbc.ConnectionPool$$anonfun$get$1.apply(ConnectionPool.scala:76) ~[scalikejdbc-core_2.11-2.4.2.jar:2.4.2]
at scalikejdbc.ConnectionPool$$anonfun$get$1.apply(ConnectionPool.scala:74) ~[scalikejdbc-core_2.11-2.4.2.jar:2.4.2]
at scala.Option.getOrElse(Option.scala:121) ~[scala-library-2.11.8.jar:na]
at scalikejdbc.ConnectionPool$.get(ConnectionPool.scala:74) ~[scalikejdbc-core_2.11-2.4.2.jar:2.4.2]
at scalikejdbc.ConnectionPool$.apply(ConnectionPool.scala:65) ~[scalikejdbc-core_2.11-2.4.2.jar:2.4.2]
at scalikejdbc.DB$.connectionPool(DB.scala:151) ~[scalikejdbc-core_2.11-2.4.2.jar:2.4.2]
at scalikejdbc.DB$.readOnly(DB.scala:172) ~[scalikejdbc-core_2.11-2.4.2.jar:2.4.2]
at dk.coolsms.smsc.Rules.loadTagRulesFromDb(Rules.scala:28) ~[smsc.jar:na]
at dk.coolsms.smsc.SendMessage.sendMessage(SendMessage.java:206) ~[smsc.jar:na]
I assume that I can get a scalikejdbc compatible connection from the BoneCP connectionHandle somehow?
EDIT: the solution is below, note that DB readOnly etc.
should not be used since it relies on DBs.setupAll()
and application.conf, which does not apply in this specific case
Accessing via a javax.sql.DataSource
instance would be the best way to integrate ScalikeJDBC with existing database connections.
http://scalikejdbc.org/documentation/connection-pool.html
But you already have a raw java.sql.Connection
, it's also possible to simply create a DBSession
as below:
implicit val session = DBSession(conn)
sql"select * from databasename.messaging_routing_matchers".toMap.list.apply()