如何使用环境变量配置Hibernate

10

我想在Heroku上部署我的Java应用。一旦部署完成,它会设置一个名为DATABASE_URL的环境变量。我想将其用作Hibernate的URL。我目前有一个hibernate.cfg.xml文件,在其中设置了类似jdbc:postgresql://localhost:port/db这样的URL。如何更改以使用DATABASE_URL?

5个回答

19

我进行了很多搜索,希望找到另一种不需要在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>

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

-Dhibernate_username=test -Dhibernate_password=testpassword -Dhibernate_db_host=localhost -Dhibernate_db_name=test -Dhibernate_show_sql=true

我将这个解决方案发布到这篇旧帖子中,因为我在一个旧的论坛帖子中发现了它(Google搜索第3页+^^)。我认为这非常有用。


为什么我们需要将它们作为VM参数传递而不是只在环境变量中设置它们? - alex
1
在我们的用例中,Hibernate配置文件被打包在一个JAR文件中。对于我们的客户来说编辑这些文件有点繁琐。这就是为什么我们将它们打包在VM参数中的原因,这样更容易配置。 - kdoteu
谢谢对旧话题的回复!是否有可能设置成您所拥有的方式,但是不使用VMargs而是使用环境变量? - alex

19

其中一种方法是使用ConfigurationsetProperty(String propertyName, String value)来显式覆盖创建SessionFactory之前hibernate.connection.url的值。

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

非常感谢,不过我几分钟前就发现了解决方法。 :) - Nathan Drake
请告诉我是否可以,祝你好运 :) - Ken Chan
2
你可能需要调整从 System.getenv("DATABASE_URL") 返回的字符串。 - Jesper J.

1

希望这能帮到您,

我正在使用Jboss AS 5.x的HSQL DB和Hibernate动态创建表,并使用以下*.cfg.xml文件。

该文件使用$JBOSS_HOME作为环境变量。

<?xml version="1.0" encoding="UTF-8"?>

    <session-factory>

            <!-- Database connection settings -->

            <property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
            <property name="connection.url">jdbc:hsqldb:$JBOSS_HOME/server/test/data/hypersonic/localDB</property>
            <property name="connection.username">sa</property>

            <property name="connection.password"></property>

            <!-- JDBC connection pool (use the built-in) -->
            <property name="connection.pool_size">1</property>

            <!-- SQL dialect -->
            <property name="dialect">org.hibernate.dialect.HSQLDialect</property>

            <!-- Enable Hibernate's automatic session context management -->
            <property name="current_session_context_class">thread</property>

            <!-- Disable the second-level cache -->
            <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

            <!-- Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
            <!-- Drop and re-create the database schema on startup -->

            <property name="hbm2ddl.auto">update</property>
            <!--  Mapping files  -->
            <mapping resource="friends_presence_log.hbm.xml" />
            <mapping resource="profileuuid.hbm.xml" />
    </session-factory>

所以,如果你想在Jboss配置中使用环境变量,那么你可以像平常一样使用它,然后由内部的hibernate.jar实用程序获取,就像在Java程序中一样正常地获取连接或其他内容。


使用$VAR不会被解析。 - Jamie-505

1
如果您使用像Gradle这样的构建工具,可以按照以下方式使用由@...@括起来的占位符:
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
   <session-factory>
      <property name = "hibernate.dialect">
         @db_dialect@
      </property>

      <property name = "hibernate.connection.driver_class">
         @db_driver@
      </property>

      <!-- Assume test is the database name -->

      <property name = "hibernate.connection.url">
         @db_url@
      </property>

      <property name = "hibernate.connection.username">
         @db_user@
      </property>

      <property name = "hibernate.connection.password">
         @db_password@
      </property>

      <!-- Cannot use anything other than "validate" in production. --> 
      <property name="hibernate.hbm2ddl.auto">validate</property>

      <!-- Connection pooling -->
      <property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
      <property name="hibernate.c3p0.min_size">1</property>
      <property name="hibernate.c3p0.max_size">500</property>
      <property name="hibernate.c3p0.timeout">120</property>
      <property name="hibernate.c3p0.max_statements">1024</property>

      <!-- Your mappings -->
   </session-factory>
</hibernate-configuration>

然后在 build.gradle 文件中,你会看到类似以下的内容:

def db_driver = System.getenv('MYAPP_DB_DRIVER')
def db_url = System.getenv('MYAPP_DB_URL')
def db_dialect = System.getenv('MYAPP_DB_DIALECT')

processResources {
    filesMatching(['**/*.xml', '**/*.properties', '**/*.json']) {
        filter ReplaceTokens, tokens: [
            'db_driver': db_driver,
            'db_url': db_url,
            'db_dialect': db_dialect,
        ]
    }
}

0

这是一个两步回答:

  1. 所有Hibernate配置属性都可以通过Java系统属性-Dhibernate_property=value进行覆盖 - https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/session-configuration.html#configuration-programmatic
  2. 如果您没有轻松访问带有脚本的Java命令行,则可以使用JAVA_TOOL_OPTIONS环境变量来插入Hibernate配置属性 - https://docs.oracle.com/javase/8/docs/technotes/guides/troubleshoot/envvars002.html

例如,这是我在docker-compose文件中设置的环境变量,用于在运行时打开或关闭Hibernate的SQL日志记录行为。

  mybackend:
    image: dkr.myrepo.com/my-backend
    environment:
      - JAVA_TOOL_OPTIONS=-Dhibernate.show_sql=true -Dhibernate.format_sql=true 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接