An Introduction to Hibernate

Need Hosting? Try ours, it's fast, reliable and feature loaded with support you can depend on. View Plans

This section gives you a short description of Hibernate and provides you with some important notes to this course.This course has instructions for working with the Windows Platform.

The instructions may need to be modified slightly for the Unix platform. Paths are shown as windows paths. There are lots of examples in this course. You can run the example by executing ANT files.

Objectives

The main objective of this course is to get you up to speed with the fundamentals of the Hibernate as fast as possible.There are couple of examples in this course which can be run from ANT files.One of the principles of this course is learning by example.

This course aims to be quite self-sufficient. The reason is that there are still many places in this world that do not yet have a good internet access. The Course requires prior knowledge of Spring framework.

What is Hibernate

Hibernate is an object/relational persistence solution which allows you to develop persistent classes following object-oriented idiom.Hibernate persistence has no requirement for a J2EE application server, while EJBs do, or any other special environments. Therefore it is a more suitable solution for stand-alone applications or other environments in which a J2EE server is not available.

To understand the object/relational persistence, we will introduce the concept of POJO first.

Plain Old Java Object (POJO)

The term POJO was coined by Martin Fowler, Rebecca Parsons and Josh Mackenzie in 2002. A POJO is a Java object that does not implement any special interfaces such as those defined by the EJB specification.Despite the simplicity of the idea, POJOs have some tremendous benefits because they decouple the applications from the volatile infrastructure frameworks and they simplify the development process. An example of POJO is as follows.

