加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – Slick 3.0.0数据库agnostism

发布时间:2020-12-16 09:50:54 所属栏目:安全 来源:网络整理
导读:我开始使用Slick 3.0.0,我喜欢它简洁的语法.然而,我无法找到以数据库无关的方式使用它的方法. 在文档中提供的以下示例中:http://slick.typesafe.com/doc/3.0.0/gettingstarted.html 我希望能够以某种方式解耦所使用的数据库代码,并避免在我的代码中导入特定
我开始使用Slick 3.0.0,我喜欢它简洁的语法.然而,我无法找到以数据库无关的方式使用它的方法.

在文档中提供的以下示例中:http://slick.typesafe.com/doc/3.0.0/gettingstarted.html

我希望能够以某种方式解耦所使用的数据库代码,并避免在我的代码中导入特定数据库(即slick.driver.H2Driver.api._).

我试图通过使用蛋糕模式提供连接来摆脱它,但是“.result”成员当时不可用.

解决方法是导入slick.driver.JdbcDriver.api._,但它已被弃用,因此不应该是一个很好的起点.

有人找到了一种在数据库不可知和优雅的方式使用Slick 3.0.0的方法吗?

这个问题与“How to write database-agnostic Play application and perform first-time database initialization?”不远,但是那个问题主要集中在Slick 3.0.0上. Sadely提供的前一个问题的答案并不针对Slick 3.0.0,除了使用弃用代码的问题.

解决方法

你正在寻找的光滑的驱动程序类是slick.driver.JdbcProfile.

有一个官方的示例项目slick-multidb,你可以通过激活器(github)获得.这是相关的代码:

import scala.language.higherKinds
import slick.driver.JdbcProfile

/** All database code goes into the DAO (data access object) class which
  * is parameterized by a Slick driver that implements JdbcProfile.
  */
class DAO(val driver: JdbcProfile) {
  // Import the Scala API from the driver
  import driver.api._

  class Props(tag: Tag) extends Table[(String,String)](tag,"PROPS") {
    def key = column[String]("KEY",O.PrimaryKey)
    def value = column[String]("VALUE")
    def * = (key,value)
  }
  val props = TableQuery[Props]

  /** Create the database schema */
  def create: DBIO[Unit] =
    props.ddl.create

  /** Insert a key/value pair */
  def insert(k: String,v: String): DBIO[Int] =
    props += (k,v)

  /** Get the value for the given key */
  def get(k: String): DBIO[Option[String]] =
    (for(p <- props if p.key === k) yield p.value).result.headOption

  /** Get the first element for a Query from this DAO */
  def getFirst[M,U,C[_]](q: Query[M,C]): DBIO[U] =
    q.result.head
}

客户代码:

val dao = new DAO(H2Driver)
import dao.driver.api._
db.run(dao.insert("foo","bar"))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读