我开始使用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,除了使用弃用代码的答案。
答案 0 :(得分:8)
您正在寻找的光滑的驱动程序类是slick.driver.JdbcProfile
。
您可以通过激活器(github)获得正式的示例项目slick-multidb
。这是相关的代码:
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, U, C]): DBIO[U] =
q.result.head
}
客户代码:
val dao = new DAO(H2Driver)
import dao.driver.api._
db.run(dao.insert("foo", "bar"))