Kshitiz Sharma
Kshitiz Sharma

Reputation: 18597

How to load a H2 database into memory?

I have written a set of unit tests using H2 in embedded mode. Whatever changes tests make to DB stay there.

I know that the recommended approach is to create a blank in-memory database and create the schema when opening the connection.

However I am looking for an alternative approach. I would like to -

  1. Initialize an in memory database with an embedded database file.
  2. Or use embedded db in a way that all the changes are discarded as soon as the connection is closed.

How can I achieve this?

Upvotes: 3

Views: 1712

Answers (2)

Usagi Miyamoto
Usagi Miyamoto

Reputation: 6289

I use SQL scripts that create tables and other objects and/or populate them, and run these scripts at the beginning of the application.

One could also create a copy of the populated on-disk DB, package it into a ZIP/JAR archive, and open it read only, to be used to recreate and populate the in-memory DB.

Upvotes: 0

jschiavon
jschiavon

Reputation: 527

What I do in cases similar to this is to write the SQL script that creates the database and populates the tables. Then the application applies a database migration using Flyway DB.

Other possibilities are to create the database and load the tables from CSV files. The other would be to create the database with a different application and create a file with the SCRIPT command to create a backup. Your main application would have to run the RUNSCRIPT command to restore the database.

Upvotes: 1

Related Questions