Keywords

These keywords were added by machine and not by the authors. This process is experimental and the keywords may be updated as the learning algorithm improves.

Most significant development projects involve a relational database.Footnote 1 The mainstay of most commercial applications is the large-scale storage of ordered information, such as catalogs, customer lists, contract details, published text, and architectural designs.

With the advent of the World Wide Web, the demand for databases has increased. Though they may not know it, the customers of online bookshops and newspapers are using databases. Somewhere in the guts of the application a database is being queried and a response is offered.

Hibernate 4 is a library that simplifies the use of relational databases in Java applications by presenting relational data as simple Java objects, accessed through a session manager, therefore earning the description of being an “Object/Relational Mapper,” or ORM. It provides two kinds of programmatic interfaces: a “native Hibernate” interface and the Java EE-standard Java Persistence API.

There are solutions for which an ORM-like Hibernate is appropriate, and some for which the traditional approach of direct access via the Java Database Connectivity (JDBC) API is appropriate. We think that Hibernate represents a good first choice, as it does not preclude the simultaneous use of alternative approaches, even though some care must be taken if data is modified from two different APIs.

To illustrate some of Hibernate’s strengths, in this chapter we take a look at a brief example using Hibernate and contrast this with the traditional JDBC approach.

Plain Old Java Objects (POJOs)

In an ideal world,Footnote 2 it would be trivial to take any Java object and persist it to the database. No special coding would be required to achieve this, no performance penalty would ensue, and the result would be totally portable. In this ideal world, we would perhaps perform such an operation in a manner like that shown in Listing 1-1.

Listing 1-1. A Rose-Tinted View of Object Persistence

POJO pojo = new POJO();

ORMSolution magic = ORMSolution.getInstance();

magic.save(pojo);

There would be no nasty surprises, no additional work to correlate the class with tables in the database, and no performance problems.

Hibernate comes remarkably close to this, at least when compared with the alternatives,but there are configuration files to create and subtle performance and synchronization issues to consider. Hibernate does, however, achieve its fundamental aim: it allows you to store POJOs in the database. Figure 1-1 shows how Hibernate fits into your application between the client code and the database.

Figure 1-1.
figure 1figure 1

The role of Hibernate in a Java application

The common term for the direct persistence of traditional Java objects is object/relational mapping—that is, mapping the objects in Java directly to the relational entities in a database.

POJOs can be any Java object at all. Hibernate allows you to persist POJOs with very few constraints. Listing 1-2 is an example of a simple POJO that might be used to represent a message. (We’ll be modifying this class as we walk through some example code.)

Listing 1-2. The POJO Used in this Chapter’s Examples

package chapter01.pojo;

public class Message {

    String text;

    public Message() {

    }

