Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Package and use embedded database (H2.db file) inside a Jar?

I'm using H2 embedded database for my application. I would like to contain everything the application needs in it's own Jar, including it's database if possible. My app does not need to create temp files or anything, so basically the user just runs the Jar.

Is it possible to embed a database inside a Jar, and be able to INSERT new records as well as just SELECT out?

EDIT: Just to clarify, I'm not looking to embed the H2 driver jar inside my distributable jar, I'm looking to embed the h2 database file (someDatabase.h2.db file) inside a Jar and still be able to write/read from that database.

like image 521
SnakeDoc Avatar asked Apr 12 '13 15:04

SnakeDoc


People also ask

How do I access my H2 memory database?

To access an in-memory database from another process or from another computer, you need to start a TCP server in the same process as the in-memory database was created. The other processes then need to access the database over TCP/IP or TLS, using a database URL such as: jdbc:h2:tcp://localhost/mem:db1 .

Is H2 an embedded database?

H2 is an embedded, open-source, and in-memory database. It is a relational database management system written in Java.


1 Answers

If you wish to embed the myDatabase.h2.db file inside the .jar, you can do so, but you'll have read-only access to the database. As .jar files are read-only, you can't modify them and therefore can't execute INSERT, DELETE or any DDL command.

That being said, below is an explanation on how to embed it read-only.

According to H2's documentation:

The JDBC URL "jdbc:h2:~/myDatabase" tells the H2 Engine to look for a database file named myDatabase.h2.db in the home directory of the current user.

The JDBC URL "jdbc:h2:file:/myDatabase" tells the H2 Engine to look for a database file named myDatabase.h2.db in the current directory (where the java program was executed).

If you embed the h2.db file inside a .jar, it is not accessible in a plain way. It is only accessible as a file inside a zip file.

In order to make H2 uset it, you have to use a zip as URL:

jdbc:h2:zip:~/data.zip!/test

See more in "Read Only Databases in Zip or Jar File".

When you embed the file as a resource in the jar, you may get it's relative url. Using...

MyClass.class.getClassLoader().getResource("myDatabase.h2.db")

...you'll get something like:

jar:file:/C:/folder1/folder2/myJar.jar!/myDatabase.h2.db

You can then manipulate it as a String and pass as JDBC URL connection to H2.

like image 71
acdcjunior Avatar answered Oct 16 '22 01:10

acdcjunior