http://www.developer.com/java/ent/article.php/3577101/Developing-J2EE-Applications-Using-Hibernate-Annotations-and-Spring-MVC.htm
The first part of this three-part series introduced you to the latest JDK5 annotations feature. 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, developers can drastically reduce the time at the configuration level. No more artless mapping files, no more klutzy XDoclet tags; life becomes so easy! This article describes a step-by-step procedure of how to build, deploy, and run a simple J2EE-based Web application using the above-mentioned technologies. It is assumed that readers of this article are quite familiar with J2EE technologies including JDBC, containers/servers, ORM tools, and frameworks. It is also recommended that readers go through that first article, "An Introduction to Java Annotations," as a primer. In J2EE-based Web applications, a traditional approach is to use XML mapping files with Hibernate when defining persistent objects (as in using one hbm.xml file per POJO). For example, if you have 40 POJOs with complex inter-relationships, you will have to define 40 hbm.xml mapping files, which is not only time-consuming but also very error prone. If you use Hibernate annotations, however, there will be no need to use such mapping files anymore. The compiler will read the annotated codes before runtime and process them as accordingly before the class is loaded (the ClassData model). The annotated beans can be accessed from the Hibernate DAO layer. For Hibernate, Spring provides good support with IoC features, addressing many typical Hibernate issues. Thus, DAOs can be configured through Dependency Injection and participate in Spring's resource and transaction management. The main advantage of the DAO layer is that it completely decouples business logic from persistence technology. The business logic layer (also known as the service layer or the manager layer) can be configured to communicate with the UI layer through some MVC type framework. MVC is a pattern that helps separate presentation from business logic. Although dependency injection is the basis of the Spring framework, it also provides a rich set of tools built on top of its core dependency injection functionality. It provides an MVC framework, transaction management, support for several O/R mapping tools, and more. I've chosen Spring's MVC pattern for this tutorial to provide you with an idea about how Spring MVC manages a clean division between controllers, JavaBean models, and views. Rather than providing theoretical descriptions, I will take the examples-with-explanation approach. You will be taken through the following five steps: You will need JDK5, Tomcat 5.x, Ant Tool, Hibernate annotations, Spring core, Hibernate 3, plus other commonly required jars to deploy this application. Here is the list and the suggested URLs where you can obtain these: Set up an environment for JAVA_HOME, ANT_HOME, and CATALINA_HOME, as demonstrated accordingly. This is shown in Figure 4: Copy all the required jar files as mentioned above in Step #1 and paste them under the 'warWEB-INFlib' directory. Figure 5 shows my environment with all the jars that are required for this application. Click here to get the build.properties and build.xml files and place these under the root directory "springapp". Edit the build.properties file according to your Tomcat environment. Modify the Tomcat location, url, manager id, and password as needed. In this step, you will need to create the entity (Persistent POJO). Typically, you will be working with the persistence layer first. To do this, you will create a persistent object mapping to your 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: The following example shows you how you can create an entity bean named MyObjectVO: Entity bean with annotations declared at method level Entity bean with annotations declared at variable/properties level For this example, I have chosen to use the method-level annotations declaration. Click here to get the full source code for MyObjectVO.java. As you can see from the previous example, 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. In short, here are the few actions you must not forget when defining an entity POJO: The next step after defining the entity is to create a Hibernate configuration file. Start by creating a file named hibernate.cfg.xml and place it under the WEB-INF/ directory. The fully qualified class name of the POJO should be included within the <mapping> tag (highlighted portion below). If more POJOs are created, they will simply be included with additional <mapping> tags under the <session-factory> tag. (Click here to get the hibernate.cfg.xml.file.) The file should look like this: Next, create a JDBC configuration file. To begin, create a file named applicationContext-jdbc.xml and place it under the "springappwarWEB-INF" directory. (Click here to get the applicationContext-jdbc.xml file.) If you have a different database schema other than this, just change the values for the properties "driverClassName", "url", "username", and "password" according to your DB environment. At this point in the POJO creation, you will need to wire it properly with your data access objects (DAOs). To do this, you will need to create your required DAO interface and implementation objects, and define them in your applicationContextXXX.xml file (wiring) to work with the persistent POJO. The following code snipped demonstrates how to create the DAO objects. Create a MyObjectDao interface and a MyObjectDaoImpl implementation class within the org.annotationmvc.dao package as follows, or click here to get the source code for MyObjectDao.java and MyObjectDaoImpl.java. The DAO interface The DAO implementation Above, note that the HibernateTemplate object (returned by the getHibernateTemplate() method) contains methods such as find, loadAll, save, and update, 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: At this point, define the DAO objects in a DAO configuration file. Create a file named applicationContext-dao.xml and place it under the "springappwarWEB-INF" directory. (Click here to get the applicationContext-dao.xml file.) Some code snippets from this file follow: Here is an explanation for the applicationContext-dao.xml file: In this step, you will need to create service objects and wire these classes. Click these links to get the source codes for the interface MyObjectService.java and the implementation class MyObjectServiceImpl.java. These should be under the org.annotationmvc.service package: If you look at these two classes, you will find that these are similar to the MyObjectDao and MyObjectDaoImpl objects with their method definitions, except for the class names. These classes basically hold the business rules. For data manipulation, it uses the DAO object to communicate at the persistence layer. For example, consider the findMyObjectById(...) method. To fetch an object by its object id, it simply invokes the MyObjectDAO's findMyObjectById method. Other methods do not need further explanation. Create a file named applicationContext-service.xml and place it under the "springappwarWEB-INF" directory. (Click here to get the applicationContext-service.xml file.) Some code snippets from this file are seen below: Note the bean with id "Service". The setter injection is identified from the property name "myObjectDao", which you have declared within the MyObjectServiceImpl class's setMyObjectDao(MyObjectDao myObjectDao) method. For this step, you will be following Spring's MVC pattern for this application. Spring provides a very clean division between controllers, JavaBean models, and views. You can use any object as a command or form object; there's no need to implement an interface or derive from a base class. Spring's data binding is highly flexible; for example, it treats type mismatches as validation errors that can be evaluated by the application, not as system errors. So, you don't need to duplicate your business objects' properties as Strings in your form objects just to be able to handle invalid submissions, or to convert the Strings properly. Instead, it is often preferable to bind directly to your business objects. This is another major difference to Struts, which is built around required base classes like Action and ActionForm—for every type of action. Okay, enough of theory, let's do some real work now: (Click here to get the Controller object, MyObjectController.java, used in this example.) This should be placed under the org.annotationmvc.web package. The Controller object is used to display read-only data. You cannot use it for data manipulation. It returns a ModelAndView object, which returns both a model (for example, the ArrayList containing the list of objects) and a view (as in the name of the JSP page). For instance, if you look at the following example you will find that a model, in this case, is represented by the string "myObjectModel". This actually refers to a list of all MyObjectVO objects (the list of POJOs), returned by the third parameter—in other words, myObjectService.getAllMyObjectVOs(). A view object, on the other hand, actually refers to the JSP page, which is represented by the string "ViewAllMyObjects". This would simply be interpreted as "ViewAllMyObjects.jsp", which is explained later in this article. Once your controller object is implemented, you next need to define it within your action-servlet.xml file. To do this, create a file named action-servlet.xml under the "WEB-INF" directory or, click here to download the action-servlet.xml. The following examples are some code snippets for this file: The following list explains some of the properties defined in the previous configuration file: (If you are interested in learning more about Spring's Controller objects, you can check this URL at http://www.springframework.org/docs/MVC-step-by-step/Spring-MVC-step-by-step-Part-2.html.) A SimpleFormController object is used for data manipulation (insert, update, delete). It lets you 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. SimpleFormController 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. SimpleFormController 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: Now, create a MyObjectFormController object within the org.annotationmvc.web package or, you can click here to download MyObjectFormController.java. Code snippets from this example are seen below: Define the MyObjectFormController object in the action-servlet.xml configuration file. You can get the updated action-servlet.xml file here. As you can see, two views are defined in the action-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 "MyObjectForm.html" is used as the redirect URL, for example. It refers to the MyObjectFormController object, which finally returns the MyObjectForm.jsp page. This can be depicted as follows: (For details on Spring's SimpleFormController object, please check this URL: http://www.springframework.org/docs/MVC-step-by-step/Spring-MVC-step-by-step-Part-3.html.) Here you will create a JSP page named "ViewAllMyObjects.jsp". After creation, place this under the 'springappwarjsp' directory and edit it as follows. This page will be used to display data only. Click here to download ViewAllMyObjects.jsp. In the preceding example, Now, create another JSP page named "MyObjectForm.jsp" and place it under the 'springappwarjsp' directory, or click here to get the code for MyObjectForm.jsp. The code snippet from this page should look like the following: In the preceding code, (For details, you can check here: http://www.springframework.org/docs/MVC-step-by-step/Spring-MVC-step-by-step-Part-3.html.) Also, create a file named test.html under the 'springappwarjsp' directory. Just keep it empty. This is not for real use; you will simply use it as a welcome file. If invoked from the URL as http://localhost:8080/war/test.html, this will simply be redirected to the MyObjectController object, which in turn, will return a list of MyObjectVOs, as explained earlier. Create an web.xml file and place it under the 'WEB-INF' directory. Click here to download web.xml. Within this file, In this step, you will build and deploy the application. The following steps describe this process for you. To do this, go to the command prompt and type ant build. See Figure 6. Use the command ant deploywar. See Figure 7. Start tomcat, point to your browser address bar, and type http://localhost:8080/springapp/test.html. If you see something like Figure 8, everything is okay. You have not inserted any data yet; that's why your browser is displaying an empty list screen. Just click on the "Click here to add new Object" link; a new empty form page will be displayed. Just insert some data and press "Add". See Figure 9. Your populated screen will look something like Figure 10: You can click any of the ID links and edit the corresponding object data. This article has shown you how to apply the Hibernate annotations feature with Spring to develop J2EE-based applications. Hibernate annotation is built on top of the basic JDK5 annotations features, which do not directly affect the semantics of a program. Development and deployment tools can read these annotated codes during runtime and process them accordingly. This tutorial also described how to get Spring MVC to come into play. The objective is to spend less time on configuration and more focus on business logic rules. This article is Part II of a series on Java Annotations. In Part I, you were introduced with the JDK5 annotations features. In Part III, you will see a complex example that includes multiple database tables relationships. M. M. Islam Chisty currently works as a Software Engineer for M&H Informatics. His responsibilities include the development and re-engineering of Web-based applications using J2EE technologies. He has a BS in computer science from North South University. He loves spending free time doing R&D on the latest Java-based technologies, watching TV, and listening to music—not to mention that he is a great WWE fan too.
Developing J2EE Applications Using Hibernate Annotations and Spring MVC
January 12, 2006
Prerequisites
Step 1: Setup up Your Development Environment
1. Obtain the required jars.
Download URL: http://java.sun.com/j2se/1.5.0/download.jsp
Download URL: http://www.axint.net/apache/jakarta/tomcat-5/v5.0.28/bin/jakarta-tomcat-5.0.28.zip
Download URL: http://archive.apache.org/dist/ant/binaries/
Download URL: http://annotations.hibernate.org
Core spring jar files reside under the "spring-framework-1.2.4dist" directory, see Figure 2.
http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html
2. Set up your environment.
Note: If you need more instruction on how to set up your development environment, here is a good link you can follow: http://hackydev.ics.hawaii.edu/hackyDevSite/hackyBuild/README.1.html.
3. Create a directory structure.
Root directory:
springapp Source directory:
springappsrc Directory for packages
Directory for web pages
springappwarjsp (JSP pages here) Directory for configuration files
warWEB-INF (xml configuration files here) Directory for jars
warWEB-INFlib (all the required jar files will reside here) 
4. Copy and paste.

