Thursday, October 28, 2010

Hibernate Basics

Hibernate Basics


Cascades

If you've worked with relational databases, you've no doubt encountered cascades. Cascades propagate certain operations on a table (such as a delete) to associated tables. (Remember that tables are associated through the use of foreign keys.) Suppose that when you delete an Event, you also want to delete each of the Speaker instances associated with the Event. Instead of having the application code perform the deletion, Hibernate can manage it for you.
Hibernate supports ten different types of cascades that can be applied to many-to-one associations as well as collections. The default cascade is none. Each cascade strategy specifies the operation or operations that should be propagated to child entities. The cascade types that you are most likely to use are the following:
  • all -All operations are passed to child entities: save , update , and delete.
  • save-update -Save and update ( and UPDATE , respectively) are passed to child entities.
  • delete -Deletion operations are passed to child entities.
  • delete-orphan -All operations are passed to child entities, and objects no longer associated with the parent object are deleted.
The cascade element is added to the desired many-to-one or collection element. For example, the following configuration instructs Hibernate to delete the child Speaker elements when the parent Event is deleted:
<set name="speakers"cascade="delete">
      <key column="event_id"/>
      <one-to-many class="Speaker"/>
    </set>
That's all there is to configuring cascades. It's important to note that Hibernate doesn't pass the cascade off to the database. Instead, the Hibernate service manages the cascades internally. This is necessary because Hibernate has to know exactly which objects are saved, updated, and deleted.
With the configuration and mapping files in hand, you're ready to persist objects to the database with Hibernate.

Fetching associated objects

When an object has one or more associated objects, it's important to consider how associated objects will be loaded. Hibernate 3 offers you two options. You can either retrieve associated objects using an outer join or by using a separate SELECT statement. The fetch attribute allows you to specify which method to use:
<many-to-one name="location"class="Location"fetch="join"/>
When an Event instance is loaded, the associated Location instance will be loaded using an outer join. If you wanted to use a separate select, the many-to-one element would look like this:
<many-to-one name="location"class="Location"fetch="select"/>
This also applies to child collections, but you can only fetch one collection using a join per persistent object. Additional collections must be fetched using the SELECT strategy.
If you're using Hibernate 2, the fetch attribute is not available. Instead, you must use the outer-join attribute for many-to-one associations. (There is no support for retrieving collections using a SELECT in Hibernate 2.) The outer-join attribute takes either a true or false value.

Building the SessionFactory

Hibernate's SessionFactory interface provides instances of the Session class, which represent connections to the database. Instances of SessionFactory are thread-safe and typically shared throughout an application. Session instances, on the other hand, aren't thread-safe and should only be used for a single transaction or unit of work in an application.

Configuring the SessionFactory

The Configuration class kicks off the runtime portion of Hibernate. It's used to load the mapping files and create a SessionFactory for those mapping files. Once these two functions are complete, the Configuration class can be discarded. Creating a Configuration and SessionFactory instance is simple, but you have some options. There are three ways to create and initialize a Configuration object.
This first snippet loads the properties and mapping files defined in the hibernate.cfg.xml file and creates the SessionFactory:
Configuration cfg =new Configuration();
    SessionFactory factory =cfg.configure().buildSessionFactory();
The configure()method tells Hibernate to load the hibernate.cfg.xml file. Without that, only hibernate.properties would be loaded from the classpath. The Configuration class can also load mapping documents programmatically:
Configuration cfg =new Configuration();
    cfg.addFile("com/manning/hq/ch03/Event.hbm.xml");
Another alternative is to have Hibernate load the mapping document based on the persistent class. This has the advantage of eliminating hard-coded filenames in the source code. For instance, the following code causes Hibernate to look for a file named com/manning/hq/ Event.hbm.xml in the classpath and load the associated class:
Configuration cfg =new Configuration();
    cfg.addClass(com.manning.hq.ch03.Event.class);
Since applications can have tens or hundreds of mapping definitions, listing each definition can quickly become cumbersome. To get around this, the hibernate.cfg.xml file supports adding all mapping files in a JAR file. Suppose your build process creates a JAR file named application.jar, which contains all the classes and mapping definitions required. You then update the hibernate.cfg.xml file:
<mapping jar="application.jar"/>
Of course, you can also do this programmatically with the Configuration class:
Configuration.addJar(new java.io.File("application.jar"));
Keep in mind that the JAR file must be in the application classpath. If you're deploying a web application archive (WAR) file, your application JAR file should be in the /WEB-INF/lib directory in the WAR file.
The four methods used to specify mapping definitions to the Hibernate runtime can be combined, depending the requirements for your project. However, once you create the SessionFactory from the Configuration instance, any additional mapping files added to the Configuration instance won't be reflected in the SessionFactory . This means you can't add new persistent classes dynamically.
You can use the SessionFactory instance to create Session instances:
Session session =factory.openSession();
Instances of the Session class represent the primary interface to the Hibernate framework. They let you persist objects, query persistent objects, and make persistent objects transient. Let's look at persisting objects with Hibernate.

Persisting objects

Persisting a transient object with Hibernate is as simple as saving it with the Session instance:
Event event =new Event();
    //populate the event
    Session session =factory.openSession();
    session.save(event);
    session.flush();
