Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I configure Hibernate with environment variable

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?

like image 314
Nathan Drake Avatar asked Dec 01 '11 23:12

Nathan Drake


2 Answers

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();
like image 182
Ken Chan Avatar answered Nov 02 '22 15:11

Ken Chan


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.

like image 30
kdoteu Avatar answered Nov 02 '22 13:11

kdoteu