    public Message(String text) {

        setText(text);

    public String getText() {

        return text;

    }

    public void setText(String text) {

        this.text = text;

    }

}

The sole condescension to Hibernate here is the provision of a default constructor. Hibernate demands that all POJOs to be stored should provide a default constructor;Footnote 3 but even that situation can be worked around when third-party classes fail to satisfy this limited requirement (through the use of an Interceptor mechanism in the Hibernate configuration; we will demonstrate this in Appendix A).

Origins of Hibernate and Object/Relational Mapping

If Hibernate is the solution, what was the problem? One answer is that doing things the right way when using JDBC requires a considerable body of code and careful observation of various rules (such as those governing connection management) to ensure that your application does not leak resources. This bit of code from the example JDBC PersistenceTest class shows how much needs to be done to retrieve a list of Message objects:

Listing 1-3. The JDBC Approach to Retrieving the POJO

@Test(dependsOnMethods = "saveMessage")

public void readMessage() {

    Connection connection = null;

    PreparedStatement ps = null;

    ResultSet rs = null;

    List<Message> list = new ArrayList<>();

    try {

        connection = DriverManager.getConnection("jdbc:hsqldb:db1;shutdown=true");

        ps = connection.prepareStatement("SELECT id, text FROM messages");

        rs = ps.executeQuery();

        while (rs.next()) {

            Message message = new Message();

            message.setId(rs.getLong(1));

            message.setText(rs.getString(2));

            list.add(message);

        }

        if (list.size() > 1) {

            Assert.fail("Message configuration in error; table should contain only one."

                +" Set ddl to drop-create.");

        }

        if (list.size() == 0) {

            Assert.fail("Read of initial message failed; check saveMessage() for errors."

                +" How did this test run?");

        }

        for (Message m : list) {

            System.out.println(m);

        }

        // eagerly free resources

        rs.close();

        ps.close();

        connection.close();

    } catch (SQLException e) {

        e.printStackTrace();

        throw new RuntimeException(e);

    } finally {

        try {

            if (rs != null && !rs.isClosed()) {

                rs.close();

            }

        } catch (SQLException ignored) {

        }

        try {

            if (ps != null && !ps.isClosed()) {

                ps.close();

            }

        } catch (SQLException ignored) {

        }

        try {

            if (connection != null && !connection.isClosed()) {

                connection.close();

            }

        } catch (SQLException ignored) {

        }

    }

}

Could some of this be trimmed down? Of course. The code to close the resources is very long (and since applications that use JDBC would do this sort of thing a lot, this code begs for refactoring into reusable methods). Using a connection pool instead of DriverManager would also help with this because most, if not all, connection pools automatically release resources on garbage collection. (In this case, though, eager release is still valuable.) You could also use classes like Spring’s JDBCTemplate to handle error conditions and connection management.

However, in the end the problem remains: there’s a lot of resource management involved, primarily around handling error and termination conditions, and the code itself is very brittle. If we added a field to the database, we would have to find every SQL statement that might need to access that field, and we would modify the code to accommodate it.

We also run into the issue of types with this code. This is a very simple object: it stores a simple numeric identifier with a simple string. However, if we wanted to store a geolocation, we’d have to break the location into its multiple properties (longitude and latitude, for example), and store each separately, which means your object model no longer cleanly matches your database.

All of this makes using the database directly look more and more flawed, and that’s not before factoring in other issues around object persistence and retrieval.

Hibernate as a Persistence Solution

Hibernate addresses a lot of these issues, or alleviates some of the pain where it can’t, so we’ll address the points in turn.

First, Hibernate provides cleaner resource management, which means that you do not have to worry about the actual database connections, nor do you have to have giant try/catch/finally blocks. Error conditions may occur such that you do need to handle them, of course; but these are exceptional conditions, not normal ones. (In other words, you’re handling exceptions that you actually should have to handle, instead of handling every exception that you might have to handle.)

Hibernate handles the mapping of the object to the database table, including constructing the database schema for you if you so configure it; it doesn’t require one table per object type; you can easily map one object to multiple tables. And Hibernate also handles relationships for you; for example, if you added a list of addresses to a Person object, you could easily have the addresses stored in a secondary table, constructed and managed by Hibernate.

In addition to mapping the object to the database table, Hibernate can handle mappings of new types to the database. The geolocation can be specified as its own table, can be normalized, or can have a custom serialization mechanism such that you can store it in whatever native form you need.

Hibernate’s startup takes a little bit longer than direct JDBC code, to be sure. However, system initialization time is usually not a meaningful metric. Most applications have long runtimes and the percentage of time spent in Hibernate initialization is irrelevant to the actual performance of the application; Hibernate’s advantages in maintenance and object management more than make up for any time the application spends in configuration. As usual, the right way to consider performance is through testing and analysis of an actual application, as opposed to spitballing anecdotal evidence.

Any Java object capable of being persisted to a database is a candidate for Hibernate persistence. Therefore, Hibernate is a natural replacement for ad hoc solutions (like our JDBC example), or as the persistence engine for an application that has not yet had database persistence incorporated into it. Furthermore, by choosing Hibernate persistence, you are not tying yourself to any particular design decisions for the business objects in your application—including which database the application uses for persistence, which is a configurable aspect.

A Hibernate Hello World Example

Listing 1-4 shows the same test as does Listing 1-3, using Hibernate instead of JDBC. Here, the factory object is initialized on test startup, but it serves the same role as the Connection initialization from the JDBC-based code.

Listing 1-4. The Hibernate Approach to Retrieving the POJO

SessionFactory factory;

@BeforeClass

public void setup() {

    Configuration configuration = new Configuration();

    configuration.configure();

    ServiceRegistryBuilder srBuilder = new ServiceRegistryBuilder();

    srBuilder.applySettings(configuration.getProperties());

    ServiceRegistry serviceRegistry = srBuilder.buildServiceRegistry();

    factory = configuration.buildSessionFactory(serviceRegistry);

}

@Test(dependsOnMethods = "saveMessage")

public void readMessage() {

    Session session = factory.openSession();

    @SuppressWarnings("unchecked")

    List<Message> list = (List<Message>) session.createQuery("from Message").list();

    if (list.size() > 1) {

        Assert.fail("Message configuration in error; table should contain only one."

            +" Set ddl to create-drop.");

    }

    if (list.size() == 0) {

        Assert.fail("Read of initial message failed; check saveMessage() for errors."

             +" How did this test run?");

    }

    for (Message m : list) {

        System.out.println(m);

    }

    session.close();

}

Note that the manual coding to populate the Message object has not been eradicated; rather, it has been moved into an external configuration file that isolates this implementation detail from the main logic.

Also note that we’re using the Hibernate Query Language (HQL) to locate the Message. HQL is very powerful, and this is a poor usage of it; we’ll dig into HQL quite a bit as we progress.

Some of the additional code in the Hibernate example given in Listing 1-4 actually provides functionality (particularly transactionality and caching) beyond that of the JDBC example.

Mappings

As we have intimated, Hibernate needs something to tell it which tables relate to which objects. In Hibernate parlance, this is called a mapping. Mappings can be provided either through Java annotations or through an XML mapping file. In this book, we will focus on using annotations, as we can mark up the POJO Java classes directly. Using annotations gives you a clear picture of the structure at the code level, which seems to be preferred by people writing code.Footnote 4 Hibernate also takes a configuration-by-exception approach for annotations: if we are satisfied with the default values that Hibernate provides for us, we do not need to explicitly provide them as annotations. For instance, Hibernate uses the name of the POJO class as the default value of the database table to which the object is mapped. In our example, if we are satisfied with using a database table named Message, we do not need to define it in the source code.

In fact, if our only access is through Hibernate, we don’t really even need to know what the table name is; as our example shows, we query based on object type and not the table name. Hibernate automatically constructs the query such that the correct table name is used, even if we were to change the table name to “Messages,” for example.

Listing 1-5 shows the Message POJO with annotations for mapping the Java object into the database. It adds an identifier and a toString( ) method to our original POJO; we’d want the ID in any event, but the toString( ) adds convenience as we use the class. (We’ll eventually want to add an equals( ) and hashCode( ) as well.)

Listing 1-5. The POJO with Mapping Annotations

package chapter01.hibernate;

import javax.persistence.*;

@Entity

public class Message {