5. Get the build properties.
Step 2: The Persistence Layer
Defining an entity
package org.annotationmvc.vo;
import java.io.*;
import javax.persistence.*;
@Entity(access = AccessType.PROPERTY)
@Table (name="myobject")
public class MyObjectVO implements Serializable {
private int id,
private String name;
private String address;
private String email;
private String phone;
@Id (generate = GeneratorType.AUTO)
public int getId() {
return id;
}
@Column (length=100)
public String getName() {
return name;
}
@Column (length=100)
public String getAddress() {
return address;
}
@Column (length=30)
public String getEmail() {
return email;
}
@Column (length=15)
public String getPhone() {
return phone;
}
public void setXXX() {
....
}
}
package org.annotationmvc.vo;
import java.io.*;
import javax.persistence.*;
@Entity(access = AccessType.FIELD)
@Table (name="myobject")
public class MyObjectVO implements Serializable {
@Id (generate = GeneratorType.AUTO)
private int id;
@Column (length=100)
private String name;
@Column (length=100)
private String address;
@Column (length=30)
private String email;
@Column (length=15)
private String phone;
public String getXXX()
{
....
}
public void setXXX() {
....
}
Some Rules of Thumb for Defining an Entity
@Column(name = "address", nullable =
false, length=100, unique=false)
Create a Hibernate configuration file
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping class="org.annotationmvc.vo.MyObjectVO"/>
</session-factory>
</hibernate-configuration>
Create a JDBC configuration file
Wiring POJO with DAO
package org.annotationmvc.dao;
public interface MyObjectDao {
MyObjectVO findMyObjectById(int id);
void insertMyObjectVO(MyObjectVO myObjectVO);
void updateMyObjectVO(MyObjectVO myObjectVO);
List getAllMyObjectVOs();
void removeMyObjectVO(MyObjectVO myObjectVO);
}
package org.annotationmvc.dao;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class MyObjectDaoImpl extends HibernateDaoSupport
implements MyObjectDao {
public MyObjectVO findMyObjectById(int id) {
List list=getHibernateTemplate().find("from MyObjectVO
where id=?",id);
return (MyObjectVO) list.get(0);
}
public List getAllMyObjectVOs() {
return getHibernateTemplate().loadAll(MyObjectVO.class);
}
public void insertMyObjectVO(MyObjectVO myObjectVO) {
getHibernateTemplate().save(myObjectVO);
}
public void removeMyObjectVO(MyObjectVO myObjectVO) {
getHibernateTemplate().delete(myObjectVO);
}
public void updateMyObjectVO(MyObjectVO myObjectVO) {
getHibernateTemplate().update(myObjectVO);
}
}
getHibernateTemplate().find("from MyObjectVO where id="+id);
// NOT Recommended
Define the DAO objects
<beans>
...
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.
LocalSessionFactoryBean">
<property name="dataSource"><ref bean="dataSource"/></property>
<property name="configLocation">
<value>WEB-INF/hibernate.cfg.xml</value></property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.
Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
...
...
<bean id="daoTmpl">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<bean id="myObjectDao"
class="org.annotationmvc.dao.MyObjectDaoImpl"
parent="daoTmpl"/>
...
</beans>
Step 3: The Service, or Business Logic, Layer
Create service objects
Wiring
<beans>
...
<bean id="myObjectService" parent="txProxyTemplate">
<property name="target">
<bean class="org.annotationmvc.service.MyObjectServiceImpl">
<property name="myObjectDao">
<ref bean="myObjectDao" />
</property>
</bean>
</property>
</bean>
...
</beans>
Step 4: Creating the UI Layer
Create a Controller object
package org.annotationmvc.web;
public class MyObjectController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
return new ModelAndView("ViewAllMyObjects",
"myObjectModel",
myObjectService.getAllMyObjectVOs());
}
public void setMyObjectService(MyObjectService
myObjectService) {
this.myObjectService = myObjectService;
}
}
Wiring
...
<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>/jsp/</value></property>
<property name="suffix"><value>.jsp</value></property>
</bean>
<!-- Custom controller objects -->
<bean id="moController"
class="org.annotationmvc.web.MyObjectController">
<property name="myObjectService">
<ref bean="myObjectService"/>
</property>
</bean>
<bean id="urlMapping"
class="org.springframework.web.servlet.handler.
SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/test.html">moController</prop>
</props>
</property>
</bean>
</beans>
Create a SimpleFormController object
package org.annotationmvc.web;
public class MyObjectFormController extends SimpleFormController {
public MyObjectService getMos() {
return mos;
}
public void setMos(MyObjectService mos) {
this.mos = mos;
}
public ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response,
Object cmd, BindException errors)
throws Exception {
MyObjectVO myObjectVO = (MyObjectVO) cmd;
if (null != request.getParameter("delete")) {
mos.removeMyObjectVO(myObjectVO);
} else if (null != request.getParameter("update")) {
mos.updateMyObjectVO(myObjectVO);
} else if (null != request.getParameter("add")) {
mos.insertMyObjectVO(myObjectVO);
}
return new ModelAndView(new RedirectView(getSuccessView()));
}
protected Object formBackingObject(HttpServletRequest
request)
throws ServletException {
String id = request.getParameter("id");
if (null != id && !id.equals("")) {
return mos.findMyObjectById(Integer.parseInt(id));
}
return new MyObjectVO();
}
}
Wiring
MyObjectForm.html
--> MyObjectFormController (referred by prop key value
"moFormController")
--> MyObjectForm (referred by the property value
"formView") -->
MyObjectForm.jsp (interpreted)
Create JSP pages
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<html>
<head><title>ViewAllMyObjects</title></head>
<body bgcolor="#ffffff">
<h1>View All Objects</h1>
<table border="1" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Address</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<c:forEach items="${myObjectModel}" var="mobj"
varStatus="status">
<tr>
<td>
<a href="MyObjectForm.html?id=${mobj.id}">
${mobj.id}</a>
</td>
<td> ${mobj.name}</td>
<td> ${mobj.address}</td>
<td> ${mobj.email}</td>
<td> ${mobj.phone}</td>
</tr>
</c:forEach>
<tr>
<td colspan="5">
<a href="MyObjectForm.html">
Click here to add new Object
</a>
</td>
</tr>
</table>
</body>
</html>
<%@ taglib uri="http://www.springframework.org/tags"
prefix="Spring"%>
<html>
<body bgcolor="#ffffff">
<form method="post">
<table border="1">
<tr>
<td>Id</td>
<td>
<Spring:bind path="myobject.id">
<input type="text"
name="id"
value="${status.value}"
disabled="disabled"/>
</Spring:bind>
</td>
</tr>
<tr>
<td>Name</td>
<td>
<Spring:bind path="myobject.name">
<input type="text"
name="name"
size="20"
value="${status.value}"/>
</Spring:bind>
</td>
</tr>
... ...
...
</tr>
<tr>
<td><input type="submit"
name="delete"
value="Delete"/></td>
<td><input type="submit"
name="update"
value="Update"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit"
name="add" value="+ Add +"/>
</td>
</tr>
</form>
</table>
</body>
</html>
Configure web.xml
Step 5: Build and Deploy the Application
1. Build the application.

2. Deploy the application.

3. Check your deployment.



Conclusion
Resources
About the Author