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

时间:2014-09-05 11:23:02

标签: java mysql hibernate

在我的应用程序中,我正在使用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>

但是当我尝试使用此db.property file使用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>

这是错误

 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

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

3 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:4)

试试这段代码:

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

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

<?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>

答案 2 :(得分:0)

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属性文件 - 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)加载属性文件:

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)创建会话工厂:

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;

    }

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

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

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