Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

December 31, 2011

Spring - Hibernate framework Integration - Hello World Example

0) To proceed with this example, complete the Spring Hello World Example and the Hibernate Hello World Example

1) Put 2 jar files from the Apache Commons collection in the WebContent/WEB-INF/lib folder of the web application - download the jars from this link

2) Add the following elements to the Spring configuration file, applicationContext.xml
Integrating Spring with Hibernate results in the hibernate.cfg.xml becoming obsolete - the configuration in hibernate.cfg.xml is now put in the applicationContext.xml

Configuration for DataSource (Database Connection properties)

<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName" value="oracle.jdbc.OracleDriver" />
   <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />
   <property name="username" value="system" />
   <property name="password" value="system" />
</bean>

Configuration for Hibernate (of hibernate.cfg.xml)


<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
   <property name="dataSource" ref="dataSource"/>
   <property name="mappingResources">
      <list>
         <value>info/icontraining/hibernate/Message.hbm.xml</value>
      </list>
   </property>
   <property name="hibernateProperties">
      <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
      </props>
   </property>
</bean>

Configuration for HibernateTemplate, DAOs, etc.

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
   <property name="sessionFactory" ref="sessionFactory" />
</bean>
 
<bean id="myDao" class="info.icontraining.dao.MyDAO">
   <property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>


3) Create a MyDAO.java class in the src folder of the web application - this class does the actual persistence

package info.icontraining.dao;

import java.util.List;
import info.icontraining.hibernate.Message;
import org.springframework.orm.hibernate3.HibernateTemplate;

public class MyDAO {

   private HibernateTemplate hibernateTemplate;
 
   public void setHibernateTemplate(HibernateTemplate template) {
      this.hibernateTemplate = template;
   }
 
   public void saveData(String str) {
      Message message1 = new Message(str);
      hibernateTemplate.save(message1);
   }

   public int retrieveData() {
      List<Message> messages = hibernateTemplate.find("from Message as m order by m.text asc");
      return messages.size();
   } 
}


4) Create a client JSP - springHibernate.jsp - in the WebContent folder of the web application


<%@ page  import="org.springframework.context.*,org.springframework.web.context.*,info.icontraining.spring.*,info.icontraining.dao.*"%>
<html>
<body>

<% 
 ApplicationContext factory = 
  (ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

 MyDAO mydao = (MyDAO)factory.getBean("myDao");
 mydao.saveData("Spring Hibernate");
 
 int numMessages = mydao.retrieveData();
%>
 
<%= numMessages + " messages found." %>

</body>
</html>

5) Test the example with the following URL in the browser,

http://localhost:8080/WebAppName/springHibernate.jsp

Log into Oracle Database and check the contents of the appropriate table

May 8, 2011

Hibernate Entity Mapping: May-to-many relationship with a join table

Map a many-to-many relationship between 2 entities with a link table in the database schema.

1) Create the Category and Item entity persistent classes.

Category.java

package info.icontraining.hibernate;

import java.util.*;

public class Category {
 
   private Long id;
   private String categoryName;
   private Set<Item> items = new HashSet<Item>() ;
 
   public Long getId() {
      return id;
   }
   public void setId(Long id) {
      this.id = id;
   }
   public String getCategoryName() {
      return categoryName;
   }
   public void setCategoryName(String categoryName) {
      this.categoryName = categoryName;
   }
   public Set<Item> getItems() {
      return items;
   }
   public void setItems(Set<Item> items) {
      this.items = items;
   }
}


Item.java

package info.icontraining.hibernate;

import java.util.*;

public class Item {

   private Long id;
   private String itemName;
   private Set<Category> categories = new HashSet<Category>();
 
   public Long getId() {
      return id;
   }
   public void setId(Long id) {
      this.id = id;
   }
   public String getItemName() {
      return itemName;
   }
   public void setItemName(String itemName) {
      this.itemName = itemName;
   }
   public Set<Category> getCategories() {
      return categories;
   }
   public void setCategories(Set<Category> categories) {
      this.categories = categories;
   }
}


2) Create the Mapping files,

Category.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.Category" table="CATEGORY_TABLE"> 
      <id name="id" column="CATEGORY_ID"> 
         <generator class="native" /> 
      </id> 
      <property name="categoryName" column="CATEGORY_NAME" type="string" />
      <set name="items" table="CATEGORY_ITEM" cascade="save-update">
         <key column="CATEGORY_ID" />
         <many-to-many class="info.icontraining.hibernate.Item" column="ITEM_ID" />
      </set>
   </class> 
</hibernate-mapping>


Item.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.Item" table="ITEM_TABLE"> 
      <id name="id" column="ITEM_ID"> 
         <generator class="native" /> 
      </id> 
      <property name="itemName" column="ITEM_NAME" type="string" />
      <set name="categories" table="CATEGORY_ITEM" cascade="save-update" inverse="true">
         <key column="ITEM_ID" />
         <many-to-many class="info.icontraining.hibernate.Category" column="CATEGORY_ID" />
      </set>
   </class> 
</hibernate-mapping>


3) In the hibernate.cfg.xml file, add the following configuration,

<mapping resource="info/icontraining/hibernate/Item.hbm.xml" />
<mapping resource="info/icontraining/hibernate/Category.hbm.xml" />


4) Create the client code in a servlet, as follows,

package info.icontraining.servlets;

import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.* ; 
import org.hibernate.*; 
import info.icontraining.hibernate.*;

