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

≯℡__Kan透↙ 提交于 2019-12-20 14:41:48

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/15975339/package-and-use-embedded-database-h2-db-file-inside-a-jar

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