9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MySQLをScalikeJDBCとHikariCPで使う

Last updated at Posted at 2015-01-15

HikariDataSourceのままDataSourceconnectionPoolに渡してしまえばOK

基本的な書き方は以下のとおり

import javax.sql.DataSource
import scalikejdbc._
import com.zaxxer.hikari._

class Sample {
  ConnectionPool.add('master, new DataSourceConnectionPool(getDataSource))

  def getDataSource: javax.sql.DataSource = {
      val host = "localhost"
      val port = 3306
      val database = "master"
      val user = "foobar"
      val password = "foobar"
      val dataSourceClassName = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource"
    
      val ds = new HikariDataSource()
      ds.setDataSourceClassName(dataSourceClassName)
      ds.addDataSourceProperty("url", s"jdbc:mysql://$host/$database")
      ds.addDataSourceProperty("user", user)
      ds.addDataSourceProperty("password", password)
      ds
  }
  
  // あとはScalikeJDBCを使う
  def findAll = {
    val result = NamedDB(Symbol("master")) readOnly { implicit session =>
      Hogehoge.findAll
    }
  }
  
}

HikariDataSourceオブジェクトを作成してConnectionPoolに登録。
scalikejdbcでborrowする。

ハマりポイント

dataSourceClassNameを設定しないとうまくいかない。ds.setDataSourceClassName(dataSourceClassName)が必要。

MySQLへの接続がうまくいっていないとborrowするときに NullPointerException が発生する。スタックトレースを見ても何故発生しているのかわからなかった。。。(´・_・`)

いろいろ試してみた結果 dataSourceClassName が必要みたい。

9
9
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?