Skip to main content

Hibernate 3 with Eclipse helios (Eclipse 3.6)

There are many blogs and tutorials on this topic. However I faced many problems while integrating Hibernate 3.0 with Eclipse Helios. Most of the problems were related to the version mismatch among the components used to create a Hibernate project on Eclipse Helios.
Software Requirements:
1.       Eclipse Helios (This tutorial could work with other versions of Eclipse but it is specially designed for Helios version.)
2.       hibernate-distribution-3.6.5.Final-dist bundle (zip file). Download the bundle from http://www.hibernate.org/downloads. It will be around 59.2 MB jar file.
3.       MySql connector for Eclipse “mysql-connector-java-5.0.8 (zip)”.
4.       slf4j-1.6.1 bundle (zip form)
5.       apache-log4j-1.2.16 bundle(zip form)
6.       commons-logging-1.1.1.jar
Pre-Requisites:
1.       In MySql create a database named “db2”.
2.       Under database db2 create a table named “employee” with following attributes.
CREATE TABLE employee (
                id VARCHAR(10),
                name VARCHAR(20)
);
Note:  The process to connect a MySql table to java code will be described next tutorial.
3.       Add Hibernate perspective to eclipse helios.
Structure of Hibernate Distribution:
        After downloading Hibernate unzip the zip file. Verify following is the file structure you get.


Creating a Hibernate Project in Eclipse Helios:
1. Open Eclipse Helios and select "File | New | Java Project".



2. Name the project as "HibernateTest" (or any other name of your choice). And leave other fields as default.


Now click “Next” then “finish”.

3.       Project opens in Project Explorer

4.       Now we need to add the necessary jar files to the project. For this Right Click on the Project on the Project Explorer and select “Build Path | Configure Build Path” from the context menu.


5.       On the build path window select “Libraries” tab. Then click “Add External Jars” button.


6.  Now add following jars to the project’s build path:
i.  Following jars present under “hibernate-distribution-3.6.5.Final-dist (zip file) “ :
a.       hibernate3.jar
b.      hibernate-testing.jar
ii.  Following files present under “hibernate-distribution-3.6.5.Final-dist (zip file)/lib/required” :
a.       antlr-2.7.6.jar
b.      commons-collections-3.1.jar
c.       dom4j-1.6.1.jar
d.      javassist-3.12.0.GA.jar
e.      jta-1.1.jar
f.        slf4j-api-1.6.1.jar
iii.   Following jars present under “slf4j-1.6.1 (zip file)” :
a.       jul-to-slf4j-1.6.1.jar
b.      log4j-over-slf4j-1.6.1.jar
c.      slf4j-api-1.6.1.jar
d.      slf4j-ext-1.6.1.jar
e.      slf4j-jcl-1.6.1.jar
f.       slf4j-jdk14-1.6.1.jar
g.      slf4j-log4j12-1.6.1.jar
h.      slf4j-migrator-1.6.1.jar
i.       slf4j-nop-1.6.1.jar
j.       slf4j-simple-1.6.1.jar
iv.   Following jars present under “hibernate-distribution-3.6.5.Final-dist (zip file)/lib/jpa” :
a.       hibernate-jpa-2.0-api-1.0.0.Final.jar
v.    Following jars present under “apache-log4j-1.2.16 (zip file)” :
a.       log4j-1.2.16.jar
vi.   Following jars present under “mysql-connector-java-5.0.8 (zip file)” :
a.       mysql-connector-java-5.0.8-bin.jar
vii.  Add “commons-logging-1.1.1.jar” to build path.


7.       After adding all the jars the project structure should look like this:


8.       Now we are done with the addition of jar files. Now the things needed to be done are making classed and xml files. For this first add a package “hibernate.pojo” to “src” folder of project.


9.   Now add a simple Java Bean class “DevTitle.java” to “hibernate.pojo” package and add following code to the class.


10.       Now adding a hibernate mapping file that maps this bean class to a backend MySql Table. For this right click on “DevTitle.java” and select “New | Other | Hibernate | Hibernate XML Mapping File (hbm.xml)”


Click “Next >”

Click “Next >”



Click “Next >”


Click “Finish”

11.       Verify the contents of “DevTitle.hbm.xml” file are as follows:



12.       Now we need to add “hibernate.cfg.xml” file which contains all the configurations related to hibernate


Click “Next >” again click “Next >” then click “Finish”.
13.       Add following code to “hibernate.cfg.xml”

