Slick 3如何在应用程序文件中获取默认配置

时间:2016-01-27 05:04:55

标签: scala playframework slick slick-3.0

我在网上看到很多具有如下光滑配置的示例

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"

我的问题是你如何连接到Scala控制器内部?我正在使用Play框架版本2.4.6。我试过这个

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

但是我收到了错误

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
                 ^

我的控制器看起来像这样

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")
  }

}

1 个答案:

答案 0 :(得分:0)

在conf中,我将数据库定义如下:

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

在.scala文件中,我使用这样的数据库:

import com.typesafe.config.ConfigFactory

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

然后从数据库中选择如下:

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