The method <literal>hsqlCleanup</literal> listed below performs some necessary shutdown code telling HsqlDB to remove all its lock-files and flush its logs. This is not a direct hibernate requirement, so this would not be necessary when using a "real" database.
Please not that all the transaction and session handling code in these examples is extremely unclean, mainly for shortness. Please don't use that in a production app. For a more detailed explanation on how to handle transactions properly see <xreflinkend="transactions-demarcation"/>.
</para>
<para>
If we now run the application with <literal>run.bat store Party</literal> an <literal>Event</literal> object will be created an persisted to the database.
</para>
<para>
But now we want to list our stored events, so we modify the <literal>main</literal> method some more:
When the first argument is "list", we call <literal>listEvents()</literal> and print all Events contained in the returned list. <literal>listEvents()</literal> is where the interesting stuff happens:
</para>
<programlisting><![CDATA[private List listEvents() {
try {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
List result = session.createQuery("from Event").list();
tx.commit();
hsqlCleanup(session);
session.close();
return result;
} catch (HibernateException e) {
throw new RuntimeException(e.getMessage());
}
} ]]></programlisting>
<para>
What we do here is using a HQL (Hibernate Query Language) query to load all existing <literal>Event</literal> objects from the database. Hibernate will generate the appropriate SQL, send it to the database and populate <literal>Event</literal> objects with the data. You can create more complex querys with HQL of course, which we will see in later chapters.
</para>
<para>
So in this chapter we learned how to setup Hibernate, how to create a mapping for our classes, and how to store and retrieve objects using Hibernate.
</para>
<para>
That's it for the first chapter, in the next part we will replace our ugly <literal>build.bat</literal> with an ant-based build system.
</para>
</sect2>
</sect1>
<sect1id="tutorial-ant">
<title>Part 2 - Building with Ant</title>
<para>
In this short chapter we will replace the ugly <literal>build.bat</literal> file we created with a nice little Ant build file. You will need to have Ant installed - get it from the <ulinkurl="http://ant.apache.org/bindownload.cgi">Ant download page</ulink>. How to install Ant will not be covered here. Please refer to the <ulinkurl="http://ant.apache.org/manual/index.html">Ant manual</ulink>. After you have installed Ant, we can start to create the buildfile. It will be called <literal>build.xml</literal> and placed directly in the development directory and will replace the <literal>build.bat</literal> (which you can delete).
The <literal>project</literal> tags surround the whole buildfile. There are two attributes, the <literal>name</literal> attribute which gives a name for the project being built, and the <literal>default</literal> attribute which specifies the default target which will be run if we launch Ant without specifying a target.
</para>
<para>
Inside of the <literal>project</literal> tags, we have to give at least one <literal>target</literal> block, where we can tell Ant what to do - in this case, ant will do just nothing. You can now run the build by running <literal>ant</literal> on the command line inside the development directory.
</para>
<para>
You should get an output like this:
</para>
<programlisting><![CDATA[Buildfile: build.xml
compile:
BUILD SUCCESSFUL
Total time: 1 second ]]></programlisting>
<para>
This tells us Ant did run successfully and which build file was used. The default target was run, which is why the <literal>compile:</literal> part of the output shows us the compile target was executed. We can however give Ant an explicit target to run by calling <literal>ant compile</literal> from the command line, which will run the compile target.
</para>
<para>
So now we want Ant to actually compile our classes. So we insert the <literal>javac</literal> task inside the <literal>target</literal> elements:
This will tell Ant to launch the java compiler and compile everything it can find under the the <literal>src</literal> directory and place the generated class files in the <literal>bin</literal> directory. However if we now run Ant, we will get a lot of compile errors, because the compiler can not find the hibernate classes. So we have to tell the compiler about the classpath to use, just as we did in the old <literal>build.bat</literal>:
This will tell Ant to find all files in the lib directory with .jar as file ending and add them to the classpath used for compilation. If you now run Ant, you should get an output like this:
[javac] Compiling 2 source files to C:\hibernateTutorial\part2\bin
BUILD SUCCESSFUL
Total time: 1 second ]]></programlisting>
</sect2>
<sect2id="tutorial-ant-depends">
<title>Dependant targets</title>
<para>
Great, so now we got ant to compile our two java files. This however still leaves the <literal>log4j.properties</literal> and the mapping file, which are not copied to the <literal>bin</literal> directory. We will take care of this now by adding an additional target:
So this tells ant when it executes the copy-resources target to copy everything it can find in the <literal>src</literal> directory or in any directories below to the <literal>bin</literal> directory but exclude all java files anywhere under the <literal>src</literal> directory (this is what the ** in front of the / means).
</para>
<para>
So if you run Ant now, you will see ... actually nothing. Ant will execute the <literal>compile</literal> target and not touch our <literal>copy-resources</literal> target. So what we need to do now is to tell ant it has to execute <literal>copy-resources</literal> before the <literal>compile</literal> target - this is what the <literal>depends</literal> attribute of the <literal>target</literal> element is for:
So if you now execute ant you should see output like this:
</para>
<programlisting><![CDATA[Buildfile: build.xml
copy-resources:
[copy] Copying 3 files to C:\hibernateTutorial\part2\bin
compile:
BUILD SUCCESSFUL
Total time: 0 seconds ]]></programlisting>
<para>
So Ant has now executed both targets and copied our resources over to the <literal>bin</literal> directory. You will notice that ant does not print anything under the <literal>compile</literal> target. Ant notices that no source files have changed and does not compile them again. The same will happen for <literal>copy-resources</literal> - ant will not copy our files again unless we change them, or remove them from the <literal>bin</literal> directory.
</para>
</sect2>
<sect2id="tutorial-ant-properties">
<title>Using Properties</title>
<para>
So now we have a nice little build script in place. We could well go on from here. You will notice however that our directory names are spread all over the build file. Should we ever want to change them, we would have to change them all over the build file. We will solve this problem by using Ant <literal>property</literal> declarations:
So we can define our properties using the <literal>property</literal> tag, and can insert them anywhere in the build file using the name we declared for the property surrounded with <literal>${}</literal>. Notice the <literal>${basedir}</literal> property we use in the property declarations - this is a property predefined by Ant, which contains the path of the directory where Ant is executed.
</para>
<para>
In the next chapter, we will create associations between our classes using java collections.
</para>
</sect2>
</sect1>
<sect1id="tutorial-associations">
<title>Part 3 - Mapping Associations</title>
<para>
As we now have mapped a single object, we are now going to add various object associations. For a starter, we will add users to our application, and store a list of participating users with every event. In addition, we will give each user the possibility to watch various events for updates. Every user will have the standard personal data, including a list of email addresses.
</para>
<sect2id="tutorial-associations-mappinguser">
<title>Mapping the User class</title>
<para>
For the beginning, our User class will be very simple:
So far this is only basic hibernate usage. But now we will add the collection of favorite events to the <literal>User</literal> class. For this we can use a simple java collection - a <literal>Set</literal> in this case, because the collection will not contain duplicate elements and the ordering is not relevant for us.
</para>
<para>
So our <literal>User</literal> class now looks like this:
As you can see, we tell Hibernate about the set property called <literal>favouriteEvents</literal>. The <literal>set</literal> element tells Hibernate that the collection property is a <literal>Set</literal>. We have to consider what kind of association we have: Every <literal>User</literal> my have multiple favorite events, but every <literal>Event</literal> may be a favorite of multiple users. So we have a <literal>many-to-many</literal> association here, which we tell Hibernate using the <literal>many-to-many</literal> tag. For many to many associations, we need an association table where hibernate can store the associations. The table name can be configured using the <literal>table</literal> attribute of the <literal>set</literal> element. The association table needs at least two columns, one for every side of the association. The column name for the User side can be configured using the <literal>key</literal> element. The column name for the Event side is configured using the <literal>column</literal> attribute of the <literal>many-to-many</literal> element.
</para>
<para>
So the relational model used by hibernate now looks like this:
After loading an <literal>User</literal> and an <literal>Event</literal> with Hibernate, we can simply modify the collection using the normal collection methods. As you can see, there is no explicit call to <literal>session.update()</literal> or <literal>session.save()</literal>, Hibernate automatically detects the collection has been modified and needs to be saved.
</para>
<para>
Sometimes however, we will have a User or an Event loaded in a different session. This is of course possible to:
</para>
<programlisting><![CDATA[private void addFavouriteEvent(Long userId, Long eventId) {
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
User user = (User) session.load(User.class, userId);
This time, we need an explicit call to <literal>update</literal> - Hibernate can't know if the object actually changed since it was loaded in the previous session. So if we have an object from an earlier session, we must update it explicitly. If the object gets changed during session lifecycle we can rely on Hibernates automatic dirty checking.
</para>
<para>
Since Hibernate 2.1 there is a third way - the object can be reassociated with the new session using session.lock(object, LockMode.NONE):
</para>
<programlisting><![CDATA[private void addFavouriteEvent(Long userId, Long eventId) {
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
User user = (User) session.load(User.class, userId);
Often you will want to map collections of simple value types - like a collections of Integers or a collection of Strings. We will do this for our <literal>User</literal> class with a collection of Strings representing email addresses. So we add another <literal>Set</literal> to our class:
As you can see, the new set mapping looks a lot like the last one. The difference is the <literal>element</literal> part, which tells Hibernate that the collection does not contain an association with a mapped class, but a collection of elements of type <literal>String</literal>. Once again, the <literal>table</literal> attribute of the <literal>set</literal> element determines the table name. The <literal>key</literal> element determines the column name in the <literal>USER_EMAILS</literal> table which establishes the relation to the <literal>USERS</literal> table. The <literal>column</literal> attribute in the <literal>element</literal> element determines the column name where the <literal>String</literal> values will be actually stored.
User user = (User) session.load(User.class, userId);
user.getEmails().add(email);
tx.commit();
hsqlCleanup(session);
HibernateUtil.closeSession();
} ]]></programlisting>
<para>
As you see, you can use the mapped collection just like every java collection. Hibernates automatic dirty detection will do the rest of the job. For objects from another session - or disconnected objects, as we will call them from now - the same as above aplies. Explicitly update them, or reassociate them before updating using <literal>session.lock(object, LockMode.NONE)</literal>.
</para>
</sect2>
<sect2id="tutorial-associations-bidirectional">
<title>Bidirectional associations using Sets</title>
<para>
Next we are going to map a bidirectional association - the User class will contain a list of events where the user participates, and the Event class will contain a list of participating users. So first we adjust our classes:
The mapping for a bidirectional association looks very much like a unidirectional one, except the <literal>set</literal> elements are mapped for both classes:
As you see, this are normal <literal>set</literal> mappings in both mapping documents. Notice that the column names in <literal>key</literal> and <literal>many-to-many</literal> are swapped in both mapping documents. The most important addition here is the <literal>inverse="true"</literal> attribute in the <literal>set</literal> element of the <literal>User</literal> mapping.
</para>
<para>
What this means is the other side - the <literal>Event</literal> class - will manage the relation. So when only the <literal>Set</literal> in the <literal>User</literal> class is changed, this will not get perstisted. Also when using explicit update for detatched objects, you need to update the one not marked as inverse. Let's see an example:
</para>
</sect2>
<sect2id="tutorial-associations-usingbidir">
<title>Using bidirectional mappings</title>
<para>
At first it is important to know that we are still responsible for keeping our associations properly set up on the java side - that means if we add an <literal>Event</literal> to the <literal>eventsJoined Set</literal> of an <literal>User</literal> object, we also have to add this <literal>User</literal> object to the <literal>participatingUsers Set</literal> in the <literal>Event</literal> object. So we will add some convenience methods to the <literal>Event</literal> class:
Notice that the get and set methods for <literal>participatingUsers</literal> are now protected - this allows classes in the same package and subclasses to still access the methods, but prevents everybody else from messing around with the collections directly. We should do the same to the <literal>getEventsJoined()</literal> and <literal>setEventsJoined()</literal> methods in the User class.
</para>
<para>
Now using the association in <literal>EventManager</literal> is very easy:
</para>
<programlisting><![CDATA[private void addParticipant(Long userId, Long eventId) {
try {
Session session = HibernateUtil.currentSession();
Transaction tx = session.beginTransaction();
User user = (User) session.load(User.class, userId);
In the next chapter we will integrate Hibernate with Tomcat and WebWork to create a better test environment - as you will notice when you look at the code, the <literal>EventManager</literal> class is really ugly now.
</para>
</sect2>
</sect1>
<sect1id="tutorial-tomcatww">
<title>Part 4 - Tomcat and WebWork</title>
<para>
In this chapter we will finally get rid of our ugly command-line-based test application and integrate Tomcat, WebWork and Hibernate to create a little web-based application.
</para>
<para>
The first step for you is to install Tomcat - you can download it <ulinkurl="http://jakarta.apache.org/site/binindex.cgi">here</ulink>. You can find documentation and install instructions for Tomcat <ulinkurl="http://jakarta.apache.org/tomcat/tomcat-5.5-doc/index.html">here</ulink>.
</para>
<sect2id="tutorial-tomcatww-develdir">
<title>Restructuring the development directory</title>
<para>At first, we will restructure our working directory, to keep the parts of our application nicely separated:</para>
<programlisting><![CDATA[.
+src
+de
+gloegl
+road2hibernate
+data
User.java
Event.java
User.hbm.xml
Event.hbm.xml
+actions
hibernate.cfg.xml
log4j.properties
+config
+static-web
+views
+lib
antlr-2.7.4.jar
cglib-full-2.0.2.jar
commons-collections-2.1.1.jar
commons-logging-1.0.4.jar
hibernate3.jar
jta.jar
dom4j-1.5.2.jar
jdbc2_0-stdext.jar
log4j-1.2.9.jar
hsqldb.jar ]]></programlisting>
<para>
We moved our classes and mappings to the data subdirectory of road2hibernate. Of course we need to adjust our package declaration in the java files and the classnames in the mapping files.
</para>
<para>
In addition, we created various new directories:
</para>
<itemizedlist>
<listitem>
<para>
<literal>src/de/gloegl/road2hibernate/actions</literal> will contain the source code for our WebWork actions.
</para>
</listitem>
<listitem>
<para>
<literal>config</literal> will contain the config files which will later be placed in <literal>WEB-INF/config</literal> of our web app.
</para>
</listitem>
<listitem>
<para>
<literal>static-web</literal> will contain all static content of our application, like html and image files.
</para>
</listitem>
<listitem>
<para>
<literal>views</literal> will contain our view files which contain the html later displayed to the user.
</para>
</listitem>
</itemizedlist>
<para>
As we will use WebWork for our application and Velocity as template engine for the views, you will need to get WebWork from <ulinkurl="http://www.opensymphony.com/webwork/">here</ulink>. You will need the webwork-2.1.7.jar from the WebWork download, and all jar files in the lib/core folder of the WebWork distribution. Place all of them into the lib directory of the development dir.
</para>
</sect2>
<sect2id="tutorial-tomcatww-configuring">
<title>Configuring WebWork</title>
<para>
Now we will configure our application to use WebWork. At first we need a <literal>web.xml</literal> which we will place in the <literal>config</literal> directory:
</para>
<programlisting><![CDATA[<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
<!-- Include webwork defaults (from WebWork JAR). -->
<includefile="webwork-default.xml"/>
<!-- Configuration for the default package. -->
<packagename="default"extends="webwork-default">
</package>
</xwork> ]]></programlisting>
<para>
This file contains only the declaration of the packages where WebWork will look for its actions.
</para>
</sect2>
<sect2id="tutorial-tomcatww-updatebuild">
<title>Updating the build process</title>
<para>
Now we will make our build process place all the files together and generate the appropriate structure for the web application. We update our <literal>build.xml</literal>:
Running this target will create a directory called <literal>war</literal>, which will contain the web application just like it will later be structured in the war file. After running this target, the war directory will look like this:
</para>
<programlisting><![CDATA[ +war
+WEB-INF
web.xml
+classes
+de
+gloegl
+road2hibernate
+data
User.class
Event.class
User.hbm.xml
Event.hbm.xml
+actions
hibernate.cfg.xml
log4j.properties
xwork.xml
+lib
<alllibraryfileshere>]]></programlisting>
<para>
Now we will add Tomcat specific tasks to our build file, so we can directly install our application into Tomcat using Ant. You need to adjust the example to your environment. Modify the <literal>build.xml</literal> again:
So now startup Tomcat and run <literal>ant install</literal> from the commandline - this will install the application to Tomcat. Now you should be able to access the eventmanager application by pointing your browser to http://localhost:8080/eventmanager/ - however you will only get a directory listing produced by Tomcat. We will now have to create some content for the application to display.
</para>
</sect2>
<sect2id="tutorial-tomcatww-firstaction">
<title>A first WebWork action</title>
<para>
Our first WebWork action will be very simple - it will do nothing so far but forwarding to a view. We create <literal>/src/de/gloegl/road2hibernate/actions/EventList.java</literal>:
The class extends <literal>ActionSupport</literal> but does not override any methods. So this will rely on the default behavior of <literal>ActionSupport</literal>: The action will forward to the view defined as the <literal>SUCCESS</literal> view. This is what we still have to do in the <literal>xwork.xml</literal> file:
</para>
<programlisting><![CDATA[<!DOCTYPE xwork PUBLIC "-//OpenSymphony Group//XWork 1.0//EN"
This defines an action called <literal>eventlist</literal> which will be handled by our <literal>EventList</literal> class. In addition, the <literal>success</literal> view gets defined. We now have to write the <literal>eventlist.vm</literal> file, which will be placed in the <literal>views</literal> folder - Ant will copy it to the correct location.
</para>
<programlisting><![CDATA[<html>
<head>
<title>Event List</title>
</head>
<body>
<h1>Successful</h1>
</body>
</html> ]]></programlisting>
<para>
As you see, this is just a simple HTML file - we will modify it to include dynamic content later on. Now run ant reload. Now you should be able to test the action by pointing your browser to <literal>http://localhost:8080/eventmanager/eventlist.action</literal> - you should see the "Success" headline in your browser.
</para>
</sect2>
<sect2id="tutorial-tomcatww-osiv">
<title>The "Open Session in View" pattern</title>
<para>
When using such features as lazy loading, Hibernate needs an open session. To do this easily in a web application we will use a simple pattern. We will create a servlet filter which will manage our session and close it at the end of the web request. Also we improve our <literal>HibernateUtil</literal> class to include transaction handling per-thread:
</para>
<programlisting><![CDATA[...
public static final ThreadLocal threadTransaction = new ThreadLocal();
catch (Exception ex) { ex.printStackTrace(); throw new RuntimeException(ex); }
}
} ]]></programlisting>
<para>
Let's look at what is done here: The <literal>HibernateUtil</literal> class will store a Hibernate session in a <literal>ThreadLocal</literal> variable. A <literal>ThreadLocal</literal> will contain an instance of a variable once for every thread. So if there are two parallel Threads executing, the <literal>ThreadLocal</literal> will contain two session. In <literal>SessionManager</literal>, the <literal>doFilter</literal> method will be invoked on every request. It will let the request go on by calling <literal>chain.doFilter()</literal>. After the request processing finished and <literal>chain.doFilter()</literal> returns, it retrieves the <literal>Session</literal> for the current thread from the <literal>ThreadLocal</literal> and closes it. It also commits the transaction - if the transaction was already committed or rolled back, <literal>HibernateUtil</literal> will simply do nothing.
</para>
<para>
Our Actions can invoke the static <literal>currentSession()</literal> method of the <literal>HibernateUtil</literal> class to get a <literal>Session</literal> - if it is invoked multiple times during one thread, the same session will be used every time.
</para>
<para>
The <literal>HibernateUtil.rollbackTransaction()</literal> method can be invoked by our Actions to have the transaction rolled back.
</para>
<para>
Also in the <literal>destroy()</literal> method of the filter, we once again do our hsqldb-housekeeping work.
</para>
<para>
We have to modify the classpath in our <literal>build.xml</literal> compile target to get this to work:
We simply retrieve the session from our <literal>HibernateUtil</literal>, and load the list of Events using <literal>session.find()</literal>. Then we assign it to an attribute of our action. Now we can use this attribute from our <literal>eventlist.vm</literal>view:
</para>
<programlisting><![CDATA[<html>
<head>
<title>Event List</title>
</head>
<body>
<h1>Events</h1>
<ul>
#foreach( $event in $events )
<li>$event.title</li>
#end
</ul>
</body>
</html>]]></programlisting>
<para>
Using the velocity template language, we simply iterate over the events, and print their titles. Now that our infrastructure is in place, you see how easy it is to create actions and views. If you now call http://localhost:8080/eventmanager/eventlist.action, you will see most likely nothing - because we have no events in the database. So we will create another action to create events.
</para>
<para>
But at first we will finally create an <literal>index.html</literal> file, where we link our actions - place it in the <literal>static-web</literal> subdirectory of the project:
As you see, this action has two <literal>doXXX()</literal> methods. The reason is we will use WebWorks ability to invoke different methods of the action class. Lets have a look at the <literal>xwork.xml</literal> first:
</para>
<programlisting><![CDATA[<!DOCTYPE xwork PUBLIC "-//OpenSymphony Group//XWork 1.0//EN"
So we have now a new action called <literal>newevent</literal>. This action has two results, the <literal>success</literal> result (which is returned by the <literal>execute()</literal> method) and the <literal>input</literal> result (which is returned by the <literal>doEnter()</literal> method). If you look at the <literal>index.html</literal> you will notice the link to <literal>"newevent!enter.action"</literal> - this tells WebWork to invoke the <literal>enter()</literal> method in the action. The submit-target of our form however will just link to <literal>"newevent.action"</literal>, invoking the default <literal>execute()</literal> method.
</para>
<para>
Finally we need to code the <literal>newEventForm.vm</literal> view file we specified, again in the <literal>views</literal> directory: