scala 3 笔交易

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30327617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 07:10:04  来源:igfitidea点击:

Slick 3 Transactions

scalaslick

提问by Bomgar

I'm confused by the way the slick 3 documentation describes transactions. I have slick 2 code that looks like this:

我对圆滑的 3 文档描述交易的方式感到困惑。我有看起来像这样的 2 段代码:

def doSomething(???) = DB.withTransaction { implicit session => 
    userDao.doSomething(???)
    addressDao.doSomething(???)
    contactDao.doSomething(???)
}

How can i span a transaction in slick 3?

如何在 slick 3 中跨越交易?

回答by Gregor Rayman

Please have a look at the documentation here http://slick.typesafe.com/doc/3.0.0/dbio.html#transactions-and-pinned-sessions

请查看这里的文档http://slick.typesafe.com/doc/3.0.0/dbio.html#transactions-and-pinned-sessions

The idea is that you wrap a sequence of IO operations into a transactionallylike shown in this example:

这个想法是你将一系列 IO 操作包装到transactionally这个例子中所示的类似中:

val a = (for {
   ns <- coffees.filter(_.name.startsWith("ESPRESSO")).map(_.name).result
   _ <- DBIO.seq(ns.map(n => coffees.filter(_.name === n).delete): _*)
} yield ()).transactionally

val f: Future[Unit] = db.run(a)

This way Slick still process all the operations reactively, but it runs them all in one transaction sequentially.

通过这种方式,Slick 仍然以被动方式处理所有操作,但它会在一个事务中按顺序运行所有操作。

So your example would look like this:

所以你的例子看起来像这样:

def doSomething(???) = (for {
  _ <- userDao.doSomething(???)
  _ <- addressDao.doSomething(???)
  _ <- contactDao.doSomething(???)
} yield()).transactionally

回答by panther

val dbAction = (
  for {
    user <- userTable.doSomething
    address <- addressTable.doSomething
    contact <- contactTable.doSomething
  } yield()
).transactionally

val resultFuture = db run dbAction

You just need to wrap your action into 'transactionally'. Slick would take care of running all wrapped DB actions as a transaction.

您只需要将您的操作包装成“事务性”。Slick 将负责将所有包装的 DB 操作作为事务运行。

Apart from the standard advantages of having a more reactive/functional/async wayof writing code, it allows couple of performance improvements. Like it can determine at runtime if multiple actions can use the same session or not. In Slick 2.0, whenever you use 'withTransaction' or 'withSession' that opens a new jdbc session while here it has potential to reuse the same.

除了具有更具反应性/功能性/异步的代码编写方式的标准优势外,它还可以提高性能。就像它可以在运行时确定多个操作是否可以使用同一个会话。在 Slick 2.0 中,每当您使用 'withTransaction' 或 'withSession' 打开一个新的 jdbc 会话时,它都有可能重用相同的会话。