1

I am writing a small Java application that reads/writes data to an embedded h2 database. For dev purposes, I would like to add the database to the jar file generated from my application.

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.

Is there a way to achieve this?

Notes: I am developing the app in IntelliJ and building the project with maven

Shorty
  • 43
  • 4
  • Does this help? https://stackoverflow.com/questions/19150811/what-is-a-fat-jar – Abra Mar 29 '21 at 15:08
  • 4
    In general there's no way to update the contents of the jar from which the application is run, so I don't see that you'd be able to embed a (writable) database in a jar file. – James_D Mar 29 '21 at 15:24
  • What I do in similar situations is check if the database exists and is in the same folder as the Jar or a subfolder. If the database does not exist. I copy the initial database that is in the jar to the folder or subfolder that contains the jar. Or you can create the whole database using SQL statements once you see that it does not exist. – SedJ601 Mar 29 '21 at 18:25

1 Answers1

1

You seem to be asking two separate questions:

  • How to bundle the H2 Database Engine product within my JAR file?
  • How to bundle a database with my JAR file?

Bundling the database engine library

The first is easy. Tell your dependency management and build tools such as Maven or Gradle to include 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 your 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. They note that you cannot write into your JAR file at deployment runtime. Your database must live outside your JAR file. Various OSes 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. If found, copy that database to another folder outside the 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. Those scripts execute DDL commands such as creating tables. And those scripts run DML commands to create rows as needed.

You have a choice of schema migration tools to locate, manage, and run those scripts. I prefer Flyway, though Liquibase is also popular. Others may exist as well.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154