April 14, 2011

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

No comments:

Post a Comment