java - H2:生成插入脚本初始化脚本

标签 java spring integration-testing h2 spring-test

我有完整的 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/

相关文章:

java - 硬件麦克风控制

java - maven clean install 不从本地存储库中获取 jar

Java 和 MySQL - 排名

java - 阅读网站,就像用户使用 HttpComponents 看到的一样

java - 在组件构造函数上使用 `@Lazy` 等于注释每个参数吗?

springfox 不能与 spring-boot-admin-server 一起使用

java - 表单验证失败时填充模型的最佳方法?

c++ - 如何在 Qt 中获取指向弹出对话框的指针,这会阻塞 QTest 中的 UI 线程

c# - 单元测试和集成测试之间的界限在哪里(例如)?

ruby-on-rails - rspec 集成/请求测试中的设计 View 未包含查看帮助器方法?