public class CategoryItem extends HttpServlet { 
  
   public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{ 
  
      PrintWriter out = res.getWriter(); 

      Session session = HibernateUtil.getSessionFactory().openSession(); 
      Transaction tx = session.beginTransaction(); 
   
      Category category1 = new Category();
      category1.setCategoryName("Category-1");
   
      Category category2 = new Category();
      category2.setCategoryName("Category-2");
   
      Item item1 = new Item();
      item1.setItemName("Item-1");
   
      Item item2 = new Item();
      item2.setItemName("Item-2");
 
      category1.getItems().add(item1);
      category1.getItems().add(item2);
   
      category2.getItems().add(item1);
      category2.getItems().add(item2);
  
      item1.getCategories().add(category1);
      item1.getCategories().add(category2);
   
      item2.getCategories().add(category1);
      item2.getCategories().add(category2);
   
      session.save(category1);
      session.save(category2);
   
      tx.commit(); 
      session.close(); 

      Session newSession = HibernateUtil.getSessionFactory().openSession(); 
      Transaction newTx = newSession.beginTransaction(); 
   
      List<Category> categories = newSession.createQuery("from Category").list(); 
      out.println( categories.size() + " categories found:" ); 
      for ( Iterator<Category> iter = categories.iterator(); iter.hasNext(); ) { 
         Category cat = iter.next(); 
         out.println( "Name of Category: " + cat.getCategoryName()); 
         out.println( "Number of Items in Category: " + cat.getItems().size());
      } 
   
      newTx.commit(); 
      newSession.close();
   } 
}


5) Configure the servlet in a web.xml file,

<servlet>
   <servlet-name>CategoryItem</servlet-name>
   <servlet-class>info.icontraining.servlets.CategoryItem</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>CategoryItem</servlet-name>
   <url-pattern>/categoryItem</url-pattern>
</servlet-mapping>


6) Enter the following URL in the browser,

http://localhost:8080/WebAppName/categoryItem

7) Check the database for the created tables and the data in those tables

Hibernate Entity Mapping: One-to-one relationship with shared primary key association

Map a one-to-one entity relationship where the primary key of the parent table is shared as also the primary key of the child table as well as the foreign key referencing the primary key of the parent table.

The Person entity has a one-to-one relationship with the Address entity. In the database schema, the table mapped to Person will be the parent table and the table mapped to Address will be the child table.

1) Create the Player and Address entity persistent classes,

Person.java

package info.icontraining.hibernate;

public class Person {
 
   private Long id;
   private String name;
   private Address address;
 
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public Address getAddress() {
      return address;
   }
   public void setAddress(Address address) {
      this.address = address;
   }
   public Long getId() {
      return id;
   }
   public void setId(Long id) {
      this.id = id;
   }
}


Address.java

package info.icontraining.hibernate;

public class Address {

   private Long id;
   private String city;
   private Person person;
 
   public String getCity() {
      return city;
   }
   public void setCity(String city) {
      this.city = city;
   }
   public Person getPerson() {
      return person;
   }
   public void setPerson(Person person) {
      this.person = person;
   }
   public Long getId() {
      return id;
   }
   public void setId(Long id) {
      this.id = id;
   }
}


2) Create the mapping files, Person.hbm.xml and Item.hbm.xml,

Person.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.Person" table="PERSON_TABLE"> 
      <id name="id" column="PERSON_ID"> 
         <generator class="native" /> 
      </id> 
      <property name="name" column="PERSON_NAME" type="string" />
      <one-to-one name="address" class="info.icontraining.hibernate.Address" cascade="save-update" />
   </class> 
</hibernate-mapping>

Address.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.Address" table="ADDRESS_TABLE"> 
      <id name="id" column="ADDRESS_ID"> 
         <generator class="foreign">
            <param name="property">person</param>
         </generator> 
      </id> 
      <property name="city" column="CITY" type="string" />
      <one-to-one name="person" class="info.icontraining.hibernate.Person" constrained="true" />
   </class> 
</hibernate-mapping>


3) In the hibernate.cfg.xml file, add the following configuration,

<mapping resource="info/icontraining/hibernate/Person.hbm.xml" />
<mapping resource="info/icontraining/hibernate/Address.hbm.xml" />


4) Create the client code in a servlet, as follows,

package info.icontraining.servlets;

import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.* ; 
import org.hibernate.*; 
import info.icontraining.hibernate.*;

public class PersonAddress extends HttpServlet { 
  
   public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{ 
  
      PrintWriter out = res.getWriter(); 

      Session session = HibernateUtil.getSessionFactory().openSession(); 
      Transaction tx = session.beginTransaction(); 
      Person person = new Person();
      person.setName("Person-1");
   
      Address address = new Address();
      address.setCity("Atlanta");
 
      person.setAddress(address);
      address.setPerson(person);
   
      session.save(person); 
   
      tx.commit(); 
      session.close(); 

      Session newSession = HibernateUtil.getSessionFactory().openSession(); 
      Transaction newTransaction = newSession.beginTransaction(); 
      List<Person> persons = newSession.createQuery("from Person").list(); 
      out.println( persons.size() + " persons found:" ); 
      for ( Iterator<Person> iter = persons.iterator(); iter.hasNext(); ) { 
         Person person1 = iter.next(); 
         out.println( person1.getName()); 
      } 
   
      newTransaction.commit(); 
      newSession.close(); 
   } 
}


