简体   繁体   中英

Best Practise of Using Connection Pool in Slick 3.0.0 Together with Play Framework

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM