简体   繁体   中英

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.

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 (ie 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM