Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

H2 in-memory database initialization with data

I'm using H2 with Hibernate to generate in-memory DB on the fly for unit-testing. I managed to create the DB successfully, and everything is working ok. But I have an issue I don't know how to approach. I need to load reference data to the DB for testing prior to the execution of the tests. I have this data sored as a SQL insert's file which I need to run only once in real time envirnemnt, however, because the DB is generated every time from scratch I need to figure out how to insert the data on runtime. The data is quite simple, it's countries lists, states list, etc. Whats the best way to do it ?

btw, everything is working underneath Spring framework.

like image 739
stdcall Avatar asked Nov 22 '11 21:11

stdcall


People also ask

How do I add data to my H2 database?

Syntax. Following is the basic syntax of INSERT INTO statement. INSERT INTO tableName { [ ( columnName [,...] ) ] { VALUES { ( { DEFAULT | expression } [,...] ) }

Is H2 A in-memory database?

H2 is an embedded, open-source, and in-memory database. It is a relational database management system written in Java. It is a client/server application. It stores data in memory, not persist the data on disk.

Does H2 automatically create tables?

Error : Table is not created automatically in H2 embedded db or I'm unable to see the tables. Usually, the table's are created but the URL used in H2 GUI Console is wrong. In the browser, change the database URL to jdbc:h2:mem:testdb (Shown in the screen below). You should be good to go!


2 Answers

For your tests you could execute an init script on creation of the connection.

http://www.h2database.com/html/features.html#execute_sql_on_connection

like image 114
Udo Held Avatar answered Sep 28 '22 11:09

Udo Held


From the question tags I see you're using Hibernate. You can add a file named "import.sql" to your classpath (i.e. in src/main/resources if you're using a Maven project layout).

From Spring documentation

In addition, a file named import.sql in the root of the classpath will be executed on startup if Hibernate creates the schema from scratch (that is if the ddl-auto property is set to create or create-drop). This can be useful for demos and for testing if you are careful, but probably not something you want to be on the classpath in production. It is a Hibernate feature (nothing to do with Spring).

like image 36
otonglet Avatar answered Sep 28 '22 09:09

otonglet