Developing J2EE Applications Using Hibernate Annotations and Spring MVC

Thursday Jan 12th 2006 by M. M. Islam Chisty
Share:

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!

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.

Prerequisites

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:

  1. Setting up up your environment.
  2. The persistence layer.
  3. The service, or business logic, layer.
  4. The UI layer.
  5. Building, deploying, and running the application.

Step 1: Setup up Your Development Environment

1. Obtain the required jars.

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:

2. Set up your environment.

Set up an environment for JAVA_HOME, ANT_HOME, and CATALINA_HOME, as demonstrated accordingly.

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.

This is shown in Figure 4:

Root directory: springapp
Source directory: springappsrc
Directory for packages
  • srcorgannotationmvcvo (persistence beans will reside here)
  • srcorgannotationmvcdao (DAO objects here)
  • srcorgannotationmvcservice (Service objects here)
  • srcorgannotationmvcweb (web controller objects here)
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.

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.

5. Get the build properties.

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.

Step 2: The Persistence Layer

Defining an entity

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:

  • At the getter-methods level
  • At the object's properties level

The following example shows you how you can create an entity bean named MyObjectVO:

Entity bean with annotations declared at method level

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() {
      ....
   }

}

Entity bean with annotations declared at variable/properties level

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() {
      ....
   }

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.

Some Rules of Thumb 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 = "address", nullable =
            false, length=100, unique=false)
    
    • 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.

Create a Hibernate configuration file

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:

<!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

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.

Wiring POJO with DAO

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

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);
}

The DAO implementation

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);
   }
}

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:

getHibernateTemplate().find("from MyObjectVO where id="+id);
   // NOT Recommended

Define the DAO objects

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:

<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>

Here is an explanation for the applicationContext-dao.xml file:

  • The "dataSource" property holds a reference (<ref bean="dataSource">) to the dataSource value defined in your external configuration file applicationContext-jdbc.xml. Similarly, the "configLocation" refers to the POJOs defined in the hibernate.cfg.xml file.
  • The "configurationClass" property value enables the annotation feature for Hibernate.
  • Because the database used in this application is Oracle, the "hibernate.dialect" property should use "org.hibernate.dialect.Oracle9Dialect" as the dialect value. There are different dialect values for different DBs. If your DB is something other than Oracle, you will have to change this value accordingly. For details on how you can set your dialect properties, please visit this URL: http://www.hibernate.org/hib_docs/v3/reference/en/html_single/#configuration-optional-dialects.
  • The bean id 'myObjectDao' represents your DAO Implementation class. It inherits the parent object 'daoTmpl' which, in turn, holds a reference to the sessionFactory object. Rather than using a <ref> for each and every bean you define, it is better to declare this in a parent object and simply inherit child objects.

Step 3: The Service, or Business Logic, Layer

In this step, you will need to create service objects and wire these classes.

Create service objects

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.

Wiring

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:

<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>

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.

Step 4: Creating the UI Layer

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:

Create a Controller object

(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.

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

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:

...
<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>

The following list explains some of the properties defined in the previous configuration file:

  • The "prefix" property defines that your 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. For example, the MyObjectController returns a view named "ViewAllMyObjects". By using the suffix property, this will actually be interpreted as ViewAllMyObjects.jsp and search for a JSP page named ViewAllMyObjects.jsp under the war/jsp directory. This means that you must have a JSP file with this name. If no page with this name is found, an exception will be generated during runtime.
  • The bean with id "moController" defines the fully qualified name of your controller class.
  • The property key "/test.html" is actually a dummy name. If you provide this name with your URL, it will actually call the keyvalue 'moController'—in other words, org.annotationmvc.web.MyObjectController object—which, in turn, will return the view object in success.

(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.)

Create a SimpleFormController object

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:

  • 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 org.annotationmvc.web package or, you can click here to download MyObjectFormController.java. Code snippets from this example are seen below:

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

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:

MyObjectForm.html
--> MyObjectFormController (referred by prop key value
                            "moFormController")
--> MyObjectForm (referred by the property value
                  "formView") -->
MyObjectForm.jsp (interpreted)

(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.)

Create JSP pages

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.

<%@ 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>

In the preceding example,

  • The ${myObjectModel} object is returned by the handleRequest() method of the MyObjectController object (the second parameter of the ModelAndView method)
  • The link to the MyObjectForm.html is the redirected URL, which actually refers to the MyObjectForm.jsp page

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:

<%@ 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>

In the preceding code,

  • By using <%@taglib uri="http://www.springframework.org/tags" prefix="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 MyObjectVO. The ${status.value} are special variables declared by the framework that can be used to display the current value of the field.

    (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.

Configure web.xml

Create an web.xml file and place it under the 'WEB-INF' directory. Click here to download web.xml.

Within this file,

  • The servlet name "action" is used by the DispatcherServlet class. This means that it will look for a configuration file named <servlet-name>-servlet.xml. In this case, it would be action-servlet.xml.
  • The <url-pattern> is used as *.html, which means the application will go through the files with extension of type .html only.
  • You will need the spring.tld file for the Spring tag library definition. I've provided one here. Just place it under your springappwarWEB-INF directory.

Step 5: Build and Deploy the Application

In this step, you will build and deploy the application. The following steps describe this process for you.

1. Build the application.

To do this, go to the command prompt and type ant build. See Figure 6.

2. Deploy the application.

Use the command ant deploywar. See Figure 7.

3. Check your deployment.

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.

Conclusion

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.

Resources

  1. Source code accompanying this article.
  2. Hibernate Annotations: http://sourceforge.net/project/showfiles.php?group_id=40712&package_id=139933
  3. Hibernate3 and EJB3 at JBoss site: http://docs.jboss.org/ejb3/HibernateAnnotations/reference/en/html_single/
  4. JDK5: http://java.sun.com/developer/technicalArticles/J2SE/constraints/annotations.html
  5. Spring MVC: http://www.springframework.org/docs/MVC-step-by-step/Spring-MVC-step-by-step.html
  6. Jakarta Tomcat version 5.0.28: http://www.axint.net/apache/jakarta/tomcat-5/v5.0.28/bin/jakarta-tomcat-5.0.28.zip

About the Author

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.

Share:
Home
Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved