04 - Hibernate Configuration Approaches

4.1 Overview

As we discussed earlier, Hibernate needs to know about the database configurations to connect to the database. There are three approaches with which we can do the configurations. These approaches are-

  1. Programmatic Configurations – Hibernate does provides a way to load and configure database and connection details programmatically.
  2. XML configurations – We can provide the database details in an XML file. By default hibernate loads the file with name  hibernate.cfg.xml but we can load the file with custom name as well.
  3. Properties configurations- This approach uses a properties file for the configuration. By default hibernate loads the file with name  hibernate.properties but we can load the file with custom name as well.

4.2 Programmatic Configurations

Hibernate does provide a Configuration class which provides certain methods to load the mapping files and database configurations programmatically .

4.2.1 Loading Mapping Files

To load the mapping files (also known as hbm files) there are three ways–      

  1. addResource() – We can call addResource() method and pass the path of mapping file available in a classpath. To load multiple mapping files, simply call addResources() method multiple times.

    Below code snippet uses addResource() method to load user.hbm.xml and account.hbm.xml file available in com.hibernate.tutorial package.

         Configuration configuration = new Configuration();   

         configuration.addResource("com/hibernate/tutorial/user.hbm.xml");

         configuration.addResource("com/hibernate/tutorial/account.hbm.xml ");

  2. addClass()-  Alternatively we can call addClass() method and pass in the class name which needs to persist. To add multiple classes , we can call addClass() multiple times.

    Below code snippet uses addClass() method to load user and account classes available in com.hibernate.tutorial package.

         Configuration configuration = new Configuration();

         configuration.addClass("com.hibernate.tutorial.user.class");

         configuration.addClass("com.hibernate.tutorial.user.account.class ");

  3. addJar()We can call addJar() to specify the path of jar file containing all the mapping files. This approach provides a generic way and need not to add mapping every time we add a new mapping.

                              Configuration configuration = new Configuration();

             configuration.addJar(new File("mapping.jar"))

4.2.2 Loading Database Configurations

In earlier section we saw how to load the mapping files programmatically, but along with mapping files, Hibernate requires database configurations as well.

We can use the Configuration object to load the database configurations from an instance of properties files, System properties or even set the database properties directly. Lets discuss all approaches in details.

  • setProperty()-  we can call setProperty() method on configuration object and pass the individual property as a key value pair. We can call setProperty() multiple times.

Below code specifies hibernate dialects , driver class , database connection url, database credentials using setProperty() method.

Configuration configuration = new Configuration();
configuration.setProperty("hibernate.dialect", " org.hibernate.dialect.MySQLDialect");
configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/tutorial");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "password");

b.setProperties()-  we can call setProperties() method on the configuration object to load the properties from system properties or can pass the property file instance explicitly.

Below code specifies load the database configurations from System properties. All the database configurations will be configured using “ Java -Dproperty=value “

                     Configuration configuration = new Configuration();
                     configuration.setProperties(System.getProperties());

Alternatively, we can create a properties file having database configurations and pass its instance in setProperties()

So we saw how we can load both mapping files and database configuration files programmatically so together the code snippet looks like below

Configuration configuration = new Configuration();    
configuration.addResource("com/hibernate/tutorial/user.hbm.xml");
configuration.addResource("com/hibernate/tutorial/account.hbm.xml ");
configuration.setProperty("hibernate.dialect", " org.hibernate.dialect.MySQLDialect");
configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
configuration.setProperty("hibernate.connection.url", " jdbc:mysql://localhost:3306/tutorial");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "password");

4.3 XML Configurations

The XML configuration approach is widely used and Hibernate loads the configurations from a file with name hibernate.cfg.xml from a class path. Alternatively, we can create an XML file with another name and pass the name of the file.

The sample XML file looks like below-

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

<hibernate-configuration>
        <session-factory>
            <property name="hibernate.connection.url">
             jdbc:mysql://localhost:3306/tutorial
         </property>
              <property name="hibernate.connection.username">
               root
              </property>
              <property name="hibernate.connection.password">
                 password
             </property>
             <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
             <property name="show_sql">false</property>
             <property name="hibernate.connection.driver_class">
                  com.mysql.jdbc.Driver
             </property> 

            <mapping resource="user.hbm.xml"/>
        </session-factory>
</hibernate-configuration> 

To add mapping resources we can use <mapping resource> tag in hibernate.cfg.xml file .This is similar to addResource() method. Similarly, we can use <mapping jar> and <mapping class> tags for addJar() and addClass()

Just need to instantiate Configuration object like below

    Configuration configuration = new Configuration().configure();

