2
我是一个Slick初学者,只是试验Slick 3.0 RC1。在我的第一个项目中,我想将文本文件中的数据导入到各种表格中。由于数据在一个事务中的文件中,因此整个导入应该按顺序发生。如何使用DBIO.sequence和避免StackOverflowError
我试着创建一个迭代器的动作,并将它们包装在一个DBO.sequence中。
问题是,当行数很大时,导入将失败并带有StackOverflowError。很明显,我误解了如何使用Slick来做我想做的事情。如何将大量数据链接到一个事务中有更好的方法吗?
这里是我的代码的简化版本,我不是从文件中读取数据,而是从Range中“导入”数字。甚至是桌子XS,甚至是桌子YS。
val db = Database.forConfig("h2mem1")
try {
class Xs(tag: Tag) extends Table[(Long, String)](tag, "XS") {
def id = column[Long]("ID", O.PrimaryKey)
def name = column[String]("NAME")
override def * : ProvenShape[(Long, String)] = (id, name)
}
class Ys(tag: Tag) extends Table[(Long, String)](tag, "YS") {
def id = column[Long]("ID", O.PrimaryKey)
def name = column[String]("NAME")
override def * : ProvenShape[(Long, String)] = (id, name)
}
val xs = TableQuery[Xs]
val ys = TableQuery[Ys]
val setupAction = DBIO.seq((xs.schema ++ ys.schema).create)
val importAction = DBIO.sequence((1L to 100000L).iterator.map { x =>
if (x % 2 == 0) {
xs +=(x, x.toString)
} else {
ys +=(x, x.toString)
}
})
val f = db.run((setupAction andThen importAction))
Await.result(f, Duration.Inf)
} finally {
db.close
}