Playframework 2.5 Slick + DI

时间:2016-04-08 01:34:24

标签: mysql scala playframework slick

我正在使用playframework 2.5 with play slick

lazy val root = (project in file(".")).enablePlugins(PlayScala)

scalaVersion := "2.11.7"

libraryDependencies ++= Seq(
  cache,
  ws,
  "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.0-RC1" % Test,
  "com.madgag.spongycastle" % "core" % "1.53.0.0",
  "org.flywaydb" %% "flyway-play" % "3.0.0",
  "com.typesafe.play" %% "play-slick" % "2.0.0",
  "com.typesafe.play" %% "play-slick-evolutions" % "2.0.0"
)

resolvers += "scalaz-bintray" at "http://dl.bintray.com/scalaz/releases"


fork in run := false

尝试用播放官方推荐的DI实现基本的CRUD课程。

trait FooService {
  def findById(id: Long)

  final class FooTable(tag: Tag) extends Table[FooModel](tag,"foo"){
    def id = column[Long]("id")
    //....
  }
}

@Singleton
class FooServiceImpl @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends FooService with HasDatabaseConfigProvider[JdbcProfile] {
  import dbConfig.driver.api._

  private lazy val bars = TableQuery[FooTable]

  def findById(id: Long) = db.run(bars.filter{ x => x.id === id}.result)
  //....
}

Module.scala

override def configure() = {
  //....
  bind(classOf[FooService]).to(classOf[FooServiceImpl])
  //....
}

application.conf

slick.dbs.default.driver = "slick.driver.MySQLDriver$"
slick.dbs.default.db.driver = com.mysql.jdbc.Driver
slick.dbs.default.db.url = "jdbc:mysql://localhost/foo"
slick.dbs.default.db.user = "root"
slick.dbs.default.db.password = "password"

我收到错误Caused by: java.lang.RuntimeException: driverClassName specified class 'com.mysql.jdbc.Driver' could not be loaded,其代码/设置高于

如果我将slick.dbs.default.db.dataSourceClass = "slick.jdbc.DatabaseUrlDataSource"添加到a​​pplication.conf,错误就会消失,但我得到了DB Timeout异常。

由于我的其他play2.4项目(非DI)可以连接到具有相同配置设置的服务器,而且我可以在控制台中连接到服务器,我很确定Db配置是正确的。

我不知道导致这个问题的原因。我在哪里做错了?

提前致谢。

1 个答案:

答案 0 :(得分:2)

您需要添加mysql驱动程序依赖项:

libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.38"

当然,请检查此版本(最新版本)是否正常或是否需要其他版本。