new Configuration() call will load the hibernate.properties file  and calling configure() method on configuration object loads hibernate.cfg.xml. In case any property is defined in both hibernate.properties and hibernate.cfg.xml file then xml file will get precedence.

To load the custom files, we can call

     Configuration configuration = new 
     Configuration().configure("/configurations/myConfiguration.cfg.xml")

The Above code snippet will load myConfiguration.cfg.xml  from the  configuration subdirectory of class path.

Note: We can skip prefix “hibernate” from the hibernate properties like hibernate.connection.password is equivalent to connection.password

4.4 Properties file Configurations

Hibernate looks for a file named hibernate.properties file in the class path. Properties file provides the similar  functionality as XML file provides with the difference of “ we cannot add a mapping resource in properties file) 

Below is the sample content of hibernate.properties file

hibernate.connection.url = jdbc:mysql://localhost:3306/tutrial hibernate.connection.username = root
hibernate.connection.password = password
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true

4.5 Commonly Used Hibernate Properties 

Hibernate supports many properties to configure database, connections, transactions, cache properties which can be referred at Hibernate Official Documentation but the most commonly used are-

Property Name Description
hibernate.cache.provider_class

We can specify the implementation of org.hibernate.cache.CacheProvider implementation. This property is used to specify the cache implementation to use.

hibernate.cache.use_query_cache

To specify whether to use or not  Query Cache
hibernate.cache.use_second_level_cacheTo specify whether  to use or not Second level  Cache
hibernate.connection.autocommitTo set auto commit mode of connection
hibernate.connection.datasourceSpecify the datasource to use
hibernate.connection.driver_classJDBC Driver class
hibernate.connection.passwordDatabase password
hibernate.connection.usernameDatabase username
hibernate.connection.pool_sizeTo limit the number of connections
hibernate.connection.urlSpecify the database connection URL
hibernate.dialectLet Hibernate know which Dialect to use
hibernate.hbm2ddl.auto

This property is used to specify if Hibernate to create , update , drop automatically when the application starts. There are five possible values –

a) create-create the tables based on mapping files when application starts and removes if already exists.

b) create-drop- drop the tables when session factory is closed and create when application starts based on mapping files.

c) update – update the tables if already exists or create if not  based on the mapping files.

d) validate – does not create table validates the table against mapping files. Gives errors if mismatch

e) none = does nothing.

 

NOTE- This option works on Tables not on SCHEMA
hibernate.show_sqlLogs the generated SQL on console. Possible values are true or false

hibernate.format_sql
Logs the formatted generated SQL on console. Possible values are true or false

 4.6 Dialects 

As we mentioned earlier that Hibernate is Database independent, but each database uses some database specific SQLs and functions like column data types, SQL functions, etc.  So Hibernate must be aware of the database that our application is connecting to so that database supported SQLs can be generated internally by Hibernate. Complete list of supported Dialects can be seen in Hibernate Official Documentation but most commonly used are-

  1. DB2- org.hibernate.dialect.DB2Dialect

  2. DB2 AS/400- org.hibernate.dialect.DB2400Dialect

  3. DB2OS390- org.hibernate.dialect.DB2390Dialect

  4. PostgreSQL-org.hibernate.dialect.PostgreSQLDialect

  5. MySQL-org.hibernate.dialect.MySQLDialect

  6. MySQL with InnoDB- org.hibernate.dialect.MySQLInnoDBDialec

  7. tMySQL with MyISAM- org.hibernate.dialect.MySQLMyISAMDialect

  8. Oracle (any version)- org.hibernate.dialect.OracleDialect

  9. Oracle 9i/10g- org.hibernate.dialect.Oracle9Dialect

  10. Sybase- org.hibernate.dialect.SybaseDialect

 

4.7 Naming Strategy

Hibernate does allow us to provide a custom naming strategy with which we can direct Hibernate on how to map Java classes with tables. We can override the configurations done in mapping files in naming strategy implementation. Simple example, we can think of is to add prefix to table names. This functionality can help us from doing repetitive configurations.

4.8 Configure Logging

Hibernate uses slf4j framework for logging which is an open source framework which can direct the log outputs to application logging framework like log4j, log-book etc.

To display the SQL statements on console, we can simply enable it with  hibernate. show_sql property. Similarly to log formatted SQL, we can enable it using  hibernate. format_sql property.

If we want to change the logging levels or want to log in additional appenders, we can create log4j.properties file in the class path of the application.

Also, you need to add log4j.jar file in the class path. You can download it from https://logging.apache.org/log4j/1.2/download.html

 

Like us on Facebook