问题
I have written this code to create a table and then insert few rows and print the number of rows inserted.
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
}
}
But when I run this code it fails with this exception
[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)
Also, is there a way to avoid nesting of futures?
回答1:
That's probably because your program ran to the end and tried to Future.cancel the running database operations resulting in the InterruptedException.
You can Await.result on the Future from populateFuture before running db.close.
val result = populateFuture.map { results =>
results.foreach(x => println(s"Number of rows inserted $x"))
}
Await.result(result, Duration.Inf)
来源:https://stackoverflow.com/questions/31062288/scala-slick-3-0-creating-table-and-then-inserting-rows