设置 Slick 3.xx 以在不同环境中使用不同的数据库

Setting up Slick 3.xx to use different databases in different environments

我已经 运行 熟练地使用我们的 Oracle 数据库一段时间了。现在我还想在我们的集成测试中将它用于 H2。我以为这只是更改正在加载的驱动程序,但现在我意识到我所有的存储库都充满了 import slick.jdbc.OracleProfile.api._,这让我觉得我的存储库此时与 OracleSQL 相关联。

让 Slick 支持根据不同的配置文件加载 Oracle 或 H2 驱动程序的标准程序是什么?

您需要通过 JdbcProfile 提取 Slick 配置文件。这将摆脱您已确定为问题的特定于 Oracle 的部分。

听起来您的应用程序相当大。在那种情况下,通常(根据我的经验)将 Slick 配置文件作为 class 或特征的参数,然后在您知道它是什么时传入特定配置文件。

例如(使用 Essential Slick 中的示例代码)我们可以说我们的应用程序配置文件必须具有 JdbcProfile:

import slick.jdbc.JdbcProfile

trait Profile {
  val profile: JdbcProfile
}

然后,对于数据库代码的每个模块,我们导入配置文件API:

trait DatabaseModule1 { self: Profile =>
  import profile.api._

  // Write database code here
}

注意抽象 profile.api._ 导入如何替换特定数据库 slick.jdbc.OracleProfile.api._

如果你有很多模块,你可以将它们组合成一个案例class:

class DatabaseLayer(val profile: JdbcProfile) extends
  Profile with
  DatabaseModule1 with
  DatabaseModule2

最后,在程序的边缘,您可以决定使用什么配置:

object Main extends App {

  // At this point, you can make a test and decide which specific
  // database you want to use. Here I'm saying it's always H2:
  val databaseLayer = new DatabaseLayer(slick.jdbc.H2Profile)

  // You can now use methods in `databaseLayer`, 
  // or pass it to other modules in your system
}

这在以下内容中有进一步描述: