我需要将 Java Web 应用程序的所有设置集中在一个 .properties 文件中。我仍然可以使用 hibernate.cfg.xml 将映射添加到实体类,但我需要将所有数据库设置和自定义路径保存在一个 .properties 文件中。
最初我将配置保存在 hibernate.cfg.xml 中,如下所示....
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">my jdbc connection</property>
<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="connection.username">user</property>
<property name="connection.password">password</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.current_session_context_class">managed</property>
<mapping class="myEntityClass"/>
</session-factory>
</hibernate-configuration>
现在我想将“connection.url”、“connection.username”和“connection.password”移动到我自己的 .properties 文件中。创建我的 hibernate 配置类的代码来自。
new AnnotationConfiguration().configure();
到
new AnnotationConfiguration()
.setProperty("connection.url", databaseUrl)
.setProperty("connection.username", databaseUser)
.setProperty("connection.password", databasePassword)
.configure();
这在概念上看起来很简单。不幸的是,当我尝试使用与以前的配置一起工作的 Hibernate Session 时,出现以下错误。
The user must supply a JDBC connection
有什么想法吗?在我看来,当 Hibernate 发现 hibernate.cfg.xml 文件中缺少这些属性时,它假定所有设置都将手动添加并完全忽略 xml。
最佳答案
来自 Hibernate 引用文档:
3.3. JDBC connections
[...]
The following is an example
hibernate.properties
file for c3p0:hibernate.connection.driver_class = org.postgresql.Driver hibernate.connection.url = jdbc:postgresql://localhost/mydatabase hibernate.connection.username = myuser hibernate.connection.password = secret hibernate.c3p0.min_size=5 hibernate.c3p0.max_size=20 hibernate.c3p0.timeout=1800 hibernate.c3p0.max_statements=50 hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
根据您的需要对其进行调整,将 hibernate.properties
放在类路径的根目录中(并从 hibernate.cfg 中删除等效条目.xml
作为 XML 配置文件覆盖属性)。所以实际上不需要更改以下行:
new AnnotationConfiguration().configure();
当然,除非您真的想要程序化配置。
但是从你的问题的主体来看,移动到 .properties
文件是另外一回事,你可以依赖 Hibernate:从 hibernate 移动相关属性.cfg.xml
到 hibernate.properties
。
关于java - 以编程方式在 Hibernate 中设置数据库 url/用户/密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3168027/