Question

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)
  }
}

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)
  }
}

then all the data is erased.

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?

Was it helpful?

Solution

Two choices.

Either create a session and keep it open. That can be done with a withSession scope lower on the call stack or db.createSession.

Or add ;DB_CLOSE_DELAY=-1 to the database url. That keeps the db alive as long as the vm runs.

See http://www.h2database.com/html/features.html#in_memory_databases

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top