So i want to deploy my java app on heroku. Once deployed it sets an environment variable DATABASE_URL. I want to use that as my url for hibernate. I currently have hibernate.cfg.xml and there i set the url jdbc:postgresql://localhost:port/db like this . How can i change it to take DATABASE_URL?
One of the ways is to use setProperty(String propertyName, String value) of Configuration to explicitly override the value of hibernate.connection.url
before creating the SessionFactory.
To get the environment variables , you can use System.getenv(String name) .
/**Load the hibernate.cfg.xml from the classpath**/
Configuration cfg = new Configuration();
cfg.setProperty("hibernate.connection.url", System.getenv("DATABASE_URL"));
SessionFactory sessionFactory = cfg.buildSessionFactory();
I searched a lot for another solution without programming anything in java itself. I came to the following conclusion.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.check_nullability">false</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.username">${hibernate_username}</property>
<property name="hibernate.connection.password">${hibernate_password}</property>
<property name="hibernate.connection.url">jdbc:postgresql://${hibernate_db_host}/${hibernate_db_name}</property>
<property name="hibernate.search.autoregister_listeners">false</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">${hibernate_show_sql}</property>
</session-factory>
</hibernate-configuration>
And I start my application with following vmargs:
-Dhibernate_username=test -Dhibernate_password=testpassword -Dhibernate_db_host=localhost -Dhibernate_db_name=test -Dhibernate_show_sql=true
I post this solution to this old Post, because I found this in an old forum post (Google Search Side 3+ ^^). And I think this is very useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With