如何使用环境变量配置Hibernate

Nat*_*ake 8 postgresql configuration hibernate heroku

所以我想在heroku上部署我的java应用程序.部署后,它会设置一个环境变量DATABASE_URL.我想用它作为我的hibernate网址.我目前有hibernate.cfg.xml,并在那里设置了url jdbc:postgresql:// localhost:port/db.如何将其更改为DATABASE_URL?

Ken*_*han 12

其中一种方法是使用的setProperty(字符串propertyName的,字符串值)配置,明确覆盖的价值hibernate.connection.url创造的SessionFactory之前.

要获取环境变量,可以使用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();
Run Code Online (Sandbox Code Playgroud)

  • 您可能需要调整从System.getenv("DATABASE_URL")返回的字符串. (2认同)

kdo*_*teu 12

我在java本身没有编程任何编程的情况下搜索了很多其他解决方案.我得出了以下结论

<?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>
Run Code Online (Sandbox Code Playgroud)

我用以下vmargs启动我的应用程序:

-Dhibernate_username=test-Dhibernate_password=testpassword -Dhibernate_db_host=localhost -Dhibernate_db_name=test -Dhibernate_show_sql=true
Run Code Online (Sandbox Code Playgroud)

我将此解决方案发布到这个旧帖子,因为我在一个旧的论坛帖子(Google Search Side 3+ ^^)中找到了这个.我认为这非常有用.