14.       Now we need to add a class that contains a demo code to demonstrate “insertion” and “retrival” of records form out database. For this make a class under “hibernate.pojo” named “HibernateTest.java” and paste following code :
package hibernate.pojo;

import java.util.Iterator;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import hibernate.pojo.DevTitle;

public class HibernateTest {

      /**
       * @param args
       */
      public static void main(String[] args) {
           
            Session session=null;
           
            try
            {
                  //Configuration cfg=new Configuration();
                  //cfg.addClass(hibernate.pojo.DevTitle.class);
                  SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
                  session=sessionFactory.openSession();
                  //SessionFactory sessionFactory=cfg.configure("hibernate.cfg.xml").buildSessionFactory();
                  System.out.println(sessionFactory);
                  session=sessionFactory.openSession();
                  Transaction txn=session.beginTransaction();
                  System.out.println("inserting record...");
                  DevTitle title=new DevTitle();
                  title.setId("3002");
                  title.setName("rajeev");
                  session.save(title);
                  System.out.println("done....");
                  txn.commit();
                  session.flush();
              session.close();
            }catch(Exception exp){exp.printStackTrace();}
            finally{
                     }
           
            try
            {
                  SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
                  session=sessionFactory.openSession();
                  String query1="from DevTitle";
                  Query query=session.createQuery(query1);
                 
                  System.out.println("quering records....");
                  for(Iterator<DevTitle> it=cast(query.iterate()); it.hasNext(); )
                  {
                        DevTitle title=(DevTitle) it.next();
                        System.out.println("ID="+title.getId()+" , name="+title.getName());
                  }
                  session.close();
            }catch(Exception exp){System.out.println(exp.getMessage());}
            finally{}
      }
     
      @SuppressWarnings( "unchecked" )
      private static final <X> X cast(Object o)
      {
            return (X)o;
      }

}

15.              Run the following code as Java Application and if everything is configured properly then following result should get displayed at the console :


Comments

Popular posts from this blog

Uploading a binary file to RESTful web service in java using Jersey

Hi, Recently I had a situation where I was supposed to upload a binary file to a server side RESTful web service created in Jersey. I faced a lot of trouble in doing so because always one or the other part of the hood was not working properly. The following post gives a step by step process as how to create a RESTful service that accepts uploaded binary files. Pre-requisites: 1. A running RESTful service based on Jersey. 2. An HTML page with file upload component. 3. Tomcat 7 as web server. 4. Eclipse indigo. Note: Let us suppose that tomcat is running on same machine on which the HTML client is present. So we will be using the base domain URL as ' http://localhost:8080/ '. If your service and client are located on different instances of tomcat then replace the localhost part of the URL with the IP address of the machine on which the REST service is running. Step 1 (Eclipse setup): a. Create a 'Dynamic Web Project' in eclipse indigo. Let us say that thi

Using R Programming Language inside Java

Hi, This tutorial walks you through using R programming language inside a java program. R is a powerful programming language for Machine Learning and Data Mining. It contains implementation of various Machine Learning algorithms. Recently i had a situation where i was supposed to use these machine learning algorithms inside my java program. I searched the web but the stuff i found was not of much help. Thus i thought of putting the same in the form of this tutorial. This tutorial is not intended to teach you R language. It is only to help you integrate R to Java and then to use R functions inside a Java program. Pre-requisite: Following things are needed to be pre-configured on your system to use R in Java program: 1. R workbench:  R has got a console known as RGui where R commands/programs could be executed. To install RGui simply go to  http://cran.r-project.org/bin/windows/base/  and download the ' Download R 3.0.2 for Windows   (52 megabytes, 32/64 bit) '. Simply

Creating a JAX-WS Web Service and Client using Eclipse Indigo

Creating a JAX-WS Web Service and corresponding client is a very trivial task. However I faced various problems while doing the same mainly while creating a client for the web service. This was mainly because the contents I found on the Internet were in a distributed manner. So I thought of creating a tutorial which binds all the concepts at one place. So this tutorial does not teaches indepth concepts of web services. Instead it guides as how to create a Web Service and a seperate client. Software Requirements: 1. Eclipse Indigo. Note: To download Eclipse Indigo follow the link http://www.eclipse.org/downloads/. Then select 'Eclipse IDE for Java EE Developers'. Process: We will proceed with the creation of web service and client in following two steps: 1. Creating Web Service 2. Creating client to consume web service. 1. Creating Web Service: Creating of a JAX-WS web service is not a very tough task. We simply create a class(normal Java class) and define certai