【问题标题】:Setting up Slick 3.xx to use different databases in different environments设置 Slick 3.xx 以在不同环境中使用不同的数据库
【发布时间】:2020-07-10 13:39:35
【问题描述】:

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

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

【问题讨论】:

    标签: database scala h2 slick


    【解决方案1】:

    您需要通过 JdbcProfile 抽象出 Slick 配置文件。这将消除您已确定为问题的特定于 Oracle 的部分。

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

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

    import slick.jdbc.JdbcProfile
    
    trait Profile {
      val profile: JdbcProfile
    }
    

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

    trait DatabaseModule1 { self: Profile =>
      import profile.api._
    
      // Write database code here
    }
    

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

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

    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
    }
    

    这在以下有进一步描述:

    【讨论】:

      猜你喜欢
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多