    @Id

    @GeneratedValue(strategy = GenerationType.AUTO)

    Long id;

    @Column(nullable = false)

    String text;

    public Message(String text) {

        setText(text);

    }

    public Message() {

    }

    public Long getId() {

        return id;

    }

    public void setId(Long id) {

        this.id = id;

    }

    public String getText() {

        return text;

    }

    public void setText(String text) {

        this.text = text;

    }

    @Override

    public String toString() {

        return "Message{" +

                "id=" + getId() +

                ", text='" + getText() + '\'' +

                '}';

    }

}

Persisting an Object

In the interest of completeness, here’s the method used to write a Message into the database with Hibernate. (The JDBC version of this code is present in the downloadable examples, but adds nothing to the knowledge of how to use Hibernate.)

Listing 1-6. Saving a Message Object in Hibernate

@Test

public void saveMessage() {

    Message message = new Message("Hello, world");

    Session session = factory.openSession();

    Transaction tx = session.beginTransaction();

    session.persist(message);

    tx.commit();

    session.close();

}

Summary

In this chapter, we have considered the problems and requirements that have driven the development of Hibernate. We have looked at some of the details of a trivial example application written with and without the aid of Hibernate. We have glossed over some of the implementation details, but we will discuss these in depth in Chapter 3.

In the next chapter, we will look at the architecture of Hibernate and how it is integrated into your applications.