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.
Syntax. Following is the basic syntax of INSERT INTO statement. INSERT INTO tableName { [ ( columnName [,...] ) ] { VALUES { ( { DEFAULT | expression } [,...] ) }
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.
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!
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With