5) Configure the servlet in the web.xml file,

<servlet>
   <servlet-name>PersonAddress</servlet-name>
   <servlet-class>info.icontraining.servlets.PersonAddress</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>PersonAddress</servlet-name>
   <url-pattern>/personAddress</url-pattern>
</servlet-mapping>


6) Enter the following URL in the browser to test,

http://localhost:8080/WebAppName/personAddress

May 7, 2011

Hibernate Entity Mapping: Many-to-one and One-to-many relationship

Map a one-to-many/many-to-one association in the object model. There are 2 entity type classes - Team and Player. A Team object can have many Player objects but a Player object can have a reference to only one Team object. Map, persist and load this association.

Properties of Team class: teamId, teamName, players
Properties of Player class: playerId, playerName, team

1) Create the persistent classes for the Team and Player entities,

Team.java

package info.icontraining.hibernate;

import java.util.*;

public class Team {

   private Set<Player> players = new HashSet<Player>();
   private String teamName;
   private Long teamId;
 
   public Set<Player> getPlayers() {
      return players;
   }
   public void setPlayers(Set<Player> players) {
      this.players = players;
   }
   public String getTeamName() {
      return teamName;
   }
   public void setTeamName(String teamName) {
      this.teamName = teamName;
   }
   public Long getTeamId() {
      return teamId;
   }
   public void setTeamId(Long teamId) {
      this.teamId = teamId;
   }
}


Player.java

package info.icontraining.hibernate;

public class Player {
 
   private Team team;
   private Long playerId;
   private String playerName;
 
   public Team getTeam() {
      return team;
   }
   public void setTeam(Team team) {
      this.team = team;
   }
   public Long getPlayerId() {
      return playerId;
   }
   public void setPlayerId(Long playerId) {
      this.playerId = playerId;
   }
   public String getPlayerName() {
      return playerName;
   }
   public void setPlayerName(String playerName) {
      this.playerName = playerName;
   }
}


2) Create the mapping files,

Team.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.Team" table="TEAM_TABLE"> 
      <id name="teamId" column="TEAM_ID"> 
         <generator class="native" /> 
      </id> 
      <property name="teamName" column="TEAM_NAME" type="string" />
      <set name="players" inverse="true" cascade="save-update,delete">
        <key column="TEAM_ID" />
        <one-to-many class="info.icontraining.hibernate.Player" />
      </set>  
   </class> 
</hibernate-mapping>


Player.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.Player" table="PLAYER_TABLE"> 
      <id name="playerId" column="PLAYER_ID"> 
         <generator class="native" /> 
      </id> 
      <property name="playerName" column="PLAYER_NAME" type="string" />
      <many-to-one name="team" column="TEAM_ID" class="info.icontraining.hibernate.Team" not-null="true" />  
   </class> 
</hibernate-mapping>


3) In the hibernate.cfg.xml file, add the following configuration,

<mapping resource="info/icontraining/hibernate/Team.hbm.xml" />
<mapping resource="info/icontraining/hibernate/Player.hbm.xml" />


4) Create the client code in a servlet, as follows,

package info.icontraining.servlets;

import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.* ; 
import org.hibernate.*; 
import info.icontraining.hibernate.*;

public class TeamPlayer extends HttpServlet { 
  
   public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{ 
  
      PrintWriter out = res.getWriter(); 

      Session session = HibernateUtil.getSessionFactory().openSession(); 
      Transaction tx = session.beginTransaction(); 
      Team team = new Team();
      team.setTeamName("My Team");
   
      Player player1 = new Player();
      Player player2 = new Player();
   
      player1.setPlayerName("P1");
      player2.setPlayerName("P2");
      player1.setTeam(team);
      player2.setTeam(team);
   
      team.getPlayers().add(player1);
      team.getPlayers().add(player2);
   
      session.save(team); 
   
      tx.commit(); 
      session.close(); 

      Session newSession = HibernateUtil.getSessionFactory().openSession(); 
      Transaction newTransaction = newSession.beginTransaction(); 
      List<Player> players = newSession.createQuery("from Player").list(); 
      out.println( players.size() + " players found:" ); 
      for ( Iterator<Player> iter = players.iterator(); iter.hasNext(); ) { 
         Player player = iter.next(); 
         out.println( player.getPlayerName() ); 
      } 
   
      newTransaction.commit(); 
      newSession.close(); 
   } 
}


5) Configure the servlet in the web.xml file,

<servlet>
   <servlet-name>TeamPlayer</servlet-name>
   <servlet-class>info.icontraining.servlets.TeamPlayer</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>TeamPlayer</servlet-name>
   <url-pattern>/teamPlayer</url-pattern>
</servlet-mapping>


6) Enter the following URL in the browser to test,

http://localhost:8080/WebAppName/teamPlayer

Hibernate Inheritance Mapping (Strategy 4) - Table per subclass

In strategy-4, each persistent class in the inheritance hierarchy, whether concrete or abstract, is mapped to a table each in the Database schema. The inheritance relationship between the domain classes is reflected in the mapping files through special XML elements and in the Database schema as relationship foreign-key associations between the tables.

1) Create the persistent classes inheritance hierarchy with S4 as the superclass and A4 and B4 as the subclasses that extend from the superclass.

S4.java

package info.icontraining.hibernate;

public abstract class S4 {

   private Long id;
   private String p1;
   private String p2;
 
