【问题标题】:Slick 3 how can I get the default configuration in the application fileSlick 3 如何获取应用程序文件中的默认配置
【发布时间】:2016-01-27 05:04:55
【问题描述】:

我在网上似乎有很多具有以下 slick 3 配置的示例

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 控制器中连接到它?我正在使用播放框架版本 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")
  }

}

【问题讨论】:

    标签: scala playframework slick slick-3.0


    【解决方案1】:

    在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
    }
    

    【讨论】:

      猜你喜欢
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 2012-01-05
      • 2017-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多