如何使用环境变量配置 Hibernate [英] How can I configure Hibernate with environment variable

查看:26
本文介绍了如何使用环境变量配置 Hibernate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

其中一种方式是使用 setProperty(String propertyName, String value) of Configuration 在创建 SessionFactory 之前显式覆盖 hibernate.connection.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.

要获取环境变量,您可以使用 System.getenv(String name) .

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();

这篇关于如何使用环境变量配置 Hibernate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