Hibernate Object Relational Mapping
First in a two-part series by Java guru John Hunt
How many Java applications have you built that store data in a database? For me, almost all the Java systems I have been involved with have, at some point, involved a database. In general, what has happened is that data held in objects, at some point has been stored into the database, so that it can be restored back into objects later. Thus, the database has acted as a persistent storage device for information required by the Java system. This can of course be achieved in a variety of ways, and the use of JDBC lies at the heart of this process.
However, mapping the Java (object oriented) world into the relational world of modern databases is not without its own set of issues. The object world and the relational world are two very different paradigms. The Object world deals with classes, instances of those classes and relationships between those instances. The relational world instead deals with tables, rows and the relationships between those tables. In the middle sits SQL, which is a declarative language used to specify a function that determines which columns and rows are returned at any one time.
While this may not be too much of an issue for a single object that can be easily mapped to a single table in the database, things get more complicated in the real world. If what you need to persist is a network of objects, which map to numerous tables (where there may or may not be an object-per-table mapping) this becomes much more complex and the amount of SQL you may need to write can very quickly grow.
Thus mapping between the two paradigms is not trivial and indeed to be successful at this you need to have a reasonable level of expertise in Java, SQL and database design. These skills are not only in demand, but are also hard to come by. An Object Relational Mapping tool (ORM) tries to alleviate this process by providing the means to automatically map form the object world into the relational world (and back again). It aims to make the database storage of objects (and even networks of objects) as simple as Java’s serialization.
Hibernate (available here) is an example of an ORM. It is probably the most widely used open source Object Relational Mapper currently available.
Hibernate is an Open Source Object Relational Mapper. Its aim is to remove the majority of the drudgery and time consuming repetitive coding needed for implementing your own Java-to-Relational mapping system. Thus, Hibernate handles the task of mapping classes to tables, and objects to actual rows. Hibernate generates SQL for you, relieves you from manual result set handling and object conversion and keeps your application portable to all SQL databases (no mean feet in itself).
In particular, Hibernate provides for transparent persistence (at least form the point of view of the object being persisted) - the only requirement for a persistent class is a no-argument constructor. Hibernate is one of the most mature and most complete open source object-relational mapping tools. It is widely used and very actively developed; it is also appearing in more and more systems including JBoss and is often combined with Spring. In the case of JBoss, Hibernate is a critical component of theJBoss Enterprise Middleware System (JEMS) suite of products.
Installing and Configuring Hibernate
Whenever you start with a new framework one of the issues can be getting the thing up and running in the first place. We will therefore step through setting up Hibernate using MySQL. There is a wide range of database that could be used, however MySQL is freely available and illustrates what would be done if we were to use an Oracle, DB2, Postgres or SQLServer database.
1. Download the Hibernate distribution file. First, you need to down load the current Hibernate distribution file. You can obtain this from the Hibernate home page - look for the download link on the left hand side. Once you have selected this, you will be presented with a number of different options to download. Select the current production release, as this will be the most stable version to work with. For example:
Then select to download. This will take you to a page from which you can download the current Hibernate release. At the time of writing this means downloading the hibernate-3.0.5.zip file.
2. Extract the contents of the ZIP file You can now extract he contents of the Hibernate distribution ZIP file using whatever unzip tool you use (for example WinZip see http://www.winzip.com). Place the contents of the Hibernate ZIP file somewhere appropriate (personally I put all these downloads into a directory called javalibs so that I can easily find them).
3. Install in the Development directory
You can now copy the various JAR files required by hibernate into your working directory (personally I store all jars I use for any particular development project within a lib directory of my working directory structure). The jars you will need include the hibernate3.jar file that contains the actual hibernate specific classes. Various other jar files are also needed to support hibernate. These include those illustrated in Figure 1.
4. Obtaining and Install MYSQL driver
I am using MySQL 4.1.14 in this tutorial along with a JDBC driver for MySQL. MySQL can be obtained from http://www.mysql.com/. On this site, select 'downloads' and then the appropriate version for your operating system. For example, for Windows, scroll down to the windows section and choose
Windows (x86) 4.1.14 37.0M
Now install the MySQL database. You will find that you have downloaded a ZIP file that contains the MySQL setup.exe program. Extract this and run the setup.exe. This will take you through the installation process. Once you have done that, open a command prompt in the bin directory of your MySQL installation and type in mysql. This should startup the MySQL console. If this works then you have successfully installed MySQL.
Next, you need to download a JDBC driver for MySQL. The MySQL driver, MySQL Connector/J, is available from the MySQL site. Go to the URL http://www.mysql.com/products/connector-j/index.html and click on the link for downloading version 3.1:
MySQL Connector/J 3.1 is the production-ready version of the driver, and is available under the GPL (recommended).
This will download a zip file containing the JAR with the JDBC driver. Extract the JAR, called mysql-connector-java-3.1.10-bin.jar, and add it to your lib directory within your development directory.
You have now installed MySQL and made the MySQL JDBC driver available for later use.
5. Setting up MySQL
Next we need to create a database, with some tables and a user that will be plugged into hibernate in the next step. We will create a database called hib, that can be accessed by hibuser using the password hib123. This is done by first starting the MySQL console as the root user. This is done by issuing:
> mysql –u root
Once MySQL is started, you can then issue the following commands:
>GRANT ALL on hib.* to 'hibuser'@'localhost' IDENTIFIED by 'hib123'; >CREATE DATABASE hib;
If this is successful, quit from the MySQL console. This is illustrated in the following diagram:
Further statements will be SQL and will be issued as a standard user. Next restart the MySQL console (but without the –u root option). Once we have started the console we need to tell MySQL which database we want to work with (so that we don’t have to pre-fix everything with hib.). To do this we say:
> USE hib;
We can now define the table that will be used by hibernate to store our persistent objects. We will call this table books. It will have an id (which will be auto incremented), a title, author and price. The id will be the primary key and the table type will be MyISAM (which is the default MySQL table type). This is done by issuing the following CREATE statement:
> CREATE TABLE books (id int(11) NOT NULL auto_increment, title varchar(250) default NULL, author varchar(250) default NULL, price char(6) default NULL, PRIMARY KEY (id)) TYPE=MyISAM;
This is also illustrated in the following screen dump:
6. Link hibernate to MySQL
We now need to tell Hibernate about our MySQL database. We can do this using the hibernate.cfg.xml file. You will find this in the hibernate3 distribution directories in the etc directory. Copy the hibernate.cfg.xml file to your classes directory of your development directory (this is so that Java can pick it up form the class path). You can now safely edit the copy of the hibernate configuration file in your development directory.
If you examine this file you will find that it lists numerous different (database) platforms that Hibernate can work with. As we are working with MySQL, find the section that lists MySQL details.
You will need to uncomment this section (remove the “#” at the start of each line). You will also need to specify the MySQL database to use (hib), and the user to connect to MySQL as (in this case hibuser with a password of hib123). I must also specify the JDBC driver to be used (in this case the com.mysql.jdbc.Driver).
This configuration information can be defined either in a hibernate.properties file or in the hibernate.cfg.xml file. We will use the XML format which is more in keeping with current trends. Note that I have placed this file again the class subdirectory of my development directory. This is illustrated below:
We have now configured MySQL and hibernate to work together. The next thing to think about is creating our Hibernate application. We will consider the steps to be performed when creating a Hibernate application in the next article. ®
Part 2 is here.