This section details the structure and functionality of the Hibernate XML Configuration File and the Hibernate Mapping Files.

Hibernate Configuration File

An application that uses Hibernate API must use a single configuration file. A configuration file for a Hibernate application will tell some of the information like the URL of the Database Server to which the application wants to connect, the username/password for the Database, class name of the Driver file and with other set of preferences.

A Hibernate configuration file can be an XML-based file (hibernate.cfg.xml) or it can be ordinary Java properties file (hibernate.properties) with key-value combination. This configuration file should be placed in the run-time classpath of an application. If both the XML-based configuration file and the properties-based configuration file are found in the classpath, then the XML-based configuration file will take preference over the other.

Following is the structure of a Hibernate configuration file,

Hibernate.cfg.xml:

ClassNameOfTheDriver

DbServerUrl

DbUser

DbPassword

…..

Let us look into the structure of the XML in detail here. The first observable thing is that this XML has a well-defined DTD defined from “http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd” meaning that the construction of this XML document should be validated against the DTD.

The outer-most element is the ‘hibernate-configuration’ element which forms the root element for specifying the configuration information. The next inner element is the ’session-factory’ element which corresponds to the SessionFactory class that contains information related to the Database like the URL of the Database server, the username/password information on the Database server etc.

The various properties within the ’session-factory’ element is represented in Hibernate Configuration file as a ‘property’ element.

Whenever we say,Configuration configuration = new Configuration().configure(), the no argument Configuration.configure() method will load the configuration file called “hibernate.cfg.xml” from the application’s classpath. The default name for the Hibernate Configuration file is “hibernate.cfg.xml”. Different configuration file can be loaded into the application by calling the one-argument Configuration.configure() method, like the following,

File configurationFile = new File(“.\\config\\MyConfiguration.xml”);
Configuration configuration = new Configuration().configure(configurationFile);

The code, SessionFactory sessionFactory = configuration.buildSessionFactory(), will populate the SessionFactory object with the set of property values values that are taken from the ’session-factory’ XML element. So, in our case, the SessionFactory object will be populated with values the class name of the driver, the URL of the Database server and the username/password of the Database.

The next section in the Hibernate Configuration File is the ‘mapping’ element which represents a XML file that contains the mapping information such as how a Java Class should be mapped against a Database table. The next section deals with the structure of the Mapping Files in greater detail.

The same configuration information in the XML-based Hibernate configuration file can be given in the property-based Hibernate configuration file and such a file may look like the following,
hibernate.properties:

hibernate.connection.driver_class = ClassNameOfTheDriver
hibernate.connection.url = URLOfTheDatabaseServer
hibernate.connection.username = DatabaseUsername
hibernate.connection.password = DatabasePassword

Hibernate Mapping Files

A Hibernate mapping file provides mapping information like how a Java Class is mapped to a relational database table. It also contains other information like which Java Property (or Field) in a class will map to which Table Column. Relations between entities can be defined in the Mapping file through various associations like one-to-one, one-to-many, many-to-many etc.

The mapping files that are needed for an application are defined and referenced in the Hibernate configuration file throught the ‘mapping’ element. If you remember, the Hibernate configuration file has references to Hibernate mapping files like this,

……

……

Let us look into the structure of a mapping file.
TestMapping.xml:

….

Like the Hibernate Configuration file, this mapping file has to be validated against the DTD given by “http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”. The root element in this XML file is the ‘hibernate-mapping’ which acts as a container for several different mapping definitions in the form of ‘class’ tag. Any number of mapping definitions can be given inside the ‘hibernate-mapping’ element, but the preferred way is to give one definition per XML file.

The ‘name’ attribute in the ‘class’ element is the name of the Java class that we want to persist. The ‘table’ attribute represents the name of the table for this java Class in the database. All the ‘property’ elements will map Java fields to Table Column names. The Java Field is identified by the ‘name’ attribute in the ‘property’ element and the table column name is represented by the ‘name’ attribute in the ‘column’ element.

A primary key is a must for every table as it used to uniquely identify Java instances. The ‘id’ element represents the primary-key portion wherein with ‘name’ and the ‘column’ attribute corresponds to the Java Field and the table primary key column. The value for the ‘generator’ element represents how the primary-key is generated for the table. So many different implementations for generating a primary-key are available in Hibernate like ‘identity’, ’select’, ‘assigned’, etc. If the value of the ‘generator’ element is ‘assigned’, then it is the responsibility of the developer to manually set the primary key.