   public Long getId() {
      return id;
   }
   public void setId(Long id) {
      this.id = id;
   } 
   public String getP1() {
      return p1;
   }
   public void setP1(String p1) {
      this.p1 = p1;
   }
   public String getP2() {
      return p2;
   }
   public void setP2(String p2) {
      this.p2 = p2;
   }
}


A4.java

package info.icontraining.hibernate;

public class A4 extends S4 {

   private String p3;
   private String p4;
 
   public A4() { }
 
   public A4(String p1, String p2, String p3, String p4) {
      this.setP1(p1);
      this.setP2(p2);
      this.setP3(p3);
      this.setP4(p4);
   }
 
   public String getP3() {
      return p3;
   }
   public void setP3(String p3) {
      this.p3 = p3;
   }
   public String getP4() {
      return p4;
   }
   public void setP4(String p4) {
      this.p4 = p4;
   }
}


B4.java

package info.icontraining.hibernate;

public class B4 extends S4 {

   private String p5;
   private String p6;
 
   public B4() { }
 
   public B4(String p1, String p2, String p5, String p6) {
      this.setP1(p1);
      this.setP2(p2);
      this.setP5(p5);
      this.setP6(p6);
   }
 
   public String getP5() {
      return p5;
   }
   public void setP5(String p5) {
      this.p5 = p5;
   }
   public String getP6() {
      return p6;
   }
   public void setP6(String p6) {
      this.p6 = p6;
   }
}


2) Create the mapping file, AB4.hbm.xml,

AB4.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.S4" table="S4_TABLE" > 
      <id name="id" column="ID" type="long" >
         <generator class="native" /> 
      </id> 
      <property name="p1" column="P1" type="string" />
      <property name="p2" column="P2" type="string" />
      <joined-subclass name="info.icontraining.hibernate.A4" table="A4_TABLE">
         <key column="A4_ID"/>
         <property name="p3" column="P3" type="string" />
         <property name="p4" column="P4" type="string" />
      </joined-subclass>
      <joined-subclass name="info.icontraining.hibernate.B4" table="B4_TABLE">
         <key column="B4_ID" />
         <property name="p5" column="P5" type="string" />
         <property name="p6" column="P6" type="string" />
      </joined-subclass>
   </class> 
</hibernate-mapping>


3) In the hibernate.cfg.xml file, add the following configuration,
<mapping resource="info/icontraining/hibernate/AB4.hbm.xml" />


4) Create the client code in a servlet class, as follows,

package info.icontraining.servlets;

import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.* ; 
import org.hibernate.*; 
import info.icontraining.hibernate.*;

public class InheritanceDemo4 extends HttpServlet { 
  
   public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{ 
  
      PrintWriter out = res.getWriter(); 

      Session session = HibernateUtil.getSessionFactory().openSession(); 
      Transaction tx = session.beginTransaction(); 
      A4 a1 = new A4("str1", "str2", "str3", "str4");
      B4 b1 = new B4("str1", "str2", "str5", "str6");
      session.save(a1); 
      session.save(b1);
      tx.commit(); 
      session.close(); 

      Session newSession = HibernateUtil.getSessionFactory().openSession(); 
      Transaction newTransaction = newSession.beginTransaction(); 
      List<S4> a = newSession.createQuery("from S4").list(); 
      out.println( a.size() + " items found:" ); 
      for ( Iterator<S4> iter = a.iterator(); iter.hasNext(); ) { 
         S4 a2 = iter.next(); 
         out.println( a2.getP1() ); 
      } 
   
      newTransaction.commit(); 
      newSession.close(); 
   } 
}


5) Configure the servlet in the web.xml file,

<servlet>
   <servlet-name>InheritanceDemo4</servlet-name>
   <servlet-class>info.icontraining.servlets.InheritanceDemo4</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>InheritanceDemo4</servlet-name>
   <url-pattern>/inheritanceDemo4</url-pattern>
</servlet-mapping>


6) Enter the following URL in the browser to test,

http://localhost:8080/WebAppName/inheritanceDemo4

Hibernate Inheritance Mapping (Strategy 3) - Table per inheritance hierarchy

In strategy-3, the entire inheritance hierarchy is mapped to a single table in the Database Schema. The mapping file reflects the existence of inheritance through special elements in the XML.

1) Create the persistent classes inheritance hierarchy, S3 is the superclass and A3 and B3 are the subclasses that inherit from the superclass.

S3.java

package info.icontraining.hibernate;

public class S3 {

   private Long id;
   private String p1;
   private String p2;
 
   public Long getId() {
      return id;
   }
   public void setId(Long id) {
      this.id = id;
   } 
   public String getP1() {
      return p1;
   }
   public void setP1(String p1) {
      this.p1 = p1;
   }
   public String getP2() {
      return p2;
   }
   public void setP2(String p2) {
      this.p2 = p2;
   } 
}

A3.java

package info.icontraining.hibernate;

public class A3 extends S3 {

   private String p3;
   private String p4;
 
   public A3() { }
 
   public A3(String p1, String p2, String p3, String p4) {
      this.setP1(p1);
      this.setP2(p2);
      this.setP3(p3);
      this.setP4(p4);
   }
 
   public String getP3() {
      return p3;
   }
   public void setP3(String p3) {
      this.p3 = p3;
   }
   public String getP4() {
      return p4;
   }
   public void setP4(String p4) {
      this.p4 = p4;
   } 
}

B3.java

package info.icontraining.hibernate;

public class B3 extends S3 {

   private String p5;
   private String p6;
 
   public B3() { }
 
   public B3(String p1, String p2, String p5, String p6) {
      this.setP1(p1);
      this.setP2(p2);
      this.setP5(p5);
      this.setP6(p6);
   }
 
   public String getP5() {
      return p5;
   }
   public void setP5(String p5) {
      this.p5 = p5;
   }
   public String getP6() {
      return p6;
   }
   public void setP6(String p6) {
      this.p6 = p6;
   }
}

2) Create the mapping file, AB3.hbm.xml

AB3.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.S3" table="SAB3_TABLE" > 
      <id name="id" column="ID" type="long" > 
         <generator class="native" /> 
      </id>
      <discriminator column="DISC_COL" type="string" />
      <property name="p1" column="P1" type="string" />
      <property name="p2" column="P2" type="string" />
      <subclass name="info.icontraining.hibernate.A3" discriminator-value="a3">
         <property name="p3" column="P3" type="string" />
         <property name="p4" column="P4" type="string" />
      </subclass>
      <subclass name="info.icontraining.hibernate.B3" discriminator-value="b3">
         <property name="p5" column="P5" type="string" />
         <property name="p6" column="P6" type="string" />
      </subclass>
   </class> 
</hibernate-mapping> 


3) In the hibernate.cfg.xml file, add the following configuration,

<mapping resource="info/icontraining/hibernate/AB3.hbm.xml" />


4) Create the client code, in a servlet class, as follows,

package info.icontraining.servlets;

import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.* ; 
import org.hibernate.*; 
import info.icontraining.hibernate.*;

public class InheritanceDemo3 extends HttpServlet { 
  
   public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{ 
  
      PrintWriter out = res.getWriter(); 

      Session session = HibernateUtil.getSessionFactory().openSession(); 
      Transaction tx = session.beginTransaction(); 
      A3 a1 = new A3("str1", "str2", "str3", "str4");
      B3 b1 = new B3("str1", "str2", "str5", "str6");
      session.save(a1); 
      session.save(b1);
      tx.commit(); 
      session.close(); 

      Session newSession = HibernateUtil.getSessionFactory().openSession(); 
      Transaction newTransaction = newSession.beginTransaction(); 
      List<A3> a = newSession.createQuery("from A3").list(); 
      out.println( a.size() + " items found:" ); 
      for ( Iterator<A3> iter = a.iterator(); iter.hasNext(); ) { 
         A3 a2 = iter.next(); 
         out.println( a2.getP1() ); 
      } 
   
      out.println();
      out.println();
   
      List<B3> b = newSession.createQuery("from B3").list(); 
      out.println( b.size() + " items found:" ); 
      for ( Iterator<B3> iter = b.iterator(); iter.hasNext(); ) { 
         B3 b2 = iter.next(); 
         out.println( b2.getP2() ); 
      } 
   
      newTransaction.commit(); 
      newSession.close(); 
   }  
}


5) Configure the servlet in the web.xml file,

<servlet>
   <servlet-name>InheritanceDemo3</servlet-name>
   <servlet-class>info.icontraining.servlets.InheritanceDemo3</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>InheritanceDemo3</servlet-name>
   <url-pattern>/inheritanceDemo3</url-pattern>
</servlet-mapping>


6) Enter the following URL in the browser to test,

http://localhost:8080/WebAppName/inheritanceDemo3

Hibernate Inheritance Mapping (Strategy 2) - Table per concrete class with unions

In strategy-2, the concrete persistent classes in the inheritance hierarchy are mapped to a table each in the Database schema. The abstract classes are not mapped. The mapping file reflects the inheritance in the domain classes by using explicit elements in the XML.

1) Create the 3 persistent classes, S2.java is the abstract superclass, and A2 and B2 are concrete subclasses that extend from the superclass.

S2.java

package info.icontraining.hibernate;

public abstract class S2 {

   private Long id;
   private String p1;
   private String p2;
 
   public Long getId() {
      return id;
   }
   public void setId(Long id) {
      this.id = id;
   } 
   public String getP1() {
      return p1;
   }
   public void setP1(String p1) {
      this.p1 = p1;
   }
   public String getP2() {
      return p2;
   }
   public void setP2(String p2) {
      this.p2 = p2;
   } 
}

A2.java

package info.icontraining.hibernate;

public class A2 extends S2 {

   private String p3;
   private String p4;
 
   public A2() { }
 
   public A2(String p1, String p2, String p3, String p4) {
      this.setP1(p1);
      this.setP2(p2);
      this.setP3(p3);
      this.setP4(p4);
   }
 
   public String getP3() {
      return p3;
   }
   public void setP3(String p3) {
      this.p3 = p3;
   }
   public String getP4() {
      return p4;
   }
   public void setP4(String p4) {
      this.p4 = p4;
   } 
}


B2.java

package info.icontraining.hibernate;

public class B2 extends S2 {

   private String p5;
   private String p6;
 
   public B2() { }
 
   public B2(String p1, String p2, String p5, String p6) {
      this.setP1(p1);
      this.setP2(p2);
      this.setP5(p5);
      this.setP6(p6);
   }
 
   public String getP5() {
      return p5;
   }
   public void setP5(String p5) {
      this.p5 = p5;
   }
   public String getP6() {
      return p6;
   }
   public void setP6(String p6) {
      this.p6 = p6;
   }
}


