読者です 読者をやめる 読者になる 読者になる

takafumi blog

日々の勉強メモ

【Scala】【ScalikeJDBC】 Config設定方法

Scala

環境   Scala 2.11.8  ScalikeJDBC 2.5.0

  • 基本的にはこの内容 Configuration - ScalikeJDBC

  • scalikejdbc-conifg, application.confは設定方法によって必要

  • build.sbt

libraryDependencies ++= Seq(
  "org.scalikejdbc" %% "scalikejdbc"        % "2.5.0",
  "org.scalikejdbc" %% "scalikejdbc-config" % "2.5.0",
  "mysql" % "mysql-connector-java"          % "6.0.5",
  "ch.qos.logback"  %  "logback-classic"    % "1.1.7"
)
  • src/main/resourcese/application.conf
development {
  db {
    sandbox {
      driver="com.mysql.cj.jdbc.Driver"
      url="jdbc:mysql://localhost:3306/test"
      user="sa"
      password=""
    }
  }
}
/**
 * ConnectionPool config sample
 */
package main.scala.com.example

import scalikejdbc._
import scalikejdbc.config._
import com.mysql.cj.jdbc.Driver

object Db1{

  /**
   * Pattern 1
   */
  def ex1 = {
    // Initialize
    ConnectionPool.singleton("jdbc:mysql://localhost:3306/test", "sa", "")

    implicit val session = AutoSession

    // Query
    val r = sql"""select * from a""".map(_.toMap).list.apply()
    println(r)
  }

  /**
   * Pattern 2
   *   necessary import scalikejdbc.config._
   */
  def ex2 = {
    // Initialize
    Class.forName("com.mysql.cj.jdbc.Driver")
    val settings = ConnectionPoolSettings(
      initialSize = 5,
      maxSize = 20,
      connectionTimeoutMillis = 3000L,
    validationQuery = "select 1")

    ConnectionPool.add('example, "jdbc:mysql://localhost:3306/test", "sa", "", settings)

    implicit val session = AutoSession

    // Query
    val r = NamedDB('example) readOnly { implicit session =>
      sql"""select * from a""".map(_.toMap).list.apply()
    }
    println(r)
  }

  /**
   * Pattern 3
   *   necessary import scalikejdbc.config._
   *   necessary main/resources/application.conf
   */
  def ex3 = {
    // Initialize
    DBsWithEnv("development").setup('sandbox)
    // addで別の設定を追加する事も可能

    implicit val session = AutoSession

    // Query
    val r = NamedDB('sandbox) readOnly { implicit session =>
      sql"""select * from a""".map(_.toMap).list.apply()
    }
    println(r)
  }
}