我正在尝试使用play-slick
插件与mySQL
数据库进行交互。除了每次编译代码时得到的[warn]
,一切都按预期工作。
在这一行:val dbConfig = DatabaseConfigProvider.get[JdbcProfile](Play.current)
警告是:method current in object Play is deprecated: This is a static reference to application, use DI instead
。
我尝试通过使用依赖注入定义Configuration来添加inject()方法,但它不起作用!如何在以下代码中使用Dependency Injection
,以便我不必使用自Play.current
以来已弃用的Play 2.5
import play.api.Play
import play.api.db.slick.DatabaseConfigProvider
import scala.concurrent.Future
import slick.driver.JdbcProfile
import slick.driver.MySQLDriver.api._
import scala.concurrent.ExecutionContext.Implicits.global
case class User(
id: Long,
firstName: String,
lastName: String,
mobile: Long,
email: String
)
class UserTableDef(tag: Tag) extends Table[User](tag, "users") {
def id = column[Long]("id", O.PrimaryKey,O.AutoInc)
def firstName = column[String]("first_name")
def lastName = column[String]("last_name")
def mobile = column[Long]("mobile")
def email = column[String]("email")
override def * =
(id, firstName, lastName, mobile, email) <>(User.tupled, User.unapply)
}
object Users {
val dbConfig = DatabaseConfigProvider.get[JdbcProfile](Play.current) //<-- PROBLEM
val users = TableQuery[UserTableDef]
def get(id: Long): Future[Option[User]] = {
dbConfig.db.run(users.filter(_.id === id).result.headOption)
}
}
答案 0 :(得分:2)
Play current
已弃用。 DBConfigProvider将使用guice注入。
DatabaseConfigProvider
将使用guice依赖注入注入到类UsersRepo
中。
以下是使用Guice和Play 2.5
执行此操作的方法case class User(profileName: ProfileName,
email: Email,
createdAt: DateTime,
id: UserId)
@Singleton
class UsersRepo @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) {
val dbConfig = dbConfigProvider.get[JdbcProfile]
import dbConfig.driver.api._
private[services] val users = TableQuery[Users]
def exists(id: UserId): DBIO[Boolean] = {
users.filter(_.id === id).exists.result
}
private[services] class Users(tag: Tag) extends Table[User](tag, UsersTable.name) {
def profileName = column[ProfileName]("profile_name")
def id = column[UserId]("user_id", O.PrimaryKey)
def email = column[Email]("email")
def createdAt = column[DateTime]("created_at")
def * = (profileName, email, source, createdAt, id) <> (User.tupled, User.unapply)
def emailIndex = index("users_email_index", email, true)
}
}
在application.conf
中使用play-slick
时的数据库配置
slick.dbs.default.driver="slick.driver.PostgresDriver$"
slick.dbs.default.db.driver="org.postgresql.Driver"
slick.dbs.default.db.url="jdbc:postgresql://ec2-54-217-243-228.eu-west-1.compute.amazonaws.com:5432/d344onl0761ji5?user=user&password=pass"
slick.dbs.default.db.user=user
slick.dbs.default.db.password="pass"