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

梦想与她 提交于 2019-12-03 03:02:45

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!