在Play Slick中分配动态注入的数据库名称 [英] Assign dynamically injected database name in Play Slick
问题描述
我有以下Play Slick DAO课程.请注意,数据库配置是常量control0001
. DAO具有readUser
函数,该函数根据用户ID读取用户:
I have the following Play Slick DAO class. Note that the database configuration is a constant control0001
. The DAO has a function readUser
that reads a user based on its user id:
class UsersDAO @Inject()(@NamedDatabase("control0001")
protected val dbConfigProvider: DatabaseConfigProvider)
extends HasDatabaseConfigProvider[JdbcProfile] {
import driver.api._
def readUser (userid: String) = {
val users = TableQuery[UserDB]
val action = users.filter(_.userid === userid).result
val future = db.run(action.asTry)
future.map{
case Success(s) =>
if (s.length>0)
Some(s(0))
else
None
case Failure(e) => throw new Exception ("Failure in readUser: " + e.getMessage)
}
}
}
除了在@NamedDatabase("control0001")
中没有常量之外,我需要数据库是可变的.在应用程序中,我在application.conf
中配置了多个数据库(control0001
,control002
等).根据变量值,我需要确定要在DAO中使用的数据库.所有数据库都是相似的,并且具有相同的表(每个数据库中的数据都不同).
Instead of having a constant in @NamedDatabase("control0001")
, I need the database to be variable. In the application, I have multiple databases (control0001
, control002
and so on) configured in application.conf
. Depending on a variable value, I need to determine the database to be used in the DAO. All the databases are similar and have the same tables (the data in each database differs).
以下Play类调用DAO函数,但首先需要确定要注入的数据库名称:
The following Play class calls the DAO function, but first it needs to determine the database name to be injected:
class TestSlick @Inject()(dao: UsersDAO) extends Controller {
def test(someCode: Int, userId: String) = Action { request =>
val databaseName = if (someCode == 1) "control0001" else "control0002"
// Run the method in UsersDAO accessing the database set by databaseName
val future = dao.readUser(userId)
future.map { result =>
result match {
case Some(user) => Ok(user.firstName)
case _ => Ok("user not found")
}
}
}
}
如何在Play Slick中实现?
How can this be achieved in Play Slick?
推荐答案
您可以尝试初始化覆盖默认配置的slick db对象:
You can try to initialize slick db object overriding default config:
val db = Database.forURL("jdbc:mysql://localhost/" + databaseName, driver="org.h2.Driver")
更多信息,请参见slick docs http://slick.lightbend.com/doc/3.0.0/database.html
more information in slick docs http://slick.lightbend.com/doc/3.0.0/database.html
这篇关于在Play Slick中分配动态注入的数据库名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!