Writing a Hibernate Application

We then write a simple Java hibernate application. This first application simply stores a single Book object in the table book.

In this application, we first import necessary classes to work with hibernate. Two primary hibernate API packages are org.hibernate and org.hibernate.cfg. Import classes from these packages:

import org.hibernate.*;

import org.hibernate.cfg.*;

The first object that we create in a hibernate application is an org.hibernate.cfg.Configuration object and is usually created only once as follows:

Configuration cfg = new Configuration();

Note that hibernate needs to know, in advance, a set of configuration settings related to database and other related parameters. It must also know where to find the mapping information that defines how Java classes relate to the database tables. Hibernate finds necessary information from Configuration object that contains the following information:

  • Configuration information such as database connection properties and hibernate properties etc. and
  • Object to database table mapping information

The configuration information is stored in files called configuration files, which may be standard Java properties files or XML files. The object to database table mapping information, on the other hand, may be stored in XML files called mapping files or may be specified using annotation. The Configuration object loads information from these files/annotations.

The default constructor of Configuration class always searches a configuration file named hibernate.properties (which is an ordinary Java property file) in the current directory. So, create a file with this name and put configuration information there. For MySQL, it looks like this:

#hibernate.properties

hibernate.connection.driver_class com.mysql.jdbc.Driver

hibernate.connection.url jdbc:mysql://172.16.5.81/test

hibernate.connection.username root

hibernate.connection.password nbuser

Alternatively, this information may be put in an XML file (say config.xml) and passed to the configure() method of Configuration object as follows:

cfg.configure(”config.xml”);

The config.xml file looks like this:

<?xml version=”1.0” encoding=”utf-8”?>

<!DOCTYPE hibernate-configuration SYSTEM

”http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd”>

<hibernate-configuration>

<session-factory>

<property name=”connection.driver_class”>com.mysql.jdbc.Driver</property>

<property name=”connection.url”>jdbc:mysql://172.16.5.81/test</property>

<property name=”connection.username”>root</property>

<property name=”connection.password”>nbuser</property>

</session-factory>

</hibernate-configuration>

This file essentially contains same information as hibernate.properties file. An XML configuration file must comply with the hibernate 3 configuration DTD, which is available from

http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd. We may also use zero argument configure() method as follows:

cfg.configure();

However, this always expects an XML file with name hibernate.cfg.xml. Note that XML configuration file, in contrast to property configuration file, is capable of storing more information such as name of mapping files. Moreover, the syntax of XML files may be validated against the above mentioned DTD. That is why it is recommended to use XML files as configuration files instead of flat property files.

The list of supported databases with their dialect are given in Table 23.1:

Anyway, so far the Configuration object is aware of database connection properties. Now, we have to specify the object to database table mapping information. A mapping document describes persistent fields and associations. The mapping documents are compiled at application startup time and provide necessary information for a class to the Hibernate framework. They are also used to provide support operations such as creating stub Java source files or generating the database schema etc. Mapping may also be specified in two ways:

  • Using XML files called mapping files or
  • Using annotation

In this section, we shall use XML file to specify mapping. Here is a sample file (Book.hbm.xmi) that maps Book class to tbi_book table:

<?xml version=”1.0” encoding=”utf-8”?>

<!DOCTYPE hibernate-mapping PUBLIC ”-//Hibernate/Hibernate Mapping DTD//EN”

”http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd”>

<hibernate-mapping>

<class name=”Book” table=”tbl_book”>

<id name=”id” type=”int” column=”no”/>

<property name=”title” column=”name” type=”string”/>

<property name=”price” column=”pr” type=”int”/>

</class>

</hibernate-mapping>

The name of this mapping file is usually chosen as [classname].hbm.xml. A mapping file must have a root element <hibernate-mapping>..</hibernate-mapping>. The <ciass> element maps a Java class to a database table specified using name and table attributes respectively. For our example, it says that the Java class Book corresponds to the database table tbl_book.

The <id> element maps a unique property (specified by name attribute) in class to the primary key (specified by column attribute) of the database table. The above example tells that the unique id class property corresponds to primary key no in the table. The <property> element is used to map a Java class property (specified by name attribute) to a column (specified by column attribute) in the database table. In the above example, the title and price Java class properties correspond to name and pr column of table tbl_book respectively.

Note that for each class property xxx, hibernate expects get and set methods as getXxx() and setXxx() respectively. Hibernate uses these methods to get and set member fields. For properties

title and price, Hibernate expects getTitle(), setTitle() and getPrice(), setPrice() methods. Needless to say that these methods really exist in our Book class. Hibernate uses these methods to get and set corresponding fields. Note that name of the fields need not be same as property name.

The mapping file may contain other elements and attributes, which we shall discuss in due course. Now, tell the Configuration object to look for mapping information in the XML file Book.hbm.xml as follows:

cfg.addResource(“Book.hbm.xml”);

The name of the mapping file may also be specified in the XML configuration file using resource attribute of <mapping> element as follows:

<hibernate-configuration>

<session-factory>

<!—Other entries–>

<!– List of XML mapping files –>

<mapping resource=”Book.hbm.xml”/>

</session-factory>

</hibernate-configuration>

Our Configuration object is now complete. This reads data from configuration and mapping files and finally places them in a high level heavyweight hibernate object, the SessionFactory object, an instance of which may be built as follows:

SessionFactory factory = cfg.buildSessionFactory();

We then create a Session object, which is primary runtime interface between a Java application and Hibernate:

Session session = factory.openSession();

A Session object is equivalent to Connection object of JDBC. The main function of the Session object is to allow creating, reading, updating and deleting instances of mapped entity classes. In our application, we shall simply save a Book object. So, we create one such object:

Book b = new Book(“Advanced Java Programming”, 450);

For a database write (e.g. insert, update, delete) hibernate needs a logical Transaction to be started as follows:

Transaction tx = session.beginTransaction();

Note that for database read operations, we do not require any logical transaction in hibernate. The Session object provides useful methods to save, update, delete objects. We use save() to save our Book object:

session.save(b);

Note that Hibernate, by default, does not automatically commit (autocommit mode false) database transaction. So, the save() method merely writes b to the database; nothing will persist permanently in the database until the transaction performs a commit explicitly. Hence, we do it using commit() method of in Transaction:

tx.commit();

The entire source code (saveBook.java) of our application is shown below:

//SaveBook.java import org.hibernate.*; import org.hibernate.cfg.*; public class SaveBook {

public static void main(String[] args) {

Configuration cfg = new Configuration();

cfg.configure(”config.xml”);

cfg.addResource(”Book.hbm.xml”);

SessionFactory factory = cfg.buildSessionFactory();

Session session = factory.openSession();

Book b = new Book(”Advanced Java Programming”, 450);

Transaction tx = session.beginTransaction();

try {

session.save(b);

tx.commit();

}catch (Exception e) {

if (tx!=null) tx.rollback();

}

finally { session.close(); factory.close();}

}

}

Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.

Leave a Reply

Your email address will not be published. Required fields are marked *