我编写了这段代码来创建一个表,然后插入几行并打印插入的行数。
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)
另外,有没有办法避免期货嵌套?
答案 0 :(得分:1)
这可能是因为您的程序运行到最后并尝试Future.cancel
正在运行的数据库操作导致InterruptedException
。
在Await.result
运行Future
之前,您可以populateFuture
db.close
{/ 1}}。
val result = populateFuture.map { results =>
results.foreach(x => println(s"Number of rows inserted $x"))
}
Await.result(result, Duration.Inf)