小编典典

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

mysql

在我的应用程序中,我正在使用hibernate模式,以将a与数据库连接并创建会话。这是我的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>

但是,当我尝试db.property file使用this
读取数据库配置属性时hibernate.cfg.xml,它显示了Exception,这是我的另一个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

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


阅读 308

收藏
2020-05-17

共1个答案

小编典典

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);
2020-05-17