在 Slick 3 的单个事务中更新多行。1.x

Updating multiple rows in a single transaction in Slick 3.1.x

假设 table table1 具有三列 col1col2col3。另外,假设我需要根据 col2 的值更新 col1。例如,使用以下 SQL 语句

update table1 set col1=111 where col2=222

假设我必须更新 1000 次 table1 并且我有以下信息 Seq:

case class Table1 (col1: Int, col2: Int, col3: Int)
val list = Seq(Table1(111,222,333),Table1(111,333,444), .... )

在 Slick 3.1.x 中更新 1000 行的最佳方法是什么?是否可以 运行 使用 foreach 的批处理语句?

 val action = table1.foreach(....)

您可以使用 DBIO.sequence 构建要执行的操作列表,如下所示:

db.run(DBIO.sequence(list.map(l => ???)))

这是一个更完整的例子:

import scala.concurrent.Await
import scala.concurrent.duration.Duration
import slick.driver.H2Driver.api._


object main {

    // The class and corresponding table
    case class Thing (id: String, col1: Int, col2: Int)
    class Things(tag: Tag) extends Table[Thing](tag, "things") {
        def id = column[String]("id", O.PrimaryKey)
        def col1 = column[Int]("col1")
        def col2 = column[Int]("col2")

        def * = (id, col1, col2) <> ((Thing.apply _).tupled, Thing.unapply)
    }

    val things = TableQuery[Things]


    def main(args: Array[String]) {

        val db = Database.forConfig("h2mem1")

        try {

            // Create schema
            Await.result(db.run(things.schema.create), Duration.Inf)

            // Insert some things for testing
            Await.result(db.run(DBIO.seq(
                things += Thing("id4", 111, 111),
                things += Thing("id5", 222, 222),
                things += Thing("id6", 333, 333)
            )), Duration.Inf)

            // List of things to update
            val list = Seq(Thing("id1", 111, 112), Thing("id2", 222, 223), Thing("id3", 333, 334))

            // ----- The part you care about is here -----
            // Create a list of Actions to update
            val actions = DBIO.sequence(list.map(current => {

                // Whatever it is you want to do here
                things.filter(_.col1 === current.col1).update(current)
            }))

            // Run the actions
            Await.result(db.run(actions), Duration.Inf).value

            // Print out the results
            val results = Await.result(db.run(things.result), Duration.Inf)
            println(results)


        } 
        finally db.close
    }
}

输出具有更新的 col2 值:

Vector(Thing(id1,111,112), Thing(id2,222,223), Thing(id3,333,334))