我有完整的 h2 数据库,里面有很多数据。我想针对该数据启动集成测试。
问题 1: 是否可以从完整的 h2 数据库生成 *.sql 插入文件/脚本?
我已经按照 here 的描述尝试了 SCRIPT TO 'fileName'
.但它只生成 CREATE/ALTER TABLE/CONSTRAINT
查询,意味着创建没有数据的模式。
如果第一个问题的答案是“不可能”,那么:
问题 2:*.sql 插入文件是将初始数据集插入 h2 数据库以进行集成测试的唯一方法吗?
最佳答案
Question1: Is it possible to generate *.sql insert files/scripts from full h2 database?
我刚刚使用我的一个 H2 文件数据库进行了测试,结果导出同时导出了结构和数据。
我用 1.4.193
测试过H2 版本。
导出工作的两种方式:
SCRIPT
来自 H2 控制台的命令-
org.h2.tools.Script
来自命令行的工具。
1) 我首先测试了 org.h2.tools.Script
工具,因为我已经使用过它。
这是导出结构和数据的最小命令:
java -cp <whereFoundYourH2Jar> org.h2.tools.Script -url <url>
-user <user> -password <password>
哪里:
-
<whereFoundYourH2Jar>
是您拥有 h2.jar 库的类路径(我使用的是我的 m2 存储库)。 -
<url>
是你数据库的url -
<user>
是数据库的用户 -
<password>
数据库密码
你在org.h2.tools.Script
的官方帮助中有更多的细节。工具:
Creates a SQL script file by extracting the schema and data of a database.
Usage: java org.h2.tools.Script <options>
Options are case sensitive. Supported options are:
[-help] or [-?] Print the list of options
[-url "<url>"] The database URL (jdbc:...)
[-user <user>] The user name (default: sa)
[-password <pwd>] The password
[-script <file>] The target script file name (default: backup.sql)
[-options ...] A list of options (only for embedded H2, see SCRIPT)
[-quiet] Do not print progress information
See also http://h2database.com/javadoc/org/h2/tools/Script.html
2) 我用 SCRIPT
测试过来自 H2 控制台的命令。它也有效。
然而,SCRIPT
的结果命令可能会产生误导。
看官方文档:
If no 'TO fileName' clause is specified, the script is returned as a result set. This command can be used to create a backup of the database. For long term storage, it is more portable than copying the database files.
If a 'TO fileName' clause is specified, then the whole script (including insert statements) is written to this file, and a result set without the insert statements is returned.
您已经使用了 SCRIPT TO 'fileName'
命令。在这种情况下,整个脚本
(包括插入语句)被写入此文件,结果在 H2 控制台中,除了插入语句之外,您拥有所有内容。
例如,输入 SCRIPT TO 'D:\yourBackup.sql'
命令(或 Unix 友好目录,如果您使用它),然后打开文件,您将看到存在 SQL 插入。
如文档中所述,如果你想在H2控制台的输出结果中同时获取结构和插入语句,请不要指定TO
。争论。
只需输入:SCRIPT
.
Question2: Are *.sql insert files the only way to insert initial dataset into h2 db for integration tests?
正如长时间讨论的那样 :) 您可以使用 DBunit 数据集(其他解决方案)。
关于java - H2:生成插入脚本初始化脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41102406/