public class Message { private Long messageId; private String messageText; // List of getters and setters .. }

Note: Hibernate does not require that one POJO should be mapped to one table. A POJO can be constructed out of a selection of table columns, and several POJOs can be persisted into a single table.

Installing Hibernate

To use Hibernate Annotations, you will need at least Hibernate 3.2, and of course Java 5. You can download latest stable version of Hibernate and the Hibernate Annotations library from the Hibernate web site. Hibernate also depends on following jars: Commons-collection.jar and javassist.jar (library for reading byte codes) and ANTLR.jar (Another Tool for Language Recognition) If you are using maven this jar will be downloaded for you. In addition to the standard Hibernate JARs and dependencies, you will also need the Hibernate Annotations .jar file (hibernate-annotations.jar) and Java Persistence API (lib/ejb3-persistence.jar).

Setting up Your Environment

This chapter explains the steps required to set up your development environment so that you can learn this Hibernate module. Create a directory for all your projects Create the following directory: C:\YOUR_NAME\DATA\java_projects where YOUR_NAME is your name. Under this directory you will be putting all your projects as you go through this training programme. Create a directory for your library resource Create the following directory: C:\YOUR_NAME\DATA\java_projects\lib Obtain the java library resource and install it.

Object/Relational Mapping (ORM)

Object/relational mapping is the automated process of persisting the objects (POJOs) in the Java application to the tables in the relational database. This is done by using metadata that describe the mappings between the objects and the database tables. The following code snippet demonstrates the mapping of a 'Message' object to a 'MESSAGE' table in the database. You can easily tell that the 'messageId' field is mapped to a 'Id' column in the table.

@Entity @Table(name = Message.TABLE_NAME) public class Message { public static final String TABLE_NAME = "MESSAGE"; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long messageId; @Column(name="MESSAGE_TEXT", nullable=false, unique=true) private String messageText; /** * * @return the messageId */ public long getMessageId() { return messageId; } /** * * @param messageId the messageId to set */ public void setMessageId(long messageId) { this.messageId = messageId; } /** * * @return the messageText */ public String getMessageText() { return messageText; } /** * * @param name the messageText to set */ public void setMessageText(String messageText) { this.messageText = messageText; } }

There are a couple of concepts that you need to keep in mind to better understand ORM.

Object Identity:

An object identity is something that can uniquely define a persisted object. It is commonly mapped to the primary key field of a database table. The 'Id' in the above mapping is an example of the object identity.

In Memory versus Persisted Objects:

When you are working with ORM technologies, there is a distinction between objects in memory and persisted ones. If one object does not exist in the database, or its properties do not match the corresponding column values in the database, it is considered an in-memory object. Hibernate distinguishes object states as persistent, detached or transient, which we will discuss in details at a later section.

Integrating And Configuring Hibernate

The essential steps to integrate and configure hibernate are as follows. Add the Hibernate libraries to the shared lib directory. Identify the POJOs that have the database representation. And identify which properties of the POJOs need to be persisted. Add annotations data for the POJOs.(The Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping. All the metadata is clubbed into the POJO java file along with the code this helps the user to understand the table structure and POJO simultaneously during the development. This also reduces the management of different files for the metadata and java code.) Create the database schema or use the existing database schema. Create the Hibernate XML configuration file. Create the Hibernate Configuration object in the application, build the SessionFactory object, retrieve the Session objects and finally persist data.

Building a Sample Application

We will go through creating a simple spring\hibernate 'Message Board' application which display a comments entered by bloggers. The application creates a message object first, stores the message in the database, then retrieves all the message(s) entered and displays the message(s). In this part, you will learn how to apply these annotations to develop real-world applications with the combination of Hibernate annotation and Spring MVC To achieve our objective, we'll go through the steps listed below: Step 1: The Persistent Layer. Step 2: The UI Layer Step 3: Build and Deploy the Application

Step 1: - The Persistent Layer.

We will need to create the entity (Persistent POJO). Typically, we'll be working with the persistence layer first. To do this, we will create a persistent object mapping to our database table. This object also can be referred to as an Entity bean, a Persistent POJO, a Value Object (VO), and so forth. The properties of the POJO will represent the fields in the table with some metadata information attached. Hibernate annotations will be used as the metadata model. Without annotations, mapping metadata is declared in XML mapping files. With Hibernate annotations, no additional mapping files are required. With the metadata information attached, the annotations are processed by the Compiler before the class is loaded. Basically, there are two ways you can define an entity POJO: * At the getter-methods level * At the object's properties level In this example we'll create an entity bean named 'Message'. Entity bean with annotations declared at the object's properties level Message class:

package com.jack.springmvc.orm.entities; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** @author Jack Mwendwa * */ @Entity @Table(name = Message.TABLE_NAME) public class Message { public static final String TABLE_NAME="Message"; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long messageId; @Column(name="postedBy",nullable=false, unique=true) private String postedBy; @Column(name="comment",nullable=true) private String comment; /** * @return the messageId */ public long getMessageId() { return messageId; } /** * @param messageId the messageId to set */ public void setMessageId(long messageId) { this.messageId = messageId; } /** * @return the postedBy */ public String getPostedBy() { return postedBy; } /** * @param postedBy the postedBy to set */ public void setPostedBy(String postedBy) { this.postedBy = postedBy; } /** * @return the comment */ public String getComment() { return comment; } /** * @param description the description to set */ public void setComment(String comment) { this.comment = comment; } }

As you can see in the 'Message' POJO, every bound persistent POJO class is an entity bean and is declared by using the @Entity annotation. @Entity declares the class as an entity bean (in other words, a persistent POJO class). @Table declares the database table to which the class corresponds. This is optional. If you do not include this attribute, the default class name is used as the table name. @Id declares the identifier property of this entity bean. The other mapping declarations are implicit. The @Entity annotation also allows you to define whether an entity bean should be accessed through its getters/setters methods or whether the entity manager should access the fields of the object directly.

Rules for Defining an Entity

In short, here are the few actions you must not forget when defining an entity POJO: * Import the javax.persistence.* packages to enable the JSDK5 annotation feature. * At the class level, declare the @Entity and @Table to map an entity object with a table name. * Define the access type for the POJO properties. access =AccessType.PROPERTY means that method level annotations are used, which will only be applied with the getter methods. If access = AccessType.FIELD were used, then the annotations would be associated with the fields. If AccessType is not mentioned, PROPERTY is used as the default type (in other words, for getter methods). * For a primary key field, use the annotation @Id. There are five types of GeneratorType variables: AUTO, TABLE, IDENTITY, SEQUENCE, and NONE. Because this is a numeric type variable, you can also use SEQUENCE in this case, although the AUTO generator is the recommended type for portable applications. * For the other properties in the POJO (in other words, not the primary field), the @Column annotation is used. Here is the syntax:

@Column(name="postedBy",nullable=false, unique=true) private String postedBy;

* name: (optional). This property refers to the corresponding table field name. If not mentioned, the default getter property is used. * nullable: (optional). Whether null values are allowed or not for this field. Default is true. * length: This determines the length of the field. Although optional, it is recommended to mention the field size. * unique: (optional). This determines whether the property is unique or not. Default is false.

Hibernate configuration

The next step after defining the entity is to create a Hibernate bean in the applicationContext configuration file. Start by creating a file named applicationContext.xml and place it under the WEB-INF/ directory. The fully qualified class name of the POJO should be included within the <value> tag. If more POJOs are created, they will simply be included with additional <value> tags under the <list> tag. Here is the syntax:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref local="dataSource"/> </property> <property name="hibernateProperties"> <ref local="hibernateProperties"/> </property> <property name="annotatedClasses"> <list> <value>com.jack.springmvc.orm.entities.Message</value> </list> </property> </bean>

JDBC configuration

Next, create a property file named mysql.jdbc.properties and place it under the WEB-INF/ Here is the syntax:

jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost/messageboard jdbc.username=root jdbc.password=pass1 hibernate.hbm2ddl.auto=update #hibernate.hbm2ddl.auto=create hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect hibernate.query.substitutions=true 'T', false 'F' hibernate.show_sql=true hibernate.c3p0.minPoolSize=5 hibernate.c3p0.maxPoolSize=25 hibernate.c3p0.timeout=900 hibernate.c3p0.max_statement=50 hibernate.c3p0.testConnectionOnCheckout

If you have a different database schema other than this, just change the values for the properties "jdbc.driverClassName", "jdbc.url", "jdbc.username","jdbc.password" and "hibernate.dialect" according to your DB environment.

#hibernate.hbm2ddl.auto=create

The line of code above is commented out because we don't want to recreate the database table every time the application is deployed. Setting the value of "hibernate.hbm2ddl.auto" to "update" means that whenever there are modification made on the pojos/annotated classes, these modifications are reflected to the database tables represented by these objects during the application's deployment. Next, create a JDBC configuration beans in the applicationContext configuration file. Here is the syntax:

<beans> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="/WEB-INF/mysql.jdbc.properties"/> </bean> <!-- START data sources ============================================= --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- END data sources ============================================== --> <!-- START Hibernate =============================================== --> <bean id="hibernateProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="properties"> <props> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.query.substitutions">${hibernate.query.substitutions} </prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.c3p0.minPoolSize">${hibernate.c3p0.minPoolSize} </prop> <prop key="hibernate.c3p0.maxPoolSize">${hibernate.c3p0.maxPoolSize} </prop> <prop key="hibernate.c3p0.timeout">${hibernate.c3p0.timeout}</prop> <prop key="hibernate.c3p0.max_statement">${hibernate.c3p0.max_statement} </prop> <prop key="hibernate.c3p0.testConnectionOnCheckout"> ${hibernate.c3p0.testConnectionOnCheckout}</prop> </props> </property> </bean>

Wiring POJO with DAO

At this point in the POJO creation, we'll need to wire it properly with our data access objects (DAOs). To do this, we'll need to create our required DAO interface and implementation objects, and define them in our applicationContext.xml file (wiring) to work with the persistent POJO. The following code snipped demonstrates how to create the DAO objects. Create a MessageDao interface and a MessageDaoHibernate implementation class within the com.jack.springmvc.dao package as follows: The DAO interface

package com.jack.springmvc.dao; import java.util.List; import com.jack.springmvc.orm.entities.Message; public interface MessageDAO { /** * @param id @return Message */ public Message getMessageById(long id)throws Exception ; /** * @param postedBy @return Message */ public Message getMessageByPostedBy(String postedBy)throws Exception ; /** * @param Message */ public void saveMessage(Message Message); /** * * @param Message */ public void updateMessage(Message Message); /** * @return a List of Messages */ public List<Message> getAllMessages(); }

The DAO implementation

package com.jack.springmvc.dao; import org.apache.log4j.Logger; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import java.util.List; import com.jack.springmvc.orm.entities.Message; /** @ * */ public class MessageDAOHibernate extends HibernateDaoSupport implements MessageDAO{ protected Logger logger = Logger.getLogger( MessageDAOHibernate.class ); /** * */ public MessageDAOHibernate() { } /* (non-Javadoc) * */ @Override public List<Message> getAllMessages() { return this.getHibernateTemplate().loadAll(Message.class); } /* (non-Javadoc) * */ @Override public Message getMessageById(long id)throws Exception { if (id == 0) { throw new Exception("Id parameter cannot be null!"); } String queryString = "from Message m where m.messageId = ?"; System.out.print(queryString + id); List<Message> message = getHibernateTemplate().find( queryString, id ); if ( message.size() == 0 ) { return null; } if ( message.size() > 1 ) { throw new Exception("Found more than one messages with the same Id." ); } return message.get(0); } /* (non-Javadoc) * */ @Override public Message getMessageByPostedBy(String postedBy) throws Exception { if (postedBy == null) { throw new Exception("name parameter cannot be null!"); } String queryString = "from Message m where m.postedBy = ?"; List<Message> message = getHibernateTemplate().find( queryString,postedBy ); if ( message.size() == 0 ) { return null; } if ( message.size() > 1 ) { throw new Exception("Found more than one messages with the same name." ); } return message.get(0); } /* (non-Javadoc) * */ @Override public void saveMessage(Message message) { System.out.print("Printed from DAO"+message.getComment()); this.getHibernateTemplate().saveOrUpdate( message ); this.getHibernateTemplate().flush(); } /* (non-Javadoc) * */ @Override public void updateMessage(Message message) { System.out.print("Printed from DAO"+message.getComment()); this.getHibernateTemplate().update( message ); this.getHibernateTemplate().flush(); } }

Above, note that the HibernateTemplate object (returned by the getHibernateTemplate() method) contains methods such as getAllMessages, getMessageById, getMessageByPostedBy, and saveOrUpdateMessage,which require no verbose explanation. Just note the find method: It is the recommended practice to always replace non-constant values with "?". Do not use string manipulation to bind a non-constant value in a query as follows:

String queryString = "from Message m where m.postedBy = ?"; List<Message> message = getHibernateTemplate().find( queryString,postedBy ); String queryString = "from Message m where m.postedBy = userName"; // NOT Recommended

Define the DAO objects

At this point, define the DAO objects in MessageDAO bean in the applicationContext configuration file. Some code snippets from this file follow:

<!-- START spring_messageboard DAO ================================= --> <bean id="MessageDAO" class="com.jack.springmvc.dao.MessageDAOHibernate"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- END spring_messageboard DAO =================================== -->

The bean id 'MessageDAO' represents your MessageDAOHibernate Implementation class.

Step 2: The UI Layer

For this step, we'll be following Spring's MVC pattern for this application. Spring provides a very clean division between controllers, JavaBean models, and views. We can use any object as a command or form object; there's no need to implement an interface or derive from a base class. Create a Controller object

package com.jack.springmvc.controller; import java.io.IOException; import java.util.Date; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; import com.jack.springmvc.delegate.MessageManager; import com.jack.springmvc.model.Model; import com.jack.springmvc.orm.entities.Message; import com.jack.springmvc.dao.MessageDAO; public class SpringController implements Controller { protected Logger logger = Logger.getLogger(SpringController.class); private Model model; private MessageManager mManager; MessageDAO messageDAO; Message message = new Message(); public Model getModel() { return model; } public void setModel(Model model) { this.model = model; } public MessageManager getMessageManager() { return mManager; } public void setMessageManager(MessageManager mManager) { this.mManager = mManager; } /** @return the messageDAO */ public MessageDAO getMessageDAO() { return messageDAO; } /** @param messageDAO the messageDAO to set */ public void setMessageDAO(MessageDAO messageDAO) { this.messageDAO = messageDAO; } public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response )throws ServletException, IOException { List<Message> messageslst = messageDAO.getAllMessages(); this.mManager.clearMessages(); for(int i=0;i < messageslst.size();i++){ this.mManager.postMessage(messageslst.get(i).getPostedBy().toString(),messageslst.get(i).getComment().toString()); } this.model.setTimeNow( ( new Date() ).toString() ); this.model.setMessages( this.mManager.getMessages()); this.model.setDiscussionTopic( this.mManager.getTopic()); logger.debug( "**** Debugging Model:

" + model ); return new ModelAndView( "messages", "model", model ); } }

For instance, if we look at the following example we will find that a model, in this case, is represented by the string "model". This actually refers to a list of all messageslst objects (the list of POJOs), returned by this line of code:

List<Message> messageslst = messageDAO.getAllMessages();

Wiring

Once our controller object is implemented, we next need to define it within our spring_messageboard-servlet.xml file. To do this, create a file named spring_messageboard-servlet.xml under the "WEB-INF" directory. The following examples are some code snippets for this file:

<beans> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass"> <value>org.springframework.web.servlet.view.JstlView</value> </property> <property name="prefix"> <value>/WEB-INF/jsp/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> <bean id="spring_messageboardController" class="com.jack.springmvc.controller.SpringController"> <property name="messageDAO" ref="MessageDAO" /> <property name="model"> <ref bean="model"/> </property> <property name="messageManager"> <ref bean="mManager"/> </property> </bean> <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <props> <prop key="/messages.spring">spring_messageboardController</prop> <prop key="/postmessage.spring">postMessageForm</prop> </props> </property> </bean> </beans>

* The "prefix" property defines that our JSP pages will reside under the war/jsp directory. * The "suffix" property defines that all views returned by the controller will be appended with a .jsp extension. * The bean with id "spring_messageboardController" defines the fully qualified name of our controller class. * The property key "/messages.spring" is actually a dummy name. If you provide this name with your URL, it will actually call the keyvalue 'spring_messageboardController'\97in other words, com.jack.springmvc.controller.SpringController object\97which, in turn, will return the view object in success.

Create a FormController object

A FormController object is used for data manipulation (insert, update, delete). It lets us specify a command object, a viewname for the form, a viewname for the page you want to show the user when form submission has succeeded, and more.FormController calls two distinct set of methods: one for GET request methods to prepare the form for display, and one for POST request methods to process the information extracted from the form. This corresponds with how most Web applications work: a GET signifies an edit, whereas a POST signifies a save or delete. FormController is a concrete FormController that provides configurable form and success views, and an onSubmit chain for convenient overriding. It automatically resubmits to the form view in case of validation errors, and renders the success view in case of a valid submission. Here are the two useful methods of the SimpleFormController object: * The onSubmit method, which is used for data insert, update, and delete operations. * The formBackingObject method, which is used to create an empty object for inserting data and a populated object for editing data. Now, create a MyObjectFormController object within the com.jack.springmvc.controller.SpringController package

package com.jack.springmvc.controller; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import org.springframework.web.servlet.view.RedirectView; import org.springframework.validation.Errors; import org.springframework.web.servlet.ModelAndView; import com.jack.springmvc.orm.entities.Message; import com.jack.springmvc.dao.MessageDAO; import com.jack.springmvc.delegate.MessageManager; import com.jack.springmvc.model.PostMessage; public class PostMessageFormController extends SimpleFormController { /** Logger for this class and subclasses */ protected final Log logger = LogFactory.getLog( getClass() ); private MessageManager messageManager; MessageDAO messageDAO; Message message = new Message(); public ModelAndView onSubmit( Object command ) throws Exception { PostMessage postmessage = ( PostMessage )command; Message message = new Message(); String bname = postmessage.getBloggerName(); String bMessage = postmessage.getNewMessage(); message.setComment(bMessage); message.setPostedBy(bname); messageDAO.saveOrUpdateMessage(message); List<Message> messageslst = messageDAO.getAllMessages(); messageManager.clearMessages(); for(int i=0;i < messageslst.size();i++){ messageManager.postMessage(messageslst.get(i).getPostedBy(). toString(),messageslst.get(i).getComment().toString()); } logger.info( "returning from AddNewMessageForm view to " + getSuccessView() ); return new ModelAndView( new RedirectView( getSuccessView() ) ); } protected Object formBackingObject( HttpServletRequest request ) throws ServletException { PostMessage pMessage = new PostMessage(); return pMessage; } public void setMessageManager( MessageManager messageManager ) { this.messageManager = messageManager; } public MessageManager getMessageManager() { return messageManager; } /** @return the messageDAO */ public MessageDAO getMessageDAO() { return messageDAO; } /** @param messageDAO the messageDAO to set */ public void setMessageDAO(MessageDAO messageDAO) { this.messageDAO = messageDAO; } }

Wiring

Define the PostMessageFormController object in the spring_messageboard-servlet.xml configuration file. As you can see, two views are defined in the spring_messageboard-servlet.xml file, one for the empty form and one for the successful form processing. The latter is called the success view. To restrict users from direct access to any JSP pages, the URL that is used is only externally reachable. This means that the "messages.spring" is used as the redirect URL, for example. It refers to the PostMessageFormController object, which finally returns the messages.jsp page. This can be depicted as follows:

<bean id="postMessageValidator" class="com.jack.springmvc.validator. PostMessageValidator"/> <bean id="postMessageForm" class="com.jack.springmvc.controller.PostMessageFormController"> <property name="messageDAO" ref="MessageDAO" /> <property name="sessionForm"> <value>true</value> </property> <property name="commandName"> <value>postMessage</value> </property> <property name="commandClass"> <value>com.jack.springmvc.model.PostMessage</value> </property> <property name="validator"> <ref bean="postMessageValidator"/> </property> <property name="formView"> <value>postmessage</value> </property> <property name="successView"> <value>messages.spring</value> </property> <property name="messageManager"> <ref bean="mManager"/> </property> </bean>

Create JSP pages

Here you will create a JSP page named "messages.jsp". After creation, place this under the 'spring_messageboard.war/jsp' directory and edit it as follows. This page will be used to display bogers comments only.

<%@ include file="/WEB-INF/jsp/include.jsp" %> <html> <head><title><fmt:message key="title"/></title></head> <body> <h1><fmt:message key="heading"/></h1> <p> <fmt:message key="time"/> <c:out value="${model.timeNow}"/> </p> <h3><fmt:message key="msgboard"/></h3> <table border="0" cellspacing="0" cellpadding="1" width="100%"> <tr bgcolor="orange"> <td width="20%"> Todays' Discussion Topic :: </td> <td><strong><u> <c:out value="${model.discussionTopic}"/> </u></strong> </td> <td><a href="<c:url value="postmessage.spring"/>"> Add Your Comment </a></td> </tr> <c:forEach items="${model.messages}" var="message"> <tr bgcolor="f8f8ff"> <td> <c:out value="${message.postedBy}"/> </td> <td colspan="2"> <c:out value="${message.comment}"/> </td> </tr> </c:forEach> </table> </body> </html>

In the preceding example, * The ${model.*} object is returned by the handleRequest() method of the SpringController object (the second parameter of the ModelAndView method). * The link to the postmessage.spring is the redirected URL, which actually refers to the postmessage.jsp page. Now, create another JSP page named "postmessage.jsp" and place it under the 'spring_messageboard.war/jsp' directory

<%@ include file="/WEB-INF/jsp/include.jsp" %> <%@ taglib prefix="spring" uri="/spring" %> <html> <head> <title> <fmt:message key="title"/> </title> </head> <body> <h1><fmt:message key="postmessage.heading"/></h1> <form method="post"> <table width="95%" bgcolor="f8f8ff" border="0" cellspacing="0" cellpadding="5"> <tr> <td alignment="right" width="20%">Bloggers Name:</td> <spring:bind path="postMessage.bloggerName"> <td width="40%"> <input type="text" name="bloggerName" value="<c:out value="${status.value}"/>"> </td> <td width="60%"> <font color="red"> <c:out value="${status.errorMessage}"/></font> </td> </spring:bind> </tr> <tr> <td alignment="right" width="20%" valign="top"> Enter Your Comment:</td> <spring:bind path="postMessage.newMessage"> <td width="40%"> <textArea name="newMessage" cols="60" rows="4" value="<c:out value="${status.value}"/>"> </textArea> </td> <td width="60%"> <font color="red"><c:out value="${status.errorMessage} "/></font> </td> </spring:bind> </tr> </table> <br> <spring:hasBindErrors name="postMessage"> <b>Please fix all errors!</b> </spring:hasBindErrors> <br><br> <input type="submit" alignment="center" value="Execute"> </form> <a href="<c:url value="messages.spring"/>">View Posted Comments</a> </body> </html>

In the preceding code, * By using 2 <%@ taglib prefix="spring" uri="/spring" %>, the spring tag library properties are imported in your JSP page. * The <spring:bind> tag is used to bind an <input> form element to a command object Message. The ${status.value} are special variables declared by the framework that can be used to display the current value of the field.

Step 3: Build and Deploy the Application

Create a database called "messageboard" if you have not done so. After copying your project to your java_projects directory, Open command prompt change directory to masterbuild directory of spring_messageboard application("C:\YOURNAME\DATA\java_projects\spring_messageboard \trunk\SVN_LOCAL\masterbuild" in my case). In the command line type "ant -p" and press return key to display all the targets defined in the build.xml file. Type "ant clean deploy.ear" targets to build and deploy the application in jboss. Open browser and type the url below to run the application. " http://localhost:8080/spring_messageboard"

Conclusion

Having gone through this tutorial, you are expected to have understood the basics of how Hibernate operates, and are able to write any piece of code using Hibernate.