2
votes

I followed the documentation of Slick 3.0.0-RC1, using Typesafe Config as database connection configuration. Here is my conf:

database = {
  driver = "org.postgresql.Driver"
  url = "jdbc:postgresql://localhost:5432/postgre"
  user = "postgre"
}

I established a file Locale.scala as:

package models

import slick.driver.PostgresDriver.api._
import scala.concurrent.Future

case class Locale(id: String, name: String)

class Locales(tag: Tag) extends Table[Locale](tag, "LOCALES") {
  def id = column[String]("ID", O.PrimaryKey)
  def name = column[String]("NAME")

  def * = (id, name) <> (Locale.tupled, Locale.unapply)
}

object Locales {
  private val locales = TableQuery[Locales]

  val db = Database.forConfig("database")

  def count: Future[Int] =
    try db.run(locales.length.result)
    finally db.close
}

Then I got confused that when and where the proper time is to create Database object using

val db = Database.forConfig("database")

If I create db like this, there will be as many Database objects as my models. So what is the best practice to get this work?

1

1 Answers

0
votes

You can create an Object DBLocator and load it using lazy operator so that its loaded only on demand.

You can always invoke the method defined in DBLocator class to get an instance of Session.