gpt4 book ai didi

java - 如何在 hibernate 中使用属性文件读取数据库配置参数

转载 作者:可可西里 更新时间:2023-11-01 07:14:45 24 4
gpt4 key购买 nike

在我的应用程序中,我使用 hibernate 来连接数据库并创建 session 。这是我的 hibernate.cfg.xml 文件。还行吧。它工作正常。

<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/country</property>
<property name="connection.username">root</property>
<property name="connection.password">password</property>

</session-factory>

</hibernate-configuration>

但是当我尝试使用 hibernate.cfg.xml 使用 db.property 文件 读取数据库配置属性时,它显示异常,这是我的另一个 hibernate.cfg.xml 文件

<util:properties id="db" location="classpath:db.properties" />

<hibernate-configuration>

<session-factory>
<!-- Database connection settings -->
<property name="driverClassName" value="#{db['driverClassName']}"></property>
<property name="url" value="#{db['url']}"></property>
<property name="username" value="#{db['username']}"></property>
<property name="password" value="#{db['password']}"></property>

</session-factory>

</hibernate-configuration>

这是错误

 org.dom4j.DocumentException: Error on line 8 of document  : The prefix "util" for       element "util:properties" is not bound. Nested exception: The prefix "util" for element   "util:properties" is not bound.
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2155)

这是我的名为 db.properties 的属性文件

driverClassName=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/country

username=root

password=password

有什么问题吗?如何正确地做到这一点

最佳答案

util:properties 不是可在 hibernate.cfg.xml 文件中使用的有效标记。如果您想将所有数据库配置详细信息放在一个属性文件中,那么您可以将它们放在 hibernate.properties 文件中,并从 hibernate.cfg.xml 文件中删除它们。这样,数据库详细信息将保存在属性文件中。

如果你想维护一个单独的文件而不是使用 hibernate.properties 文件,那么你可以试试这个:

java.util.Properties properties = new Properties();
properties.load(new FileInputStream("db.properties"));

Configuration configuration = new Configuration();

configuration.configure("hibernate.cfg.xml").addProperties(properties);;

ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();

SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);

关于java - 如何在 hibernate 中使用属性文件读取数据库配置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25684785/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com