Scala Slick 3.0 创建 Table 然后插入行

Scala Slick 3.0 Creating Table and then Inserting Rows

我写了这段代码来创建一个 table 然后插入几行并打印插入的行数。

package com.example

import tables._
import scala.concurrent.{Future, Await}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import slick.backend.DatabasePublisher
import slick.driver.H2Driver.api._

object Hello {
  def main(args: Array[String]): Unit = {
    val db = Database.forConfig("h2mem1")
    try {
      val people = TableQuery[Persons]
      val setupAction : DBIO[Unit] = DBIO.seq(
        people.schema.create
        )
      val setupFuture : Future[Unit] = db.run(setupAction)

      setupFuture.flatMap { _ => 
        val populateAction: DBIO[Option[Int]] = people ++= Seq(
            (1, "test1", "user1"),
            (2, "test2", "user2"),
            (3, "test3", "user3"),
            (4, "test4", "user4")
          )

        val populateFuture : Future[Option[Int]] = db.run(populateAction)

        populateFuture.map {results =>
          results.foreach(x => println(s"Number of rows inserted $x"))
        }
      }


    } finally db.close
  }
}

但是当我运行这段代码时,它失败了,出现了这个异常

[info] Loading project definition from/Users/abhi/ScalaProjects/SlickTest2/project
[info] Set current project to SlickTest2 (in build file:/Users/abhi/ScalaProjects/SlickTest2/)
[info] Running com.example.Hello RandomUtils warning: InterruptedException
java.lang.InterruptedException
    at java.lang.Object.wait(Native Method)
    at java.lang.Thread.join(Thread.java:1253)
    at org.h2.util.RandomUtils.getSecureRandom(RandomUtils.java:50)
    at org.h2.util.RandomUtils.getSecureBytes(RandomUtils.java:139)
    at org.h2.engine.User.setUserPasswordHash(User.java:49)

还有,有没有办法避免期货嵌套?

那可能是因为你的程序运行结束并试图Future.cancel运行数据库操作导致InterruptedException

您可以在 populateFuture Future 运行 db.close 之前 Await.result

val result = populateFuture.map { results =>
  results.foreach(x => println(s"Number of rows inserted $x"))
}

Await.result(result, Duration.Inf)