6

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.

<?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 file using this hibernate.cfg.xml, it showing Exception, this is my another hibernate.cfg.xml file

<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

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

Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
Killer
  • 592
  • 1
  • 6
  • 24
  • if you are using spring then you can refer this link,http://stackoverflow.com/questions/17939339/propertyplaceholderconfigurer-with-hibernate-cfg-xml – Kishore Kumar Sep 05 '14 at 11:37
  • I read that, but I need to do it in hibernate only, not using spring. Because I want my hibernate application to get the DB configuration properties from properties file. – Killer Sep 05 '14 at 11:39
  • @Killer does [this](http://stackoverflow.com/questions/24176024/how-to-include-properties-from-external-file-to-hibernate-cfg-xml) helps you – Ankur Singhal Sep 05 '14 at 11:42

3 Answers3

10

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

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

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);
Chaitanya
  • 15,403
  • 35
  • 96
  • 137
5

try this code:

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>
hossein ketabi
  • 480
  • 7
  • 19
  • 1
    Where would "HibernateUtil.java" go in my project? I'm not clear as to how my project would know to use this file... – buddamus May 06 '16 at 17:31
  • use where that you want to create seassionFactory. SessionFactory factory = HibernateUtil.getSessionFactory(); – hossein ketabi May 09 '16 at 19:54
1

1) Hibernate configuration XML file: 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

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:

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:

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.

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

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