Hibernate.orgCommunity Documentation
Table of Contents
Intended for new users, this chapter provides an step-by-step introduction to Hibernate, starting with a simple application using an in-memory database. The tutorial is based on an earlier tutorial developed by Michael Gloegl. All code is contained in thetutorials/web directory of the project source.
This tutorial expects the user have knowledge of both Java and SQL. If you have a limited knowledge of JAVA or SQL, it is advised that you start with a good introduction to that technology prior to attempting to learn Hibernate.
The distribution contains another example application under thetutorial/eg project source directory.
For this example, we will set up a small database application that can store events we want to attend and information about the host(s) of these events.
Although you can use whatever database you feel comfortable using, we will useHSQLDB (an in-memory, Java database) to avoid describing installation/setup of any particular database servers.
The first thing we need to do is to set up the development environment. We will be using the "standard layout" advocated by alot of build tools such asMaven. Maven, in particular, has a good resource describing thislayout. As this tutorial is to be a web application, we will be creating and making use ofsrc/main/java,src/main/resources andsrc/main/webapp directories.
We will be using Maven in this tutorial, taking advantage of its transitive dependency management capabilities as well as the ability of many IDEs to automatically set up a project for us based on the maven descriptor.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.hibernate.tutorials</groupId> <artifactId>hibernate-tutorial</artifactId> <version>1.0.0-SNAPSHOT</version> <name>First Hibernate Tutorial</name> <build> <!-- we dont want the version to be part of the generated war file name --> <finalName>${artifactId}</finalName> </build> <dependencies> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> </dependency> <!-- Because this is a web app, we also have a dependency on the servlet api. --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> </dependency> <!-- Hibernate uses slf4j for logging, for our purposes here use the simple backend --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-simple</artifactId> </dependency> <!-- Hibernate gives you a choice of bytecode providers between cglib and javassist --> <dependency> <groupId>javassist</groupId> <artifactId>javassist</artifactId> </dependency> </dependencies></project> It is not a requirement to use Maven. If you wish to use something else to build this tutorial (such as Ant), the layout will remain the same. The only change is that you will need to manually account for all the needed dependencies. If you use something likeIvy providing transitive dependency management you would still use the dependencies mentioned below. Otherwise, you'd need to graball dependencies, both explicit and transitive, and add them to the project's classpath. If working from the Hibernate distribution bundle, this would meanhibernate3.jar, all artifacts in thelib/required directory and all files from either thelib/bytecode/cglib orlib/bytecode/javassist directory; additionally you will need both the servlet-api jar and one of the slf4j logging backends.
Save this file aspom.xml in the project root directory.
Next, we create a class that represents the event we want to store in the database; it is a simple JavaBean class with some properties:
package org.hibernate.tutorial.domain;import java.util.Date;public class Event { private Long id; private String title; private Date date; public Event() {} public Long getId() { return id; } private void setId(Long id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; }}This class uses standard JavaBean naming conventions for property getter and setter methods, as well as private visibility for the fields. Although this is the recommended design, it is not required. Hibernate can also access fields directly, the benefit of accessor methods is robustness for refactoring.
Theid property holds a unique identifier value for a particular event. All persistent entity classes (there are less important dependent classes as well) will need such an identifier property if we want to use the full feature set of Hibernate. In fact, most applications, especially web applications, need to distinguish objects by identifier, so you should consider this a feature rather than a limitation. However, we usually do not manipulate the identity of an object, hence the setter method should be private. Only Hibernate will assign identifiers when an object is saved. Hibernate can access public, private, and protected accessor methods, as well as public, private and protected fields directly. The choice is up to you and you can match it to fit your application design.
The no-argument constructor is a requirement for all persistent classes; Hibernate has to create objects for you, using Java Reflection. The constructor can be private, however package or public visibility is required for runtime proxy generation and efficient data retrieval without bytecode instrumentation.
Save this file to thesrc/main/java/org/hibernate/tutorial/domain directory.
Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.
The basic structure of a mapping file looks like this:
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping package="org.hibernate.tutorial.domain">[...]</hibernate-mapping>
Hibernate DTD is sophisticated. You can use it for auto-completion of XML mapping elements and attributes in your editor or IDE. Opening up the DTD file in your text editor is the easiest way to get an overview of all elements and attributes, and to view the defaults, as well as some comments. Hibernate will not load the DTD file from the web, but first look it up from the classpath of the application. The DTD file is included inhibernate-core.jar (it is also included in thehibernate3.jar, if using the distribution bundle).
We will omit the DTD declaration in future examples to shorten the code. It is, of course, not optional.
Between the twohibernate-mapping tags, include aclass element. All persistent entity classes (again, there might be dependent classes later on, which are not first-class entities) need a mapping to a table in the SQL database:
<hibernate-mapping package="org.hibernate.tutorial.domain"> <class name="Event" table="EVENTS"> </class></hibernate-mapping>
So far we have told Hibernate how to persist and load object of classEvent to the tableEVENTS. Each instance is now represented by a row in that table. Now we can continue by mapping the unique identifier property to the tables primary key. As we do not want to care about handling this identifier, we configure Hibernate's identifier generation strategy for a surrogate primary key column:
<hibernate-mapping package="org.hibernate.tutorial.domain"> <class name="Event" table="EVENTS"> <id name="id" column="EVENT_ID"> <generator/> </id> </class></hibernate-mapping>
Theid element is the declaration of the identifier property. Thename="id" mapping attribute declares the name of the JavaBean property and tells Hibernate to use thegetId() andsetId() methods to access the property. The column attribute tells Hibernate which column of theEVENTS table holds the primary key value.
The nestedgenerator element specifies the identifier generation strategy (aka how are identifier values generated?). In this case we choosenative, which offers a level of portability depending on the configured database dialect. Hibernate supports database generated, globally unique, as well as application assigned, identifiers. Identifier value generation is also one of Hibernate's many extension points and you can plugin in your own strategy.
native is no longer consider the best strategy in terms of portability. for further discussion, seeSection 27.4, “Identifier generation”
Lastly, we need to tell Hibernate about the remaining entity class properties. By default, no properties of the class are considered persistent:
<hibernate-mapping package="org.hibernate.tutorial.domain"> <class name="Event" table="EVENTS"> <id name="id" column="EVENT_ID"> <generator/> </id> <property name="date" type="timestamp" column="EVENT_DATE"/> <property name="title"/> </class></hibernate-mapping>
Similar to theid element, thename attribute of theproperty element tells Hibernate which getter and setter methods to use. In this case, Hibernate will search forgetDate(),setDate(),getTitle() andsetTitle() methods.
Why does thedate property mapping include thecolumn attribute, but thetitle does not? Without thecolumn attribute, Hibernate by default uses the property name as the column name. This works fortitle, however,date is a reserved keyword in most databases so you will need to map it to a different name.
Thetitle mapping also lacks atype attribute. The types declared and used in the mapping files are not Java data types; they are not SQL database types either. These types are calledHibernate mapping types, converters which can translate from Java to SQL data types and vice versa. Again, Hibernate will try to determine the correct conversion and mapping type itself if thetype attribute is not present in the mapping. In some cases this automatic detection using Reflection on the Java class might not have the default you expect or need. This is the case with thedate property. Hibernate cannot know if the property, which is ofjava.util.Date, should map to a SQLdate,timestamp, ortime column. Full date and time information is preserved by mapping the property with atimestamp converter.
Hibernate makes this mapping type determination using reflection when the mapping files are processed. This can take time and resources, so if startup performance is important you should consider explicitly defining the type to use.
Save this mapping file assrc/main/resources/org/hibernate/tutorial/domain/Event.hbm.xml.
At this point, you should have the persistent class and its mapping file in place. It is now time to configure Hibernate. First let's set up HSQLDB to run in "server mode"
We do this so that the data remains between runs.
We will utilize the Maven exec plugin to launch the HSQLDB server by running: mvn exec:java -Dexec.mainClass="org.hsqldb.Server" -Dexec.args="-database.0 file:target/data/tutorial" You will see it start up and bind to a TCP/IP socket; this is where our application will connect later. If you want to start with a fresh database during this tutorial, shutdown HSQLDB, delete all files in thetarget/data directory, and start HSQLDB again.
Hibernate will be connecting to the database on behalf of your application, so it needs to know how to obtain connections. For this tutorial we will be using a standalone connection pool (as opposed to ajavax.sql.DataSource). Hibernate comes with support for two third-party open source JDBC connection pools:c3p0 andproxool. However, we will be using the Hibernate built-in connection pool for this tutorial.
The built-in Hibernate connection pool is in no way intended for production use. It lacks several features found on any decent connection pool.
For Hibernate's configuration, we can use a simplehibernate.properties file, a more sophisticatedhibernate.cfg.xml file, or even complete programmatic setup. Most users prefer the XML configuration file:
<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="connection.url">jdbc:hsqldb:hsql://localhost</property> <property name="connection.username">sa</property> <property name="connection.password"></property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.HSQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">update</property> <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/> </session-factory></hibernate-configuration>
Notice that this configuration file specifies a different DTD
You configure Hibernate'sSessionFactory. SessionFactory is a global factory responsible for a particular database. If you have several databases, for easier startup you should use several<session-factory> configurations in several configuration files.
The first fourproperty elements contain the necessary configuration for the JDBC connection. The dialectproperty element specifies the particular SQL variant Hibernate generates.
In most cases, Hibernate is able to properly determine which dialect to use. SeeSection 27.3, “Dialect resolution” for more information.
Hibernate's automatic session management for persistence contexts is particularly useful in this context. Thehbm2ddl.auto option turns on automatic generation of database schemas directly into the database. This can also be turned off by removing the configuration option, or redirected to a file with the help of theSchemaExport Ant task. Finally, add the mapping file(s) for persistent classes to the configuration.
Save this file ashibernate.cfg.xml into thesrc/main/resources directory.
We will now build the tutorial with Maven. You will need to have Maven installed; it is available from theMaven download page. Maven will read the/pom.xml file we created earlier and know how to perform some basic project tasks. First, lets run thecompile goal to make sure we can compile everything so far:
[hibernateTutorial]$ mvn compile[INFO] Scanning for projects...[INFO] ------------------------------------------------------------------------[INFO] Building First Hibernate Tutorial[INFO] task-segment: [compile][INFO] ------------------------------------------------------------------------[INFO] [resources:resources][INFO] Using default encoding to copy filtered resources.[INFO] [compiler:compile][INFO] Compiling 1 source file to /home/steve/projects/sandbox/hibernateTutorial/target/classes[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESSFUL[INFO] ------------------------------------------------------------------------[INFO] Total time: 2 seconds[INFO] Finished at: Tue Jun 09 12:25:25 CDT 2009[INFO] Final Memory: 5M/547M[INFO] ------------------------------------------------------------------------
It is time to load and store someEvent objects, but first you have to complete the setup with some infrastructure code. You have to startup Hibernate by building a globalorg.hibernate.SessionFactory object and storing it somewhere for easy access in application code. Aorg.hibernate.SessionFactory is used to obtainorg.hibernate.Session instances. Aorg.hibernate.Session represents a single-threaded unit of work. Theorg.hibernate.SessionFactory is a thread-safe global object that is instantiated once.
We will create aHibernateUtil helper class that takes care of startup and makes accessing theorg.hibernate.SessionFactory more convenient.
package org.hibernate.tutorial.util;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; }} Save this code assrc/main/java/org/hibernate/tutorial/util/HibernateUtil.java
This class not only produces the globalorg.hibernate.SessionFactory reference in its static initializer; it also hides the fact that it uses a static singleton. We might just as well have looked up theorg.hibernate.SessionFactory reference from JNDI in an application server or any other location for that matter.
If you give theorg.hibernate.SessionFactory a name in your configuration, Hibernate will try to bind it to JNDI under that name after it has been built. Another, better option is to use a JMX deployment and let the JMX-capable container instantiate and bind aHibernateService to JNDI. Such advanced options are discussed later.
You now need to configure a logging system. Hibernate uses commons logging and provides two choices: Log4j and JDK 1.4 logging. Most developers prefer Log4j: copylog4j.properties from the Hibernate distribution in theetc/ directory to yoursrc directory, next tohibernate.cfg.xml. If you prefer to have more verbose output than that provided in the example configuration, you can change the settings. By default, only the Hibernate startup message is shown on stdout.
The tutorial infrastructure is complete and you are now ready to do some real work with Hibernate.
We are now ready to start doing some real work with Hibernate. Let's start by writing anEventManager class with amain() method:
package org.hibernate.tutorial;import org.hibernate.Session;import java.util.*;import org.hibernate.tutorial.domain.Event;import org.hibernate.tutorial.util.HibernateUtil;public class EventManager { public static void main(String[] args) { EventManager mgr = new EventManager(); if (args[0].equals("store")) { mgr.createAndStoreEvent("My Event", new Date()); } HibernateUtil.getSessionFactory().close(); } private void createAndStoreEvent(String title, Date theDate) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Event theEvent = new Event(); theEvent.setTitle(title); theEvent.setDate(theDate); session.save(theEvent); session.getTransaction().commit(); }} IncreateAndStoreEvent() we created a newEvent object and handed it over to Hibernate. At that point, Hibernate takes care of the SQL and executes anINSERT on the database.
Aorg.hibernate.Session is designed to represent a single unit of work (a single atomic piece of work to be performed). For now we will keep things simple and assume a one-to-one granularity between a Hibernateorg.hibernate.Session and a database transaction. To shield our code from the actual underlying transaction system we use the Hibernateorg.hibernate.Transaction API. In this particular case we are using JDBC-based transactional semantics, but it could also run with JTA.
What doessessionFactory.getCurrentSession() do? First, you can call it as many times and anywhere you like once you get hold of yourorg.hibernate.SessionFactory. ThegetCurrentSession() method always returns the "current" unit of work. Remember that we switched the configuration option for this mechanism to "thread" in oursrc/main/resources/hibernate.cfg.xml? Due to that setting, the context of a current unit of work is bound to the current Java thread that executes the application.
Hibernate offers three methods of current session tracking. The "thread" based method is not intended for production use; it is merely useful for prototyping and tutorials such as this one. Current session tracking is discussed in more detail later on.
Aorg.hibernate.Session begins when the first call togetCurrentSession() is made for the current thread. It is then bound by Hibernate to the current thread. When the transaction ends, either through commit or rollback, Hibernate automatically unbinds theorg.hibernate.Session from the thread and closes it for you. If you callgetCurrentSession() again, you get a neworg.hibernate.Session and can start a new unit of work.
Related to the unit of work scope, should the Hibernateorg.hibernate.Session be used to execute one or several database operations? The above example uses oneorg.hibernate.Session for one operation. However this is pure coincidence; the example is just not complex enough to show any other approach. The scope of a Hibernateorg.hibernate.Session is flexible but you should never design your application to use a new Hibernateorg.hibernate.Session forevery database operation. Even though it is used in the following examples, considersession-per-operation an anti-pattern. A real web application is shown later in the tutorial which will help illustrate this.
SeeChapter 13,Transactions and Concurrency for more information about transaction handling and demarcation. The previous example also skipped any error handling and rollback.
To run this, we will make use of the Maven exec plugin to call our class with the necessary classpath setup:mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" -Dexec.args="store"
You may need to performmvn compile first.
You should see Hibernate starting up and, depending on your configuration, lots of log output. Towards the end, the following line will be displayed:
[java] Hibernate: insert into EVENTS (EVENT_DATE, title, EVENT_ID) values (?, ?, ?)
This is theINSERT executed by Hibernate.
To list stored events an option is added to the main method:
if (args[0].equals("store")) { mgr.createAndStoreEvent("My Event", new Date()); } else if (args[0].equals("list")) { List events = mgr.listEvents(); for (int i = 0; i < events.size(); i++) { Event theEvent = (Event) events.get(i); System.out.println( "Event: " + theEvent.getTitle() + " Time: " + theEvent.getDate() ); } } A newlistEvents() method is also added:
private List listEvents() { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); List result = session.createQuery("from Event").list(); session.getTransaction().commit(); return result; } Here, we are using a Hibernate Query Language (HQL) query to load all existingEvent objects from the database. Hibernate will generate the appropriate SQL, send it to the database and populateEvent objects with the data. You can create more complex queries with HQL. SeeChapter 16,HQL: The Hibernate Query Language for more information.
Now we can call our new functionality, again using the Maven exec plugin:mvn exec:java -Dexec.mainClass="org.hibernate.tutorial.EventManager" -Dexec.args="list"
So far we have mapped a single persistent entity class to a table in isolation. Let's expand on that a bit and add some class associations. We will add people to the application and store a list of events in which they participate.
The first cut of thePerson class looks like this:
package org.hibernate.tutorial.domain;public class Person { private Long id; private int age; private String firstname; private String lastname; public Person() {} // Accessor methods for all properties, private setter for 'id'} Save this to a file namedsrc/main/java/org/hibernate/tutorial/domain/Person.java
Next, create the new mapping file assrc/main/resources/org/hibernate/tutorial/domain/Person.hbm.xml
<hibernate-mapping package="org.hibernate.tutorial.domain"> <class name="Person" table="PERSON"> <id name="id" column="PERSON_ID"> <generator/> </id> <property name="age"/> <property name="firstname"/> <property name="lastname"/> </class></hibernate-mapping>
Finally, add the new mapping to Hibernate's configuration:
<mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/><mapping resource="org/hibernate/tutorial/domain/Person.hbm.xml"/>
Create an association between these two entities. Persons can participate in events, and events have participants. The design questions you have to deal with are: directionality, multiplicity, and collection behavior.
By adding a collection of events to thePerson class, you can easily navigate to the events for a particular person, without executing an explicit query - by callingPerson#getEvents. Multi-valued associations are represented in Hibernate by one of the Java Collection Framework contracts; here we choose ajava.util.Set because the collection will not contain duplicate elements and the ordering is not relevant to our examples:
public class Person { private Set events = new HashSet(); public Set getEvents() { return events; } public void setEvents(Set events) { this.events = events; }} Before mapping this association, let's consider the other side. We could just keep this unidirectional or create another collection on theEvent, if we wanted to be able to navigate it from both directions. This is not necessary, from a functional perspective. You can always execute an explicit query to retrieve the participants for a particular event. This is a design choice left to you, but what is clear from this discussion is the multiplicity of the association: "many" valued on both sides is called amany-to-many association. Hence, we use Hibernate's many-to-many mapping:
<class name="Person" table="PERSON"> <id name="id" column="PERSON_ID"> <generator/> </id> <property name="age"/> <property name="firstname"/> <property name="lastname"/> <set name="events" table="PERSON_EVENT"> <key column="PERSON_ID"/> <many-to-many column="EVENT_ID"/> </set></class>
Hibernate supports a broad range of collection mappings, aset being most common. For a many-to-many association, orn:m entity relationship, an association table is required. Each row in this table represents a link between a person and an event. The table name is decalred using thetable attribute of theset element. The identifier column name in the association, for the person side, is defined with thekey element, the column name for the event's side with thecolumn attribute of themany-to-many. You also have to tell Hibernate the class of the objects in your collection (the class on the other side of the collection of references).
The database schema for this mapping is therefore:
_____________ __________________ | | | | _____________ | EVENTS | | PERSON_EVENT | | | |_____________| |__________________| | PERSON | | | | | |_____________| | *EVENT_ID | <--> | *EVENT_ID | | | | EVENT_DATE | | *PERSON_ID | <--> | *PERSON_ID | | TITLE | |__________________| | AGE | |_____________| | FIRSTNAME | | LASTNAME | |_____________|
Now we will bring some people and events together in a new method inEventManager:
private void addPersonToEvent(Long personId, Long eventId) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Person aPerson = (Person) session.load(Person.class, personId); Event anEvent = (Event) session.load(Event.class, eventId); aPerson.getEvents().add(anEvent); session.getTransaction().commit(); } After loading aPerson and anEvent, simply modify the collection using the normal collection methods. There is no explicit call toupdate() orsave(); Hibernate automatically detects that the collection has been modified and needs to be updated. This is calledautomatic dirty checking. You can also try it by modifying the name or the date property of any of your objects. As long as they are inpersistent state, that is, bound to a particular Hibernateorg.hibernate.Session, Hibernate monitors any changes and executes SQL in a write-behind fashion. The process of synchronizing the memory state with the database, usually only at the end of a unit of work, is calledflushing. In our code, the unit of work ends with a commit, or rollback, of the database transaction.
You can load person and event in different units of work. Or you can modify an object outside of aorg.hibernate.Session, when it is not in persistent state (if it was persistent before, this state is calleddetached). You can even modify a collection when it is detached:
private void addPersonToEvent(Long personId, Long eventId) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Person aPerson = (Person) session .createQuery("select p from Person p left join fetch p.events where p.id = :pid") .setParameter("pid", personId) .uniqueResult(); // Eager fetch the collection so we can use it detached Event anEvent = (Event) session.load(Event.class, eventId); session.getTransaction().commit(); // End of first unit of work aPerson.getEvents().add(anEvent); // aPerson (and its collection) is detached // Begin second unit of work Session session2 = HibernateUtil.getSessionFactory().getCurrentSession(); session2.beginTransaction(); session2.update(aPerson); // Reattachment of aPerson session2.getTransaction().commit(); } The call toupdate makes a detached object persistent again by binding it to a new unit of work, so any modifications you made to it while detached can be saved to the database. This includes any modifications (additions/deletions) you made to a collection of that entity object.
This is not much use in our example, but it is an important concept you can incorporate into your own application. Complete this exercise by adding a new action to the main method of theEventManager and call it from the command line. If you need the identifiers of a person and an event - thesave() method returns it (you might have to modify some of the previous methods to return that identifier):
else if (args[0].equals("addpersontoevent")) { Long eventId = mgr.createAndStoreEvent("My Event", new Date()); Long personId = mgr.createAndStorePerson("Foo", "Bar"); mgr.addPersonToEvent(personId, eventId); System.out.println("Added person " + personId + " to event " + eventId); } This is an example of an association between two equally important classes : two entities. As mentioned earlier, there are other classes and types in a typical model, usually "less important". Some you have already seen, like anint or ajava.lang.String. We call these classesvalue types, and their instancesdepend on a particular entity. Instances of these types do not have their own identity, nor are they shared between entities. Two persons do not reference the samefirstname object, even if they have the same first name. Value types cannot only be found in the JDK , but you can also write dependent classes yourself such as anAddress orMonetaryAmount class. In fact, in a Hibernate application all JDK classes are considered value types.
You can also design a collection of value types. This is conceptually different from a collection of references to other entities, but looks almost the same in Java.
Let's add a collection of email addresses to thePerson entity. This will be represented as ajava.util.Set ofjava.lang.String instances:
private Set emailAddresses = new HashSet(); public Set getEmailAddresses() { return emailAddresses; } public void setEmailAddresses(Set emailAddresses) { this.emailAddresses = emailAddresses; } The mapping of thisSet is as follows:
<set name="emailAddresses" table="PERSON_EMAIL_ADDR"> <key column="PERSON_ID"/> <element type="string" column="EMAIL_ADDR"/> </set>
The difference compared with the earlier mapping is the use of theelement part which tells Hibernate that the collection does not contain references to another entity, but is rather a collection whose elements are values types, here specifically of typestring. The lowercase name tells you it is a Hibernate mapping type/converter. Again thetable attribute of theset element determines the table name for the collection. Thekey element defines the foreign-key column name in the collection table. Thecolumn attribute in theelement element defines the column name where the email address values will actually be stored.
Here is the updated schema:
_____________ __________________ | | | | _____________ | EVENTS | | PERSON_EVENT | | | ___________________ |_____________| |__________________| | PERSON | | | | | | | |_____________| | PERSON_EMAIL_ADDR | | *EVENT_ID | <--> | *EVENT_ID | | | |___________________| | EVENT_DATE | | *PERSON_ID | <--> | *PERSON_ID | <--> | *PERSON_ID | | TITLE | |__________________| | AGE | | *EMAIL_ADDR | |_____________| | FIRSTNAME | |___________________| | LASTNAME | |_____________|
You can see that the primary key of the collection table is in fact a composite key that uses both columns. This also implies that there cannot be duplicate email addresses per person, which is exactly the semantics we need for a set in Java.
You can now try to add elements to this collection, just like we did before by linking persons and events. It is the same code in Java:
private void addEmailToPerson(Long personId, String emailAddress) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Person aPerson = (Person) session.load(Person.class, personId); // adding to the emailAddress collection might trigger a lazy load of the collection aPerson.getEmailAddresses().add(emailAddress); session.getTransaction().commit(); }This time we did not use afetch query to initialize the collection. Monitor the SQL log and try to optimize this with an eager fetch.
Next you will map a bi-directional association. You will make the association between person and event work from both sides in Java. The database schema does not change, so you will still have many-to-many multiplicity.
A relational database is more flexible than a network programming language, in that it does not need a navigation direction; data can be viewed and retrieved in any possible way.
First, add a collection of participants to theEvent class:
private Set participants = new HashSet(); public Set getParticipants() { return participants; } public void setParticipants(Set participants) { this.participants = participants; } Now map this side of the association inEvent.hbm.xml.
<set name="participants" table="PERSON_EVENT" inverse="true"> <key column="EVENT_ID"/> <many-to-many column="PERSON_ID"/> </set>
These are normalset mappings in both mapping documents. Notice that the column names inkey andmany-to-many swap in both mapping documents. The most important addition here is theinverse="true" attribute in theset element of theEvent's collection mapping.
What this means is that Hibernate should take the other side, thePerson class, when it needs to find out information about the link between the two. This will be a lot easier to understand once you see how the bi-directional link between our two entities is created.
First, keep in mind that Hibernate does not affect normal Java semantics. How did we create a link between aPerson and anEvent in the unidirectional example? You add an instance ofEvent to the collection of event references, of an instance ofPerson. If you want to make this link bi-directional, you have to do the same on the other side by adding aPerson reference to the collection in anEvent. This process of "setting the link on both sides" is absolutely necessary with bi-directional links.
Many developers program defensively and create link management methods to correctly set both sides (for example, inPerson):
protected Set getEvents() { return events; } protected void setEvents(Set events) { this.events = events; } public void addToEvent(Event event) { this.getEvents().add(event); event.getParticipants().add(this); } public void removeFromEvent(Event event) { this.getEvents().remove(event); event.getParticipants().remove(this); }The get and set methods for the collection are now protected. This allows classes in the same package and subclasses to still access the methods, but prevents everybody else from altering the collections directly. Repeat the steps for the collection on the other side.
What about theinverse mapping attribute? For you, and for Java, a bi-directional link is simply a matter of setting the references on both sides correctly. Hibernate, however, does not have enough information to correctly arrange SQLINSERT andUPDATE statements (to avoid constraint violations). Making one side of the associationinverse tells Hibernate to consider it amirror of the other side. That is all that is necessary for Hibernate to resolve any issues that arise when transforming a directional navigation model to a SQL database schema. The rules are straightforward: all bi-directional associations need one side asinverse. In a one-to-many association it has to be the many-side, and in many-to-many association you can select either side.
A Hibernate web application usesSession andTransaction almost like a standalone application. However, some common patterns are useful. You can now write anEventManagerServlet. This servlet can list all events stored in the database, and it provides an HTML form to enter new events.
First we need create our basic processing servlet. Since our servlet only handles HTTPGET requests, we will only implement thedoGet() method:
package org.hibernate.tutorial.web;// Importspublic class EventManagerServlet extends HttpServlet { protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SimpleDateFormat dateFormatter = new SimpleDateFormat( "dd.MM.yyyy" ); try { // Begin unit of work HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction(); // Process request and render page... // End unit of work HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit(); } catch (Exception ex) { HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback(); if ( ServletException.class.isInstance( ex ) ) { throw ( ServletException ) ex; } else { throw new ServletException( ex ); } } }} Save this servlet assrc/main/java/org/hibernate/tutorial/web/EventManagerServlet.java
The pattern applied here is calledsession-per-request. When a request hits the servlet, a new HibernateSession is opened through the first call togetCurrentSession() on theSessionFactory. A database transaction is then started. All data access occurs inside a transaction irrespective of whether the data is read or written. Do not use the auto-commit mode in applications.
Donot use a new HibernateSession for every database operation. Use one HibernateSession that is scoped to the whole request. UsegetCurrentSession(), so that it is automatically bound to the current Java thread.
Next, the possible actions of the request are processed and the response HTML is rendered. We will get to that part soon.
Finally, the unit of work ends when processing and rendering are complete. If any problems occurred during processing or rendering, an exception will be thrown and the database transaction rolled back. This completes thesession-per-request pattern. Instead of the transaction demarcation code in every servlet, you could also write a servlet filter. See the Hibernate website and Wiki for more information about this pattern calledOpen Session in View. You will need it as soon as you consider rendering your view in JSP, not in a servlet.
Now you can implement the processing of the request and the rendering of the page.
// Write HTML header PrintWriter out = response.getWriter(); out.println("<html><head><title>Event Manager</title></head><body>"); // Handle actions if ( "store".equals(request.getParameter("action")) ) { String eventTitle = request.getParameter("eventTitle"); String eventDate = request.getParameter("eventDate"); if ( "".equals(eventTitle) || "".equals(eventDate) ) { out.println("<b><i>Please enter event title and date.</i></b>"); } else { createAndStoreEvent(eventTitle, dateFormatter.parse(eventDate)); out.println("<b><i>Added event.</i></b>"); } } // Print page printEventForm(out); listEvents(out, dateFormatter); // Write HTML footer out.println("</body></html>"); out.flush(); out.close();This coding style, with a mix of Java and HTML, would not scale in a more complex application;keep in mind that we are only illustrating basic Hibernate concepts in this tutorial. The code prints an HTML header and a footer. Inside this page, an HTML form for event entry and a list of all events in the database are printed. The first method is trivial and only outputs HTML:
private void printEventForm(PrintWriter out) { out.println("<h2>Add new event:</h2>"); out.println("<form>"); out.println("Title: <input name='eventTitle' length='50'/><br/>"); out.println("Date (e.g. 24.12.2009): <input name='eventDate' length='10'/><br/>"); out.println("<input type='submit' name='action' value='store'/>"); out.println("</form>"); } ThelistEvents() method uses the HibernateSession bound to the current thread to execute a query:
private void listEvents(PrintWriter out, SimpleDateFormat dateFormatter) { List result = HibernateUtil.getSessionFactory() .getCurrentSession().createCriteria(Event.class).list(); if (result.size() > 0) { out.println("<h2>Events in database:</h2>"); out.println("<table border='1'>"); out.println("<tr>"); out.println("<th>Event title</th>"); out.println("<th>Event date</th>"); out.println("</tr>"); Iterator it = result.iterator(); while (it.hasNext()) { Event event = (Event) it.next(); out.println("<tr>"); out.println("<td>" + event.getTitle() + "</td>"); out.println("<td>" + dateFormatter.format(event.getDate()) + "</td>"); out.println("</tr>"); } out.println("</table>"); } } Finally, thestore action is dispatched to thecreateAndStoreEvent() method, which also uses theSession of the current thread:
protected void createAndStoreEvent(String title, Date theDate) { Event theEvent = new Event(); theEvent.setTitle(title); theEvent.setDate(theDate); HibernateUtil.getSessionFactory() .getCurrentSession().save(theEvent); } The servlet is now complete. A request to the servlet will be processed in a singleSession andTransaction. As earlier in the standalone application, Hibernate can automatically bind these objects to the current thread of execution. This gives you the freedom to layer your code and access theSessionFactory in any way you like. Usually you would use a more sophisticated design and move the data access code into data access objects (the DAO pattern). See the Hibernate Wiki for more examples.
To deploy this application for testing we must create a Web ARchive (WAR). First we must define the WAR descriptor assrc/main/webapp/WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <servlet> <servlet-name>Event Manager</servlet-name> <servlet-class>org.hibernate.tutorial.web.EventManagerServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Event Manager</servlet-name> <url-pattern>/eventmanager</url-pattern> </servlet-mapping></web-app>
To build and deploy callmvn package in your project directory and copy thehibernate-tutorial.war file into your Tomcatwebapps directory.
If you do not have Tomcat installed, download it fromhttp://tomcat.apache.org/ and follow the installation instructions. Our application requires no changes to the standard Tomcat configuration.
Once deployed and Tomcat is running, access the application athttp://localhost:8080/hibernate-tutorial/eventmanager. Make sure you watch the Tomcat log to see Hibernate initialize when the first request hits your servlet (the static initializer inHibernateUtil is called) and to get the detailed output if any exceptions occurs.
This tutorial covered the basics of writing a simple standalone Hibernate application and a small web application. More tutorials are available from the Hibernatewebsite.