2) Create the mapping file AB2.xml,

AB2.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.S2" abstract="true" > 
      <id name="id" column="ID" type="long" > 
         <generator class="native" /> 
      </id> 
      <property name="p1" column="P1" type="string" />
      <property name="p2" column="P2" type="string" />
      <union-subclass name="info.icontraining.hibernate.A2" table="A2_TABLE">
         <property name="p3" column="P3" type="string" />
         <property name="p4" column="P4" type="string" />
      </union-subclass>
      <union-subclass name="info.icontraining.hibernate.B2" table="B2_TABLE">
         <property name="p5" column="P5" type="string" />
         <property name="p6" column="P6" type="string" />
      </union-subclass>
   </class> 
</hibernate-mapping>


3) In the hibernate.cfg.xml, add the following configuration,

<mapping resource="info/icontraining/hibernate/AB2.hbm.xml" /> 

4) Create the client code, in a servlet class, as follows,

package info.icontraining.servlets;

import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.* ; 
import org.hibernate.*; 
import info.icontraining.hibernate.*;

public class InheritanceDemo2 extends HttpServlet { 
  
   public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{ 
  
      PrintWriter out = res.getWriter(); 

      Session session = HibernateUtil.getSessionFactory().openSession(); 
      Transaction tx = session.beginTransaction(); 
      A2 a1 = new A2("str1", "str2", "str3", "str4");
      B2 b1 = new B2("str1", "str2", "str5", "str6");
      session.save(a1); 
      session.save(b1);
      tx.commit(); 
      session.close(); 

      Session newSession = HibernateUtil.getSessionFactory().openSession(); 
      Transaction newTransaction = newSession.beginTransaction(); 
      List<S2> a = newSession.createQuery("from S2").list(); 
      out.println( a.size() + " items found:" ); 
      for ( Iterator<S2> iter = a.iterator(); iter.hasNext(); ) { 
         S2 a2 = iter.next(); 
         out.println( a2.getP1() ); 
      } 
   
      newTransaction.commit(); 
      newSession.close(); 
   } 
}


5) Configure the servlet in the web.xml file,

<servlet>
   <servlet-name>InheritanceDemo2</servlet-name>
   <servlet-class>info.icontraining.servlets.InheritanceDemo2</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>InheritanceDemo2</servlet-name>
   <url-pattern>/inheritanceDemo2</url-pattern>
</servlet-mapping>


6) Enter the following URL in the browser to test the example,

http://localhost:8080/WebAppName/inheritanceDemo2

Hibernate Inheritance Mapping (Strategy 1) - Table per concrete class with implicit polymorphism

In strategy-1, we map only the concrete persistent classes in the inheritance hierarchy to a table each in the Database Schema. The abstract classes are not mapped. Neither the mapping files nor the Database schema reflect that inheritance exists in the domain classes, making it implicit polymorphism.

1) Create the 3 persistent classes, where the super class, S, is an abstract class and the two sub-classes that extend from the superclass, A and B, are concrete classes.

S.java

package info.icontraining.hibernate;

public abstract class S {

   private Long id;
   private String p1;
   private String p2;
 
   public Long getId() {
      return id;
   }
   public void setId(Long id) {
      this.id = id;
   } 
   public String getP1() {
      return p1;
   }
   public void setP1(String p1) {
      this.p1 = p1;
   }
   public String getP2() {
      return p2;
   }
   public void setP2(String p2) {
      this.p2 = p2;
   }
}

A.java

package info.icontraining.hibernate;

public class A extends S {

   private String p3;
   private String p4;
 
   public A() { }
 
   public A(String p1, String p2, String p3, String p4) {
      this.setP1(p1);
      this.setP2(p2);
      this.setP3(p3);
      this.setP4(p4);
   }
 
   public String getP3() {
      return p3;
   }
   public void setP3(String p3) {
      this.p3 = p3;
   }
   public String getP4() {
      return p4;
   }
   public void setP4(String p4) {
      this.p4 = p4;
   }
}

B.java

package info.icontraining.hibernate;

public class B extends S {

   private String p5;
   private String p6;
 
   public B() { }
 
   public B(String p1, String p2, String p5, String p6) {
      this.setP1(p1);
      this.setP2(p2);
      this.setP5(p5);
      this.setP6(p6);
   }
 
   public String getP5() {
      return p5;
   }
   public void setP5(String p5) {
      this.p5 = p5;
   }
   public String getP6() {
      return p6;
   }
   public void setP6(String p6) {
      this.p6 = p6;
   }
}


2) The 2 mapping files for the concrete classes, A and B, will be mapped normally.

A.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.A" table="A1"> 
      <id name="id" column="ID"> 
         <generator class="native" /> 
      </id> 
      <property name="p1" column="P1" type="string" />
      <property name="p2" column="P2" type="string" />
      <property name="p3" column="P3" type="string" />
      <property name="p4" column="P4" type="string" />  
   </class> 
</hibernate-mapping>


B.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.B" table="B1"> 
      <id name="id" column="ID"> 
         <generator class="native" /> 
      </id> 
      <property name="p1" column="P1" type="string" />
      <property name="p2" column="P2" type="string" />
      <property name="p5" column="P5" type="string" />
      <property name="p6" column="P6" type="string" />  
   </class> 
</hibernate-mapping> 


3) In the hibernate.cfg.xml file, add the following configuration,

