Hibernate Tutorial 01 Object/Relational Mapping: 1. Installation
Hibernate Tutorial 01 Object/Relational Mapping: 1. Installation
By Gary Mak
[email protected]
September 2006
1. Installation
JDK is an essential toolkit provided for Java application development. You can go to
http://java.sun.com/j2se/1.5.0/download.jsp to download JDK 5.0. Install it into a folder say
“C:\jdk1.5.0”.
Eclipse is an IDE for developing Java application. WTP provides some tools for Web and J2EE
development, such as XML editor and SQL editor. You can go to http://www.eclipse.org/webtools/
and download WTP All-in-one 1.0. Unzip it into a folder say “C:\eclipse”.
HSQLDB is an open source SQL relational database engine written in Java. You can go to
http://www.hsqldb.org/ and download HSQLDB 1.8.0. Unzip it into a folder say “C:\hsqldb”.
Suppose we need to develop an online bookshop application. It will use relational database to store
its application data.
To create a new HSQLDB database instance, use the following command. Some files
(BookShopDB.*) will be created for the first time running this command.
Page 1 of 8
java -cp lib/hsqldb.jar org.hsqldb.Server -database.0 BookShopDB -dbname.0 BookShopDB
For the first step, we create the tables for our online bookshop using the following SQL statements:
We can use DbVisualizer to generate the following diagram for our schema. It is the “relational
model” for our online bookshop.
Page 2 of 8
Next, let’s input some data for these tables using the following SQL statements:
INSERT INTO PUBLISHER (CODE, PUBLISHER_NAME, ADDRESS) VALUES ('MANN', 'Manning', 'Address for
Manning');
INSERT INTO BOOK (ISBN, BOOK_NAME, PUBLISHER_CODE, PUBLISH_DATE, PRICE) VALUES ('1932394419',
'Hibernate Quickly', 'MANN', '2005-08-01', 35);
INSERT INTO CHAPTER (BOOK_ISBN, IDX, TITLE, NUM_OF_PAGES) VALUES ('1932394419', 1, 'Why
Hibernate?', 25);
INSERT INTO CHAPTER (BOOK_ISBN, IDX, TITLE, NUM_OF_PAGES) VALUES ('1932394419', 2, 'Hibernate
basics', 37);
The traditional way of accessing a relational database is to use JDBC (Java Database Connectivity).
For the first time of developing our Java application, we create a project “BookShop” in Eclipse and
add the HSQLDB JDBC driver to its Java build path. The location of that driver is
${HSQLDB_INSTALL_DIR}/lib/hsqldb.jar.
We must first load the JDBC driver and create a connection to that database before we can execute
any SQL statements. Be careful, you must remember to close that connection in any case (whether
an exception is raised or not).
Page 3 of 8
Class.forName("org.hsqldb.jdbcDriver");
Connection connection = DriverManager.getConnection(
"jdbc:hsqldb:hsql://localhost/BookShopDB", "sa", "");
try {
// Using the connection to query or update database
} finally {
connection.close();
}
For demo purpose, we query for a book whose ISBN is “1932394419”. Below is the JDBC code
fragment for this task:
For demo purpose, we update the name of the book whose ISBN is “1932394419”. Below is the
JDBC code fragment for this task:
Page 4 of 8
4. Object/Relational Mapping
In the previous sections, we have learned how to use JDBC to access relational database. As widely
known, Java is an Object-Oriented programming language. That means we should use an “object
model” to represent our domain concepts.
We use normal JavaBeans to build our object model. These JavaBeans are called “Plain Old Java
Objects” (POJOs). This term is used to distinguish from Enterprise JavaBeans (EJBs). Note that
each of these POJOs must have a no-argument constructor.
We use “Class Diagram” in UML to represent the object model for our online bookshop.
Page 5 of 8
You can see that there are differences between an object model and a relational model. For example,
we used a foreign key to reference PUBLISHER from BOOK table, but it is a many-to-one
association in Book class. We used a foreign key to reference BOOK from CHAPTER table, but
there’s nothing referencing Book class from Chapter class. In opposite, a Book object has a list of
Chapter objects (one-to-many association).
For the incompatibility of these models, we need to do some conversion when we “retrieve” and
“persist” our object model. This is called “Object/Relational Mapping” (O/R Mapping or ORM).
Suppose we have a web page in our application for showing the detail of a book (including ISBN,
book name, publisher name, publisher address, publish date and all the chapters inside the book).
We can use the following JDBC code fragment to retrieve a book object together with a publisher
object and a list of chapter objects. Such a group of objects with association is called an “object
graph”.
Page 6 of 8
Publisher publisher = new Publisher();
publisher.setCode(rs.getString("PUBLISHER_CODE"));
publisher.setName(rs.getString("PUBLISHER_NAME"));
publisher.setAddress(rs.getString("ADDRESS"));
book.setPublisher(publisher);
}
rs.close();
stmt.close();
Suppose we are providing a web page for the users to input the information of a book, including the
details of publisher, and what chapters are inside. When he is done, the whole object graph will be
saved to the database.
stmt = connection.prepareStatement(
"INSERT INTO BOOK (ISBN, BOOK_NAME, PUBLISHER_CODE, PUBLISH_DATE, PRICE)
VALUES (?, ?, ?, ?, ?)");
stmt.setString(1, book.getIsbn());
stmt.setString(2, book.getName());
stmt.setString(3, book.getPublisher().getCode());
Page 7 of 8
stmt.setDate(4, new java.sql.Date(book.getPublishDate().getTime()));
stmt.setInt(5, book.getPrice());
stmt.executeUpdate();
stmt.close();
stmt = connection.prepareStatement(
"INSERT INTO CHAPTER (BOOK_ISBN, IDX, TITLE, NUM_OF_PAGES) VALUES (?, ?, ?, ?)");
for (Iterator iter = book.getChapters().iterator(); iter.hasNext();) {
Chapter chapter = (Chapter) iter.next();
stmt.setString(1, book.getIsbn());
stmt.setInt(2, chapter.getIndex());
stmt.setString(3, chapter.getTitle());
stmt.setInt(4, chapter.getNumOfPages());
stmt.executeUpdate();
}
stmt.close();
5. Problems
Now, you have experienced Object/Relational Mapping. The method you are using is through JDBC.
Is it good enough? Let’s investigate some problems inside this method.
Using JDBC means you can execute any kind of SQL statements. For a simple task, you have to
code many SELECT, INSERT, UPDATE, DELETE statements repeatedly.
When you perform object retrieval, you need to copy the fields in a ResultSet to the properties of an
object. When you perform object persistence, you need to copy the properties of an object to the
parameters in PreparedStatement.
When you perform object retrieval, you need to perform table join or read from several tables to get
a graph of objects. When you perform object persistence, you need to update several tables
accordingly.
The SQL statements you wrote for one database may not work with another brand of database.
Although the chance is very small, you may have to migrate to another database for some reasons.
Page 8 of 8