Hibernate Configuration file:

Following is the Hibernate configuration file.

hibernate.cfg.xml:

jdbc:mysql://localhost/DbForHibernate

com.mysql.jdbc.Driver

root

root

org.hibernate.dialect.MySQLDialect

The above XML file has the various database parameters like the URL, class name of the driver, username and password set to ‘jdbc:mysql://localhost/DbForHibernate’, ‘com.mysql.jdbc.Driver’, ‘root’ and ‘root’ respectively. We have already seen how these various parameters will affect the configuration of the SessionFactory object.
Sql Dialects:

The only new property defined in this file is the ‘dialect’ property which is pointing to org.hibernate.dialect.MySQLDialect. Dialects are one among the various new features in Hibernate. Consider a database vendor ‘DB-V1′ who provides a feature called performance tuning using some SQL syntax. If some other database vendor ‘DB-V2′ provides that performance tuning feature, then it’s very likely that the syntax of both the queries will be different.

Suppose, if such a feature is enabled in a hibernate application by some piece of code, Hibernate should using two different syntax for two different databases. How will Hibernate knows the correct SQL syntax for different databases?

The answer lies in SQL Dialect. Every database has their own SQL Dialect. The following provides some major SQL Dialects from some popular Database vendors.

Database SQL Dialect

Microsoft SQL Server org.hibernate.dialect.SQLServerDialect
MySQL org.hibernate.dialect.MySQLDialect
Oracle org.hibernate.dialect.OracleDialect
Informix org.hibernate.dialect.InformixDialect
Sybase org.hibernate.dialect.SybaseDialect

So, if an application uses any vendor specific features, it is a must that the application must provide that particular SQL Dialect in the Hibernate Configuration file to function properly.
Hibernate Mapping File: The XML-based Hibernate mapping file is shown below,

As explained previously, the Hibernate mapping file contains the mapping information between a Java Class and the database table name. In the above file, the value for the ‘generator’ element is given as ‘assigned’, which means that the application when persisting the Java object must manually set the value for the primary key (in our case, it’s the ‘Id’ column). If it is not set, then an exception will be thrown by Hibernate at run-time.
Client Application:

Following is the listing for the Client Application.
RunClient.java:

package client;

import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import test.User;

public class RunClient {
public static void main(String[] args) {

try{
Configuration conf = new Configuration().configure();
SessionFactory sessionFactory = conf.buildSessionFactory();
Session session =sessionFactory.openSession();

User user = new User();
user.setId(1000);
user.setName(“Test User”);
user.setAge(24);

Transaction t = session.beginTransaction();
session.save(user);
t.commit();

session.close();
}catch(Exception e){
e.printStackTrace();
}
}
}

For the above program to compile and run properly, two set of Jar files have to placed properly in the application’s class-path. One is the set of Jar files that are available within the Hibernate Ditribution, which is normally the \lib, where refers to the installation of the Hibernate. Following jar files from the Hibernate distribution have to be maintained in the class-path of the application,

* cglib2.jar
* commons-collections
* commons-Logging
* dom4j.jar
* ehcache.jar
* jdbc2.0-stdext
* jta.jar
* log4j.jar
* odmg.jar
* xalan.jar
* xerces.jar
* xml-apis.jar

The other set of the jar files are for the Jdbc Driver, which is ‘mysql-connector-java-5.0.5-bin.jar’ in the case of MySQL Database.

The above code establishes a Configuration object by calling new Configuration().configure() which scans the classpath for the presence of hibernate.cfg.xml file. It then creates an instance of SessionFactory object with the details populated from the Configuration File by calling Configuration.buildSessionFactory(). A new Session object is then created for persisting objects by calling SessionFactory.openSession().

A new Java object called ‘User’ is populated with some test values and the object is persisted into the Session object within a transactional context by calling Session.beginTransaction() which marks the beginning of the transaction. Remember that Session.save(object) only marks the object to be persisted. After a successful save operation and transaction is committed by calling Transaction.commit(), which means that the object will be synchronized with the database.