Calling save(...)for the Event instance assigns a generated ID value to the instance and persists the instance. (Keep in mind that Hibernate doesn't set the ID value if the generator type is assigned.) The flush() call forces persistent objects held in memory to be synchronized to the database. Session’s don't immediately write to the database when an object is saved. Instead, the Session queues a number of database writes to maximize performance.
If you would like to update an object that is already persistent, the update(...)method is available. Other than the type of SQL operation executed, the difference between save(...)and update(...)is that update(...)doesn't assign an ID value to the object. Because of this minor difference, the Session interface provides the saveOrUpdate(...) methods, which determine the correct operation to execute on the object. How does Hibernate know which method to call on an object?
When we described the mapping document, we mentioned the unsaved-value attribute. That attribute comes into play when you use the saveOrUpdate(...)method. Suppose you have a newly created Event instance. The id property is null until it's persisted by Hibernate. If the value is null, Hibernate assumes that the object is transient and assigns a new id value before saving the instance. A non-null id value indicates that the object is already persistent; the object is updated in the database, rather than inserted.
You could also use a long primitive to store the primary key value. However, using a primitive type also means that you must update the unsaved-value attribute value to 0, since primitive values can't be null.
TIP
In general, we suggest that you use object wrapper classes for primitive types in your persistent classes. To illustrate this, suppose you have a legacy database with a boolean column, which can be null. Your persistent class, mapped to the legacy table, also has a boolean property. When you encounter a row in the legacy table with a null boolean value, Hibernate throws a Property-AccessException since a boolean primitive can't be null-only true or false. However, you can avoid this problem if your persistent class property is of type java.lang.Boolean, which can be null, true, or false.
Here's the necessary code to persist an Event instance:
Configuration cfg =new Configuration();
    SessionFactory factory =cfg.buildSessionFactory();
    Event event =new Event();
    //populate the Event instance
    Session session =factory.openSession();
    session.saveOrUpdate(event);
    session.flush();
    session.close();
The first two lines create the SessionFactory after loading the configuration file from the classpath. After the Event instance is created and populated, the Session instance, provided by the SessionFactory , persists the Event. The Session is then flushed and closed, which closes the JDBC connection and performs some internal cleanup. That's all there is to persisting objects.
Once you've persisted a number of objects, you'll probably want to retrieve them from the database. Retrieving persistent objects is the topic of the next section.

Retrieving objects

Suppose you want to retrieve an Event instance from the database. If you have the Event ID, you can use a Session to return it:
Event event =(Event)session.load(Event.class,eventId);
    session.close();
This code tells Hibernate to return the instance of the Event class with an ID equal to eventId. Notice that you're careful to close the Session, returning the database connection to the pool. There is no need to flush the Session, since you're not persisting objects-only retrieving them. What if you don't know the ID of the object you want to retrieve? This is where HQL enters the picture.
The Session interface allows you to create Query objects to retrieve persistent objects. (In Hibernate 2, the Session interface supported a number of overloaded find methods. They were deprecated in Hibernate 3.) HQL statements are object-oriented, meaning that you query on object properties instead of database table and column names. Let’s look at some examples using the Query interface.
This example returns a collection of all Event instances. Notice that you don't need to provide a select ...clause when returning entire objects:
Query query =session.createQuery("from Event");
    List events =query.list();
This query is a little more interesting since we're querying on a property of the Event class:
Query query =session.createQuery("from Event where name ="+
                                    "'Opening Presentation'");
    List events =query.list();
We've hardcoded the name value in the query, which isn't optimal. Let's rewrite it:
Query query =session.createQuery("from Event where name =?",
                                     "Opening Presentation");
    query.setParameter(0,"Opening Presentation",Hibernate.STRING);
    List events =query.list();
The question mark in the query string represents the variable, which is similar to the JDBC PreparedStatement interface. The second method parameter is the value bound to the variable, and the third parameter tells Hibernate the type of the value. (The Hibernate class provides constants for the built-in types, such as STRING , INTEGER , and LONG , so they can be referenced programmatically.)
One topic we haven't touched on yet is the cache maintained by the Session. The Session cache tends to cause problems for developers new to Hibernate, so we'll talk about it next.

The Session cache

One easy way to improve performance within the Hibernate service, as well as your applications, is to cache objects. By caching objects in memory, Hibernate avoids the overhead of retrieving them from the database each time. Other than saving overhead when retrieving objects, the Session cache also impacts saving and updating objects. Let's look at a short code listing:
Session session =factory.openSession();
    Event e =(Event)session.load(Event.class,myEventId);
    e.setName("New Event Name");
    session.saveOrUpdate(e);
    //later,with the same Session instance
    Event e =(Event)session.load(Event.class,myEventId);
    e.setDuration(180);
    session.saveOrUpdate(e);
    session.flush();
This code first retrieves an Event instance, which the Session caches internally. It then does the following: updates the Event name, saves or updates the Event instance, retrieves the same Event instance (which is stored in the Session cache), updates the duration of the Event,and saves or updates the Event instance. Finally, you flush the Session.
All the updates made to the Event instance are combined into a single update when you flush the Session. This is made possible in part by the Session cache.
The Session interface supports a simple instance cache for each object that is loaded or saved during the lifetime of a given Session. Each object placed into the cache is keyed on the class type, such as The Session cache com.manning.hq.ch03.Event, and the primary key value. However, this cache presents some interesting problems for unwary developers.
A common problem new developers run into is associating two instances of the same object with the same Session instance, resulting in a NonUniqueObjectException. The following code generates this exception:
Session session =factory.openSession();
    Event firstEvent =(Event)session.load(Event.class,myEventId);
    //...perform some operation on firstEvent
    Event secondEvent =new Event();
    secondEvent.setId(myEventId);
    session.save(secondEvent);
This code opens the Session instance, loads an Event instance with a given ID, creates a second Event instance with the same ID, and then attempts to save the second Event instance, resulting in the Non-UniqueObjectException.
Any time an object passes through the Session instance, it's added to the Session’s cache. By passes through, we're referring to saving or retrieving the object to and from the database. To see whether an object is contained in the cache, call the Session.contains()method. Objects can be evicted from the cache by calling the Session.evict() method. Let's revisit the previous code, this time evicting the first Event instance:
Session session =factory.openSession();
    Event firstEvent =(Event)session.load(Event.class,myEventId);
    //...perform some operation on firstEvent
    if (session.contains(firstEvent)){
          session.evict(firstEvent);
    }
    Event secondEvent =new Event();
    secondEvent.setId(myEventId);
    session.save(secondEvent);
The code first opens the Session instance and loads an Event instance with a given ID. Next, it determines whether the object is contained in the Session cache and evicts the object if necessary. The code then creates a second Event instance with the same ID and successfully saves the second Event instance.
If you simply want to clear all the objects from the Session cache, you can call the aptly named Session.clear()method.
So far, we've covered the basics of Hibernate configuration and use. Now we'll address some of the advanced configuration options that come into play when you deploy Hibernate in an application server.

No comments:

Post a Comment