简体   繁体   English

将嵌入式 h2 数据库添加到可执行文件 jar

[英]Add an embedded h2 database to an executable jar

I am writing a small Java application that reads/writes data to an embedded h2 database.我正在编写一个小型 Java 应用程序,它将数据读/写到嵌入式 h2 数据库。 For dev purposes, I would like to add the database to the jar file generated from my application.出于开发目的,我想将数据库添加到从我的应用程序生成的 jar 文件中。

The use case is: A user only gets the jar file delivered and is able to read and write data to the database embedded within it.用例是:用户仅获得交付的 jar 文件,并且能够读取和写入其中嵌入的数据库的数据。

Is there a way to achieve this?有没有办法做到这一点?

Notes: I am developing the app in IntelliJ and building the project with maven注意:我正在 IntelliJ 中开发应用程序并使用 maven 构建项目

You seem to be asking two separate questions:您似乎在问两个不同的问题:

  • How to bundle the H2 Database Engine product within my JAR file?如何在我的JAR文件中捆绑H2 数据库引擎产品?
  • How to bundle a database with my JAR file?如何将数据库与我的 JAR 文件捆绑在一起?

Bundling the database engine library绑定数据库引擎库

The first is easy.第一个很容易。 Tell your dependency management and build tools such as Maven or Gradle to include H2.告诉您的依赖管理和构建工具,例如MavenGradle包括 H2。 That is the job of such tools, to download and install a copy of such libraries.这就是此类工具的工作,下载并安装此类库的副本。

For Maven, see the Cheat Sheet page for the current Maven dependency XML fragment to include in yourPOM .对于 Maven,请参阅备忘页面以获取当前 Maven 依赖项 XML 片段以包含在您的POM中。

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
</dependency>

Bundling a database绑定数据库

Regarding the issue of bundling a database within your JAR, study the Comments on your Question.关于在 JAR 中捆绑数据库的问题,请研究您的问题的评论。 They note that you cannot write into your JAR file at deployment runtime.他们指出,您无法在部署运行时写入 JAR文件。 Your database must live outside your JAR file.您的数据库必须位于 JAR 文件之外 Various OS es have dedicated places in their file system for apps to write such data files.各种操作系统在其文件系统中都有专门的位置供应用程序写入此类数据文件。

One comment suggests that your code look for a database within your JAR.一条评论建议您的代码在 JAR 中查找数据库。 If found, copy that database to another folder outside the JAR.如果找到,将该数据库复制到 JAR 之外的另一个文件夹。 Then proceed using that externalized copy.然后继续使用该外部化副本。

This approach could work.这种方法可以奏效。 But I would choose schema migration instead.但我会选择模式迁移

Schema migration架构迁移

With schema migration , at runtime in deployment you create a new database and then run a series of SQL scripts.使用模式迁移,在部署运行时创建一个新数据库,然后运行一系列 SQL 脚本。 Those scripts execute DDL commands such as creating tables.这些脚本执行DDL命令,例如创建表。 And those scripts run DML commands to create rows as needed.这些脚本运行DML命令以根据需要创建行。

You have a choice of schema migration tools to locate, manage, and run those scripts.您可以选择架构迁移工具来定位、管理和运行这些脚本。 I prefer Flyway , though Liquibase is also popular.我更喜欢Flyway ,虽然Liquibase也很受欢迎。 Others may exist as well.其他人也可能存在。

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

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