应该如何配置Slick在会话之间持久化表? [英] How should one configure Slick to persist tables between sessions?
问题描述
我在设置Slick 2.0.2时遇到了一些问题。在一个会话中执行的任何配置在下一个会话中丢失。例如,在第一个会话中,我创建表并添加三个人:
I have experienced some issues while setting up Slick 2.0.2. Any configuration that I do in one session is lost in the next. For example, in the first session, I create the table and add three people:
// H2 in-memory database
lazy val db = Database.forURL("jdbc:h2:mem:contacts", driver="org.h2.Driver")
// Contacts table
lazy val contacts = TableQuery[ContactsSchema]
// Initial session
db withSession { implicit session =>
contacts.ddl.create
// Inserts sample data
contacts += Person("John", "123 Main street", 29)
contacts += Person("Greg", "Neither here nor there", 40)
contacts += Person("Michael", "Continental U.S.", 34)
// Successfully retrieves data
contacts foreach { person =>
println(person)
}
}
到这一点。输出重复我添加的三个人。当我开始一个新的会话,我开始遇到问题。
All is well up to this point. The output repeats the three people whom I added. When I start a new session, I start to experience issues.
// New session in which the previous data is lost
db withSession { implicit session =>
contacts foreach { person =>
println(person)
}
}
创建一个 org.h2.jdbc.JdbcSQLException:表CONTACTS未找到
异常。如果我编辑如下
The above block creates a org.h2.jdbc.JdbcSQLException: Table "CONTACTS" not found
exception. If I edit as follows
db withSession { implicit session =>
contacts.ddl.create
contacts foreach { person =>
println(person)
}
}
数据已删除。
我看到 Slick的Scalatra指南使用类似于我的配置。我究竟做错了什么?如何让数据在会话之间保持?
I see that the Scalatra guide to Slick uses a similar configuration to mine. What am I doing wrong? How should I get the data to persist between sessions? Does the fact that I am using an in-memory database have anything to do with it?
推荐答案
有两个选择。
创建会话并保持打开。这可以通过调用堆栈或db.createSession上的withSession范围来实现。
Either create a session and keep it open. That can be done with a withSession scope lower on the call stack or db.createSession.
或者添加; DB_CLOSE_DELAY = -1
到数据库url。
Or add ;DB_CLOSE_DELAY=-1
to the database url. That keeps the db alive as long as the vm runs.
请参阅 http://www.h2database.com/html/features.html#in_memory_databases
这篇关于应该如何配置Slick在会话之间持久化表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!