<mapping resource="info/icontraining/hibernate/A1.hbm.xml" /> 
<mapping resource="info/icontraining/hibernate/B1.hbm.xml" /> 


4) Create the client code, in a servlet class, as follows,

package info.icontraining.servlets;

import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.* ; 
import org.hibernate.*; 
import info.icontraining.hibernate.*;

public class InheritanceDemo1 extends HttpServlet { 
  
   public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { 
  
      PrintWriter out = res.getWriter(); 

      Session session = HibernateUtil.getSessionFactory().openSession(); 
      Transaction tx = session.beginTransaction(); 
      A a1 = new A("str1", "str2", "str3", "str4");
      B b1 = new B("str1", "str2", "str5", "str6");
      session.save(a1); 
      session.save(b1);
      tx.commit(); 
      session.close(); 

      Session newSession = HibernateUtil.getSessionFactory().openSession(); 
      Transaction newTransaction = newSession.beginTransaction(); 
      List<A> a = newSession.createQuery("from A").list(); 
      out.println( a.size() + " items found:" ); 
      for ( Iterator<A> iter = a.iterator(); iter.hasNext(); ) { 
         A a2 = iter.next(); 
         out.println( a2.getP1() ); 
      } 
   
      out.println();
      out.println();
   
      List<B> b = newSession.createQuery("from B").list(); 
      out.println( b.size() + " items found:" ); 
      for ( Iterator<B> iter = b.iterator(); iter.hasNext(); ) { 
         B b2 = iter.next(); 
         out.println( b2.getP2() ); 
      } 
   
      newTransaction.commit(); 
      newSession.close(); 
   } 
}


5) Configure the servlet in the web.xml file,

<servlet>
   <servlet-name>InheritanceDemo1</servlet-name>
   <servlet-class>info.icontraining.servlets.InheritanceDemo1</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>InheritanceDemo1</servlet-name>
   <url-pattern>/inheritanceDemo1</url-pattern>
</servlet-mapping>

6) Enter the following URL in the browser to test,

http://localhost:8080/WebAppName/inheritanceDemo1

April 14, 2011

Mapping Entity and Value types in Hibernate

Create a User Entity type persistent class and an Address Value type persistent class. Create the User.hbm.xml mapping file for the Entity type. Add the mapping for the value type in the User.hbm.xml.
Persist an object of type User.
Retrieve the same object and print a property from the Address value type.

1) Create the User.java persistent class of type entity in the src folder of the web application. The class will have a property of type Address which is a persistent class of value type.


package info.icontraining.hibernate;

public class User {
 
   private Long id;
   private String name;
   private HomeAddress address;
 
   public String getName() {
       return name;
   }
   public void setName(String name) {
       this.name = name;
   }
   public HomeAddress getAddress() {
       return address;
   }
   public void setAddress(HomeAddress address) {
       this.address = address;
   }
   public Long getId() {
       return id;
   }
   public void setId(Long id) {
       this.id = id;
   }
}

2) Create the HomeAddress.java persistent class of type value in the src folder of the web application.

package info.icontraining.hibernate;

public class HomeAddress {

   private String street;
   private String city;
   private String zipCode;
   private User user;
 
   public String getStreet() {
       return street;
   }
   public void setStreet(String street) {
       this.street = street;
   }
   public String getCity() {
       return city;
   }
   public void setCity(String city) {
       this.city = city;
   }
   public String getZipCode() {
       return zipCode;
   }
   public void setZipCode(String zipCode) {
       this.zipCode = zipCode;
   }
   public User getUser() {
       return user;
   }
   public void setUser(User user) {
       this.user = user;
   } 
}


3) Create the User.hbm.xml mapping file in the same folder/package as the User.java class - this file will contain the mapping information for the entity and the value types

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.User" table="USER_TABLE"> 
      <id name="id" column="USER_ID"> 
         <generator class="native" /> 
      </id> 
      <property name="name" column="USER_NAME" /> 
      <component name="address" class="info.icontraining.hibernate.HomeAddress">
         <parent name="user" />
         <property name="street" column="STREET" />
         <property name="city" column="CITY" />
         <property name="zipCode" column="ZIPCODE" />
      </component> 
   </class> 
</hibernate-mapping> 


4) Modify the hibernate.cfg.xml file in the WebContent/WEB-INF folder to add the User.hbm.xml as a mapping resource,

<mapping resource="info/icontraining/hibernate/User.hbm.xml" /> 


5) Create a UserServlet.java class to execute the code to save a User object.

package info.icontraining.servlets;

import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.* ; 
import org.hibernate.*; 
import info.icontraining.hibernate.*;

public class UserServlet extends HttpServlet { 
  
   public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{ 
  
      PrintWriter out = res.getWriter(); 

      Session session = HibernateUtil.getSessionFactory().openSession(); 
      Transaction tx = session.beginTransaction(); 
  
      User user = new User();
      user.setName("Dinesh");
  
      HomeAddress address = new HomeAddress();
      address.setCity("Mumbai");
      address.setStreet("Worli");
      address.setZipCode("400040");
      address.setUser(user);
      user.setAddress(address);
  
      session.save(user); 
      tx.commit(); 
      session.close(); 

      Session newSession = HibernateUtil.getSessionFactory().openSession(); 
      Transaction newTransaction = newSession.beginTransaction(); 
  
      List users = newSession.createQuery("from User as u").list(); 
      out.println( users.size() + " user/s found" ); 
  
      for ( Iterator iter = users.iterator(); iter.hasNext(); ) { 
         User user2 = iter.next(); 
         out.println( user2.getName() +": " + user2.getAddress().getCity());   
      }

      newTransaction.commit(); 
      newSession.close(); 
   } 
}


