如何在Scala的Play 2.6中设置MySql连接

时间:2018-11-27 13:44:51

标签: scala playframework

我是新手,请尝试一下,因为我可能找不到如何配置Scala Play 2.6应用程序的完整示例。 Play和2.6 documentaion版本之间没有明显的示例。

我当前的状态是我正在获取ataSource或 dataSourceClassName或jdbcUrl。错误。

此外,有人可以解释application.conf中两个“ db”部分的目的, play.db {}与db {}

2 个答案:

答案 0 :(得分:2)

使用Slick时,您可以像这样配置它:

slick {
  dbs {
    default {
      profile = "slick.jdbc.MySQLProfile$"
      db {
        driver = "com.mysql.jdbc.Driver"
        url = "jdbc:mysql://url:3306/dbname"
        user = "user"
        password = "password"

        // comment out for Production
        connectionPool = disabled
      }
    }
  }
}

如果您使用的是Evolution,则必须在配置中添加以下行:

play.evolutions.enabled = true

默认数据库配置的Evolution .sql文件需要放置在

conf/evolutions/default/

具有某些数据库内容的类需要进行以下导入和注入:

import javax.inject.{Inject, Singleton}
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import slick.jdbc.JdbcProfile

@Singleton
class DBClass @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)
extends HasDatabaseConfigProvider[JdbcProfile] { 

    import profile.api._
...
}

控制器将类似于:

import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import play.api.mvc.{AbstractController, ControllerComponents}
import slick.jdbc.{JdbcProfile, TransactionIsolation}

@Singleton
class DBController @Inject()(protected val dbConfigProvider: DatabaseConfigProvider, 
cc: ControllerComponents)
      extends AbstractController(cc) with HasDatabaseConfigProvider[JdbcProfile] {

    import profile.api._
...
}

对于隐式执行上下文,您需要此导入:

import scala.concurrent.ExecutionContext.Implicits.global

如需进一步阅读,请阅读本书:

https://books.underscore.io/essential-slick/essential-slick-3.pdf

答案 1 :(得分:0)

经过反复试验,以下内容不会引发任何异常:

在build.sbt

libraryDependencies ++= Seq(jdbc,  ehcache , ws , specs2 % Test , guice )
libraryDependencies ++= Seq("com.typesafe.play" %% "play" % "2.6.11")
libraryDependencies += "com.typesafe.play" %% "play-slick" % "3.0.0"
libraryDependencies ++= Seq("mysql" % "mysql-connector-java" % "5.1.36")

在application.conf中

db.default.driver   = com.mysql.jdbc.Driver
db.default.url      = "jdbc:mysql://localhost/my_database"
db.default.username = "my_user_name"
db.default.password = "my_password"
play.db {
  # The combination of these two settings results in "db.default" as the
  # default JDBC pool:
  #config = "db"
  #default = "default"

  # Play uses HikariCP as the default connection pool.  You can override
  # settings by changing the prototype:
  prototype {
    # Sets a fixed JDBC connection pool size of 50
    #hikaricp.minimumIdle = 50
    #hikaricp.maximumPoolSize = 50
  }
}