Slick 3.0.0 玩2.6.2
我正在尝试使用Slick并遇到一个有趣的问题。我希望解决方案是微不足道的,我在想这个
我已经实现了以下简单代码。
case class Content(content:String)
class ContentTable(tag: Tag) extends Table[Content](tag, "content"){
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def content = column[String]("content")
override def * : ProvenShape[Content] = (content).mapTo[Content]
}
object ContentDb {
val db = Database.forConfig("databaseConfiguration")
lazy val contents = TableQuery[ContentTable]
def all: Seq[Content] = Await.result(db.run(contents.result), 2 seconds)
}
因此,要使此代码正常工作,当然需要进行以下导入。
import slick.jdbc.H2Profile.api._
或者
import slick.jdbc.PostgresProfile.api._
现在,我想,如果我错了,请纠正我,数据库驱动程序应该是配置细节。也就是说,我选择在开发时在内存数据库中运行H2。在测试时针对测试PostgreSQL实例运行,然后在生产时针对另一个实例运行。我的意思是抽象驱动程序的整个想法就是拥有这种灵活性......我想。
现在,我做了一些研究,发现我可以这样做:
trait DbComponent {
val driver: JdbcProfile
import driver.api._
val db: Database
}
trait H2DbComponent extends DbComponent {
val driver: JdbcProfile = slick.jdbc.H2Profile
import driver.api._
val db = Database.forConfig("databaseConfiguration")
}
trait Contents {
def all: Seq[Content]
}
object Contents {
def apply: Contents = new ContentsDb with H2DbComponent
}
trait ContentsDb extends Contents {
this: DbComponent =>
import driver.api._
class ContentTable(tag: Tag) extends Table[Content](tag, "content") {
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def content = column[String]("content")
override def * : ProvenShape[Content] = content.mapTo[Content]
}
lazy val contents = TableQuery[ContentTable]
def all: Seq[Content] = Await.result(db.run(contents.result), 2 seconds)
}
然后我可以使用依赖注入为我拥有的每个实体注入正确的实例。不理想,但可能。因此,我开始深入研究如何根据Play Framework中运行的环境进行条件依赖注入。
我期待类似于以下内容:
@Component(env=("prod","test")
class ProductionContentsDb extends ContentsDb with PostgresDbComponent
@Component(env="dev")
class ProductionContentsDb extends ContentsDb with H2DbComponent
但是,没有运气......
修改
在我写完这篇文章并再次开始阅读之后,我很好奇我们是否可以拥有类似的内容:
class DbComponent @Inject (driver: JdbcProfile) {
import driver.api._
val db = Database.forConfig("databaseConfiguration")
}
答案 0 :(得分:-1)
您可以为每个环境创建单独的配置文件。喜欢
application.conf --local
application.prod.conf -- prod with contents below
include "aplication.conf"
###update slick configurations
然后,在不同阶段运行应用程序时,请输入-Dconfig.resource=