6) Configure the UserServlet.java in the web.xml file,

<servlet>
   <servlet-name>UserServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>UserServlet</servlet-name>
   <url-pattern>/userServlet.hibernate</url-pattern>
</servlet-mapping>


7) Test the code by typing the following URL in the browser,

http://localhost:8080/WebAppName/userServlet.hibernate

Hibernate 3.0 - Hello World Example

0) Download Oracle Express 10g Express Edition and setup according to instructions on this link.
Copy the Oracle JDBC jar into the lib folder of the web application.

1) Download the hibernate_jars.zip from this link, unzip and paste the jar files into the WebContent/WEB-INF/lib folder of the web application

2) Create the persistent class, Message.java in the src folder of the web application

package info.icontraining.hibernate;
public class Message { 
  
   private Long id; 
   private String text; 
   private Message nextMessage; 
  
   private Message() {} 
     
   public Message(String text) { 
      this.text = text; 
   } 
   public Long getId() { 
      return id; 
   } 
   private void setId(Long id) { 
      this.id = id; 
   } 
   public String getText() { 
      return text; 
   } 
   public void setText(String text) { 
      this.text = text; 
   } 
   public Message getNextMessage() { 
      return nextMessage; 
   } 
   public void setNextMessage(Message nextMessage) { 
      this.nextMessage = nextMessage; 
   }   
} 


3) Create the Message.hbm.xml file in the same folder (package) as the Message.java class - this is the hibernate mapping file for the persistent class Message.java.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 
<hibernate-mapping> 
   <class name="info.icontraining.hibernate.Message" table="MESSAGES"> 
      <id name="id" column="MESSAGE_ID"> 
         <generator class="native"/> 
      </id> 
      <property name="text" column="MESSAGE_TEXT"/> 
      <many-to-one name="nextMessage" cascade="all" column="NEXT_MESSAGE_ID"/> 
   </class> 
</hibernate-mapping>


4) Create the hibernate.cfg.xml file in the WebContent/WEB-INF folder - this file holds the Hibernate configuration. Make sure that the username, password, the database connection string and the JDBC driver class name in this file are appropriate for your database installation.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC 
"-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration> 

<session-factory>  
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</property> 
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property> 
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property> 
<property name="hibernate.connection.username">system</property> 
<property name="hibernate.connection.password">system</property> 
<property name="show_sql">true</property> 
<property name="hibernate.use_sql_comments">true</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> 
<property name="hibernate.hbm2ddl.auto">create</property> 
<property name="hibernate.current_session_context_class">thread</property> 
<property name="hibernate.generate_statistics">true</property> 
<property name="hibernate.format_sql">true</property> 

<!-- Mapping files --> 
<mapping resource="info/icontraining/hibernate/Message.hbm.xml" /> 

</session-factory>
  
</hibernate-configuration>  


5) Create a HibernateUtil.java utility class in the src folder of the web application. This class abstracts the loading of the Hibernate configuration and procuring the SessionFactory object

package info.icontraining.hibernate;

import org.hibernate.*; 
import org.hibernate.cfg.*; 

public class HibernateUtil { 

   private static SessionFactory sessionFactory; 

   static { 
      try { 
         sessionFactory = new Configuration().configure("/WEB-INF/hibernate.cfg.xml").buildSessionFactory(); 
      } catch (Throwable ex) { 
         ex.printStackTrace(); 
      } 
   } 

   public static SessionFactory getSessionFactory() { 
      return sessionFactory; 
   } 
   public static void shutdown() { 
      getSessionFactory().close(); 
   } 
} 


6) Create the MessageServlet.java servlet class in the src folder of the web application. This class contains code to persist/retrieve the persistent objects.

package info.icontraining.servlets;

import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.* ; 
import org.hibernate.*; 
import info.icontraining.hibernate.*;

public class MessageServlet extends HttpServlet { 
  
   public void doGet(HttpServletRequest req, HttpServletResponse res) 
                        throws IOException, ServletException{ 
  
      PrintWriter out = res.getWriter(); 

      Session session = HibernateUtil.getSessionFactory().openSession(); 
      Transaction tx = session.beginTransaction(); 
      Message message1 = new Message("Hello World"); 
      session.save(message1); 
      tx.commit(); 
      session.close(); 

      Session newSession = HibernateUtil.getSessionFactory().openSession(); 
      Transaction newTransaction = newSession.beginTransaction(); 
      List messages = newSession.createQuery("from Message as m order by m.text asc").list(); 
      out.println( messages.size() + " message(s) found:" ); 

      for (Iterator iter = messages.iterator(); iter.hasNext(); ) { 
         Message message2 = iter.next(); 
         out.println( message2.getText() ); 
      }

      newTransaction.commit(); 
      newSession.close();  
   } 
}


7) Configure the servlet class in the web.xml file

<servlet>
   <servlet-name>MessageServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.MessageServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>MessageServlet</servlet-name>
   <url-pattern>/messageServlet.hibernate</url-pattern>
</servlet-mapping>


8) Test the code by typing the following URL in the browser,

http://localhost:8080/WebAppName/messageServlet.hibernate