在Slick 3.1.x中更新单个事务中的多个行

时间:2016-12-11 21:18:44

标签: scala slick slick-3.0

假设表格table1有三列col1col2col3。另外,假设我需要根据col1的值更新col2。例如,使用以下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(....)

1 个答案:

答案 0 :(得分:5)

您可以使用li, li.red li { color: black } li.red, li.red li.red { color: red }构建要执行的操作列表,如下所示:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>    
<div id="content2">
  <div>
    <div>
      <p>Some Text</p>
      <p>Some More Text</p>
      <div>Random Div</div>
      <ul>
        <li>Bob</li>
        <li>Sally
          <ul>
            <li>Car</li>
            <li>Boat</li>
            <li>Bike
              <ul>
                <li>Red</li>
                <li>Green</li>
                <li>Blue</li>
              </ul>
            </li>
          </ul>
        </li>
        <li>Larry</li>
        <li>Mo</li>
      </ul>
    </div>
  </div>
</div>

这是一个更完整的例子:

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
    }
}