Scala Slick 3.0创建表,然后插入行 [英] Scala Slick 3.0 Creating Table and then Inserting Rows
本文介绍了Scala Slick 3.0创建表,然后插入行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写此代码是为了创建一个表,然后插入几行并打印插入的行数。
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
。
在运行db.close
之前,您可以从populateFuture
在Future
上Await.result
。
val result = populateFuture.map { results =>
results.foreach(x => println(s"Number of rows inserted $x"))
}
Await.result(result, Duration.Inf)
这篇关于Scala Slick 3.0创建表,然后插入行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文