October 21, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Developing J2EE Applications Using Hibernate Annotations and Spring MVC

  • January 12, 2006
  • By M. M. Islam Chisty
  • Send Email »
  • More Articles »

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.




Page 2 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel