How can I provide a relative path for H2 database file, using hibernate under Tomcat?
-
29-09-2019 - |
Question
I have a setup which must be fairly common: I have an H2 db, with a db file. I'm using the db in standalone mode. Hibernate provides access to db and I've deployed my code into Tomcat.
The problem is: I could not find a nice way of simply putting the db file into the war
and providing a relative path in hibernate config file.
At the moment, I have to use a path to c://whatever_db_file_container_dir/dbname
in hibernate config.
This stops me from deploying a zero config web app. Is there a way of turning this setup into a self containing zero configuration package?
Solution
Currently, H2 doesn't support databases in the classpath (there is a feature request for it, but it's not yet implemented). But this would only work for read-only databases. Unfortunately, H2 also doesn't support system properties in the database URL yet.
However, Hibernate supports Programmatic configuration. I am not sure how to get the directory of the web application in Tomcat, but I know about catalina.home and catalina.base. So when starting your application, get value of the catalina.home
system property, and set the Hibernate system property with the database URL accordingly. I didn't try myself, but this is how it should work.
OTHER TIPS
If you do not want to wait for the feature implemented you can set H2 (or HSQL, derby) url dynamically in your code. Check http://www.jvmhost.com/spring-hosting for code example.