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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25684785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 00:55:06  来源:igfitidea点击:

How to read database configuration parameter using properties file in hibernate

javamysqlhibernate

提问by Killer

In my apps I am using hibernate, to connect a with database and create a session. this is my hibernate.cfg.xml file. This is ok. It working properly.

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

But when I try to read the DB configuration properties using db.property fileusing this hibernate.cfg.xml, it showing Exception, this is my another hibernate.cfg.xmlfile

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

this is the error

这是错误

 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)

this is my properties file named db.properties

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

driverClassName=com.mysql.jdbc.Driver

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

username=root

password=password

what is the problem is there? how to do that properly

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

采纳答案by Chaitanya

util:propertiesis not a valid tag to use in hibernate.cfg.xmlfile. If you want to place all the DB configuration details in a properties file then you can place them in hibernate.propertiesfile and remove those from hibernate.cfg.xmlfile. In this way the DB details will be maintained in properties file.

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

If you want to maintain a separate file instead of using hibernate.properties file then you can try this:

如果你想维护一个单独的文件而不是使用 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);

回答by hossein ketabi

try this code:

试试这个代码:

hibernate.properties

hibernate.properties

hibernate.connection.url=jdbc:mysql://localhost:3306/country
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.username=root
hibernate.connection.password=123

HibernateUtil.java

HibernateUtil.java

import java.util.Properties;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
    try {

        Properties dbConnectionProperties = new Properties();
        try {
            dbConnectionProperties.load(HibernateUtil.class.getClassLoader().getSystemClassLoader().getResourceAsStream("hibernate.properties"));
        } catch(Exception e) {
            e.printStackTrace();
            // Log
        }           

        return new AnnotationConfiguration().mergeProperties(dbConnectionProperties).configure("hibernate.cfg.xml").buildSessionFactory();          


    } catch (Throwable ex) {
        ex.printStackTrace();
//            throw new ExceptionInInitializerError(ex);
    }
    return null;
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}

}

hibernate.cfg.xml

休眠文件.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>

    <!-- Database connection settings -->

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

    <!-- SQL dialect -->
     <property name="dialect">org.hibernate.dialect.MySQLDialect</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">false</property>

    <property name="hibernate.hbm2ddl.auto">update</property>
    <!--<mapping class="net.viralpatel.hibernate.Employee"/>-->
    <!--<mapping class="net.viralpatel.hibernate.PersonEntity"/>-->
    <mapping class="mobin.FavaEmail.entities.PersonEntity"/>
    <mapping class="mobin.FavaEmail.entities.OrgEntity"/>
    <mapping class="mobin.FavaEmail.entities.User"/>


</session-factory>
</hibernate-configuration>

回答by Harikrishnan A

1) Hibernate configuration XML file: Hibernateconfig.cfg.xml

1)Hibernate配置XML文件:Hibernateconfig.cfg.xml

<!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.connection.driver_class"></property>
        <property name="hibernate.connection.url"></property>
        <property name="hibernate.connection.username"></property>
        <property name="hibernate.connection.password"></property>
        <property name="hibernate.connection.pool_size"></property>
        <property name="hibernate.dialect"></property>
        <property name="show_sql"></property>
        <property name="format_sql"></property>
        <property name="hbm2ddl.auto"></property>

        <mapping class="SourceFields"/>
    </session-factory>
</hibernate-configuration>

2) Hibernate properties file - config.properties

2) Hibernate 属性文件 - config.properties

hibernate.connection.driver_class=org.hsqldb.jdbcDriver
hibernate.connection.url=jdbc:hsqldb:hsql://localhost:9191/Register
hibernate.connection.username=username
hibernate.connection.password=password
hibernate.connection.pool_size=10
hibernate.dialect=org.hibernate.dialect.HSQLDialect
show_sql=true
format_sql=true
hbm2ddl.auto=update

3) Loading properties file:

3) 加载属性文件:

public static Properties propertyLoad() {
        Properties properties = null;
        if (properties == null) {
            properties = new Properties();
            try {
                properties.load(PropertiesUtil.class
                        .getResourceAsStream("/config.properties"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return properties;
    }

4) Creation of session factory:

4)创建会话工厂:

public class HibernateBaseDB {

    private static Properties properties = new Properties();

    public static SessionFactory getSessionFactory() {

        properties = PropertiesUtil.propertyLoad();
        Configuration configuration = new Configuration();

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

        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
                .applySettings(configuration.getProperties())
                .buildServiceRegistry();

        SessionFactory sessionFactory = configuration
                .buildSessionFactory(serviceRegistry);

        return sessionFactory;

    }

Here you can configure the DB credentials from properties file to xml file at run time and you can create session factory using the xml file. The xml file will be configured according to the credentials given in the properties file.

在这里,您可以在运行时将数据库凭据从属性文件配置为 xml 文件,并且您可以使用 xml 文件创建会话工厂。xml 文件将根据属性文件中提供的凭据进行配置。

You can call the static method of HibernateBaseDBclass, getSessionFactory(), wherever you need to create a session factory.

您可以在任何需要创建会话工厂的地方调用HibernateBaseDB类的静态方法getSessionFactory()。

SessionFactory sessionFactory = HibernateBaseDB.getSessionFactory();
Session session = sessionFactory.openSession();