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 possi
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.