简体   繁体   English

H2内存数据库初始化与数据

[英]H2 in-memory database initialization with data

I'm using H2 with Hibernate to generate in-memory DB on the fly for unit-testing. 我正在使用H2和Hibernate来动态生成内存数据库以进行单元测试。 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. 我需要在执行测试之前将参考数据加载到DB进行测试。 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. 我把这个数据作为SQL插件的文件存储,我需要实时运行一次envirnemnt,但是,因为每次从头开始生成数据库我需要弄清楚如何在运行时插入数据。 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. 顺便说一句,一切都在Spring框架下工作。

For your tests you could execute an init script on creation of the connection. 对于测试,您可以在创建连接时执行init脚本。

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

From the question tags I see you're using Hibernate. 从问题标签我看到你正在使用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). 您可以将名为“import.sql”的文件添加到类路径中(例如,如果您使用的是Maven项目布局,则在src / main / resources中)。

From Spring documentation 从Spring文档

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). 此外,如果Hibernate从头开始创建模式(即ddl-auto属性设置为create或create-drop),则在启动时将在启动时执行类路径根目录中名为import.sql的文件。 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). 它是一个Hibernate功能(与Spring无关)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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