Ignacio Perez
Ignacio Perez

Reputation: 2361

Slick 3 how can I get the default configuration in the application file

I have seem many examples on the web that has slick 3 configuration as follows

slick.dbs.default.driver="slick_driver"
slick.dbs.default.db.driver="db_driver"
slick.dbs.default.db.url="URL_file
slick.dbs.default.db.user="user"
slick.dbs.default.db.password="password"

My question is how can you connect to that inside a Scala controller ? I am using play framework version 2.4.6 . I have tried this

def db: Database = Database.forDataSource(DB.getDataSource())

but I get an error

Error:(5, 17) Play 2 Compiler: 
 C:\Users\nemer\mycontroller\app\controllers\Application.scala:5:
  object db is not a member of package play.api
 import play.api.db.DB
                 ^

My Controller looks like this

package controllers


import org.mindrot.jbcrypt.BCrypt
import play.api.db.DB

import play.api.libs.json.{Json, JsValue}
import play.api.mvc._
import slick.driver.PostgresDriver.api._
import scala.concurrent.duration._
import scala.concurrent.Await
import play.api.libs.concurrent.Execution.Implicits._


class Application extends Controller {


 // I am trying to get the Slick config settings in here
 def db: Database = Database.forDataSource(DB.getDataSource())

  def mypage = Action {



    val json: JsValue = Json.parse("""
{
  "name" : "Watership Down",
  "location" : {
    "lat" : 51.235685,
    "long" : -1.309197
  },
  "residents" : [ {
    "name" : "Fiver",
    "age" : 4,
    "role" : null
  }, {
    "name" : "Bigwig",
    "age" : 6,
    "role" : "Owsla"

  } ]
}
                                   """)
    Ok(json).as("text/json")
  }

}

Upvotes: 2

Views: 1324

Answers (1)

Jerry
Jerry

Reputation: 492

in the conf, I define the database as following:

db.test.driver="com.mysql.jdbc.Driver"
db.test.url="jdbc:mysql://localhost/test"
db.test.user="test"
db.test.password="test"

in the .scala file, I use the database like this:

import com.typesafe.config.ConfigFactory

val config = ConfigFactory.load()
val db = Database.forConfig("db.test", config)

Then select from database as following:

db.withSession { implicit session =>
    myTable.filter(_.id === "123").firstOption
}

Upvotes: 1

Related Questions