24
Sep
10

Hibernate – HelloWorld

This a my first hibernate Program.After going through the hibernate documentation from http://www.hibernate.org/docs.html i  have started trying this program and faced a couple of issues before make it to run successfully. Hope this will help you. 

  SoftWare Used  

1. Eclipse 3.2
2. Razorsql (http://www.razorsql.com/)
3 HsqlDB (http://hsqldb.org/)
4 JDK 1.6
5 ant   

 The following jar are requied to run the appication  

1.hibernate3.jar
2.antlr-2.7.6.jar
3.javassist-3.9.0.GA.jar
4.jta-1.1.jar
5.dom4j-1.6.1.jar
6.commons-collections-3.1.jar
7.slf4j-api-1.5.8.jar
8.slf4j-simple-1.5.2.jar
9.hsqldb.jar   

Most of the jars will be available in hibernate binary distribution, remaining can be downloaded from findjar.com 

Below are the steps to develop and run the hibernate hsql Application    

 Create the directory structure and source files as shown below    

Directory Structure

JAVA SOURCE FILES 

User.java 

package com.upog.demo;
import java.util.Date;
public class User {
 private int id;
 private String name;
 private Date date;
 public User() {} 

 public int getId() {
 return id;
 }
 private void setId(int id) {
 this.id = id;
 }
 
 public Date getDate() {
 return date;
 }
 public void setDate(Date date) {
 this.date = date;
 }
 
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }

HibernateUtil.java 

package com.upog.demo; 

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; 

public class HibernateUtil {
 private static final SessionFactory sessionFactory = buildSessionFactory();
 private static SessionFactory buildSessionFactory()
 {
  try
  {
   return new Configuration().configure().buildSessionFactory();
  }
  catch (Exception e)
  {
   System.out.println(” SessionFactory creation failed” + e);
   throw new ExceptionInInitializerError(e);
  }
 }
 public static SessionFactory getSessionFactory()
 {
  return sessionFactory;
 }

HibernateTest.java  

package com.upog.demo; 

import java.util.Date;
import java.util.Iterator;
import java.util.List; 

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction; 

public class HibernateTest {
       
        public static void RetrieveUser()
          {
              System.out.println(“Retrieving User list from USER_INFO ….”);
              Session session = HibernateUtil.getSessionFactory().openSession(); 

                  List UserList = session.createQuery(“from User”).list();
                  for (Iterator iterator = UserList.iterator(); iterator.hasNext();)
                  {
                      User user = (User) iterator.next();
                      System.out.println(user.getName() + “\t ” + user.getId() + “\t ” + user.getDate());
                  }
                  session.close();
 
          }
         
        public static void  saveUser( String title)
         {
             Session session = HibernateUtil.getSessionFactory().openSession();  
                 User user = new User();
                 user.setName(title);
                 user.setDate(new Date());
                 System.out.println(“\n Saving user ” + user.getName());
                 session.save(user);
                 session.flush();
                 session.close(); 
         }
       
        public static void main (String args[])
        {
             saveUser(“abc”);
             saveUser(“def”);
             saveUser(“Hi”);
             saveUser(“hello”);
             RetrieveUser(); 

        } 

Hibernate Configuration Files
Hibernate.cfg.xml  –  Contains the information about the database like URL,diver,ID,Password etc
  Note: Change the value of connection.url as per you project home (I have given absolute path)
  
 <!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>org.hsqldb.jdbcDriver</property>
        <property>jdbc:hsqldb:file:D:\data\workspace\Hibernate\database\mydb;shutdown=true</property> 
        <property>sa</property>
        <property> </property> 

        <property>2</property>
        <property>org.hibernate.dialect.HSQLDialect</property>
        <property>true</property>
        <property>update</property>
        <property>thread</property>
        <mapping resource=”hibernate.hbm.xml”/>
 </session-factory>
</hibernate-configuration> 

Hibernate.hbm.xml  – Defines the mapping between the Java Object and database table
  
  <?xml version=”1.0″?>
  <!DOCTYPE hibernate-mapping PUBLIC
  “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
  “http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd“>
  <hibernate-mapping package=”com.upog.demo”>
   <class table=”USER_INFO”>
    <id column=”USER_ID”>
     <generator/>
    </id>
    <property column=”NAME”/>
    <property column=”CREATED_DATE”/>
   </class> 
  </hibernate-mapping> 

Create USER_INFO table in hsqldb
                1. Connect hsqldb using razor sql with the properties as given below. 

                 Login                      : sa
                 Password              :
                 Driver class          : org.hsqldb.jdbcDriver
                 Driver location   :${PROJECT_HOME}\lib\hsqldb.jar
                 JDBC URL              :jdbc:hsqldb:file:${PROJECT_HOME}\database\mydb;shutdown=true
                2. Execute the following command
                        CREATE MEMORY TABLE PUBLIC.USER_INFO(ID INTEGER DEFAULT 0 NOT NULL PRIMARY KEY,NAME VARCHAR(25),CREATED_DATE DATE)
                3. close the connection
Build.xml 

<?xml version = “1.0” encoding = “UTF-8″?>
<project name = “Hibernate” default = “run” basedir = “.”> 

        <property file=”${basedir}/project.properties”/>
        <property file=”${basedir}/log4j.properties”/>
        <property  value=”hibernate” />
        <property   value=”${basedir}/src”/>
        <property      value=”${basedir}/lib” />
        <property    value=”${basedir}/build”/>
        <property  value=”hibernate” />
        

        <path>
         <pathelement path=”${lib}/hibernate3.jar”/>
         <pathelement path=”${lib}/antlr-2.7.6.jar”/>
         <pathelement path=”${lib}/javassist-3.9.0.GA.jar”/>
         <pathelement path=”${lib}/jta-1.1.jar”/>
         <pathelement path=”${lib}/dom4j-1.6.1.jar”/>
         <pathelement path=”${lib}/commons-collections-3.1.jar”/>
         <pathelement path=”${lib}/slf4j-api-1.5.8.jar” />
         <pathelement path=”${lib}/slf4j-simple-1.5.2.jar” />
         <pathelement path=”${lib}/hsqldb.jar” />  
        </path>        
       
        <target>
                <delete dir=”${build}”/>
        </target> 

        <target depends=”clean”>
                <mkdir dir=”${build}”/>
        </target>
       
        <target depends=”mkdir” >
              <javac srcdir=”${source}”  destdir=”${build}”  includes=”com/**/*.java”>
                  <classpath refid=”dependencies”/>
              </javac>
        </target>
 
  <target name = “buildJar” depends=”compile”>
   <copy todir=”${build}”>
    <fileset dir=”${source}” includes = “*.xml, *.properties”/>
   </copy>
   <jar jarfile = “${build}/${jarname}.jar” basedir = “${build}”  />    
  </target>
       
  <target depends=”buildJar”>
   <java  classname=”com.upog.demo.HibernateTest” >
    <classpath >      
       <pathelement location=”${build}/${jarname}.jar”/> 
    </classpath >      
    <classpath refid=”dependencies”/>
    </java>               
  </target>   
 
</project> 

Right click on the build.xml file in eclipse Then Click on Run As – > Ant Buid. 

Let me know your comments 

About these ads

3 Responses to “Hibernate – HelloWorld”


  1. 1 Anonymous
    September 28, 2010 at 12:49 pm

    Simple Example

  2. 2 vasantha
    January 18, 2011 at 5:40 am

    Hi,
    with the same example i want in maven build tool.

  3. 3 sreekanth
    December 11, 2011 at 12:24 pm

    Dear sir,
    I an new to Hibernate3 can you plase suggest how to configure hibernate3 and struts2.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: