About Me

My photo
Ernakulam, Kerala, India
I am Sajadh, author of this blog. I run this with loads of passion.
If you are into java, you may find lot of interesting things around ...
Advance thanks for your queries to sajadhaja90@gmail.com.

Thursday, 24 January 2013

Java Technical Programs in Interviews

1) Write a program that accepts 10 student records (roll number and score) and prints them in decreasing
order of scores. In case there are multiple records pertaining to the same student, the program should
choose a single record containing the highest score. The program should be capable of accepting a multi-line
input. Each subsequent line of input will contain a student record, that is, a roll number and a score
(separated by a hyphen). The output should consist of the combination of roll number and corresponding
score in decreasing order of score.

INPUT to program

1001-40
1002-50
1003-60
1002-80
1005-35
1005-55
1007-68
1009-99
1009-10
1004-89

OUTPUT from program

1009-99
1004-89
1002-80
1007-68
1003-60
1005-55
1001-40

Note: In case of input data being supplied to the question, it should be assumed to be a console input.


SOLUTIONS:-

/* Author:- Mohammed Sajadh NA
   Blog:- http://sajadhaja.blogspot.in
 */
/*

package com.sajadhaja.training;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Student {
 int id;
 int score;
     public static void main(String args[]){
        try{
        Scanner in = new Scanner(System.in);
        ArrayList<Student> stud= new ArrayList<Student>();
        int c=0;
        while(c<10){
            String k=in.nextLine();
            StringTokenizer stk =new StringTokenizer(k,"-");
            Student st=new Student();
            st.id=Integer.parseInt(stk.nextToken());
            st.score=Integer.parseInt(stk.nextToken());   
            if(c>1){
                Student stDup=findStudentByid(st.id,stud);
                  if(stDup!=null){
                      if(st.score >stDup.score) {
                          stud.add(st);
                          stud.remove(stDup);
                      }
                  }else{
                    System.out.println("stDup Null"+st.id+" "+st.score);;
                    stud.add(st);
                  }
            }else stud.add(st);           
               c++;
        }   
        Collections.sort (stud, new Comparator<Student>() {
              public int compare(Student o1, Student o2) {
                return o2.score - o1.score;
              }
            });
        for(Student stt:stud){
            System.out.println(">>>>"+stt.id+"   and   "+stt.score);
        }   
    }catch(Exception ex){
        ex.printStackTrace();
    }
    }
    static Student findStudentByid(int id,ArrayList<Student> list){
        for(Student s:list){
            if(s.id==id)
            return s;
        }
        return null;
       }
}


2) Sam wants to select a username in order to register on a website.

The rules for selecting a username are:

1. The minimum length of the username must be 5 characters and the maximum may be 10.
2. It should contain at least one letter from A-Z
3. It should contain at least one digit from 0-9
4. It should contain at least one character from amongst @#*=
5. It should not contain any spaces

Write a program which accepts 4 usernames (one username per line) as input and checks whether each of them satisfy the above mentioned conditions.
If a username satisfies the conditions, the program should print PASS (in uppercase)
If a username fails the conditions, the program should print FAIL (in uppercase)

Suppose the following usernames are supplied to the program:
1234@a
ABC3a#@
1Ac@
ABC 3a#@

Then the output should be:
FAIL
PASS
FAIL
FAIL

IMPORTANT NOTES - READ CAREFULLY:

1. Your solution should assume console input

2. Your solution should contain class name as Main, as the solution will be compiled as Main.java


SOLUTIONS:-


/* Author:- Mohammed Sajadh NA
   Blog:- http://sajadhaja.blogspot.in
*/
package com.sajadhaja.training;

import java.util.Scanner;

public class Pyramid {
    public static void main(String args[]){
        Scanner in=new Scanner(System.in);
        int arr[]=new int[3];
        arr[0]=in.nextInt();
        arr[1]=in.nextInt();
        arr[2]=in.nextInt();
        for(int i=0;i<arr.length;i++){
            int y=arr[i];
            int z=y+1;
            for(int j=1;j<=y;j++){
                System.out.println();
                System.out.format("%"+z+"s","");
                for(int k=1;k<=j;k++){
                    System.out.print(j);
                    System.out.format("%1s","");
                }
                z--;
            }
        }

    }

}



3) Kermit, a frog hops in a particular way such that:

1. He hops 20cm in the first hop, 10cm in the second hop and 5cm in the third hop.
2. After three hops Kermit rests for a while and then again follows the same hopping pattern.

Calculate the total distance travelled by Kermit (in centimeters) for the provided number of hops. Exactly 4 numbers of hops will be provided to the program (one number per line) as per the below example.

Suppose the following number of hops is provided to the program:
4
6
3
5
Then the total distance covered should be displayed as follows:
55
70
35
65


SOLUTIONS:-

/* Author:- Mohammed Sajadh NA
   Blog:- http://sajadhaja.blogspot.in
 */
package com.sajadhaja.training;
import java.util.Scanner;
public class MonkeyHop {

public static void main(String[] args) {
int a,b,c,d;
Scanner in = new Scanner(System.in);
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
d = in.nextInt();
int[] array = {a,b,c,d};
int k = 0;

for(int i=0; i<array.length; i++){
switch(array[i]%3){
case 0: k = 0 + (array[i]/3)*35; break;
case 1: k = 20 + (array[i]/3)*35; break;
case 2: k = 30 + (array[i]/3)*35; break;
case 3: k = 35 + (array[i]/3)*35; break;
}
System.out.println(k);
}
}
}



4) Write a program which will print the below structures according to the input provided to the program. The program should accept 3 inputs in the form of numbers between 1 and 9, both inclusive (one number per line) and then generate the corresponding structures based on the input.

Suppose the following sequence of numbers is supplied to the program:

3
2
4

Then the output should be:

  1
 2 2
3 3 3
 1
2 2
   1
  2 2
 3 3 3
4 4 4 4


IMPORTANT NOTES - READ CAREFULLY:

1. Your solution should assume console input

2. Your solution should contain class name as Main, as the solution will be compiled as Main.java


 SOLUTIONS:-

/* Author:- Mohammed Sajadh NA
   Blog:- http://sajadhaja.blogspot.in
*/
package com.sajadhaja.training;

import java.util.Scanner;

public class Pyramid {
    public static void main(String args[]){
        Scanner in=new Scanner(System.in);
        int arr[]=new int[3];
        arr[0]=in.nextInt();
        arr[1]=in.nextInt();
        arr[2]=in.nextInt();
        for(int i=0;i<arr.length;i++){
            int y=arr[i];
            int z=y+1;
            for(int j=1;j<=y;j++){
                System.out.println();
                System.out.format("%"+z+"s","");
                for(int k=1;k<=j;k++){
                    System.out.print(j);
                    System.out.format("%1s","");
                }
                z--;
            }
        }
    }
}



5) Ross is an event organizer. He has received data regarding the participation of employees in two different events. Some employees have participated in only one event and others have participated in both events. Ross now needs to count the number of employees who have taken part in both events. The records received by Ross consist of employee ids, which are unique. Write a program that accepts the employee ids participating in each event (the first line relates to the first event and the second line relates to the second event). The program should print the number of common employee ids in both the events.

Suppose the following input is given to the program, where each line represents a different event:
1001,1002,1003,1004,1005
1106,1008,1005,1003,1016,1017,1112

Now the common employee ids are 1003 and 1005, so the program should give the output as:
2

IMPORTANT NOTES - READ CAREFULLY:

1. Your solution should assume console input
2. Your solution should contain class name as Main, as the solution will be compiled as Main.java


SOLUTIONS:-

/* Author:- Mohammed Sajadh NA
   Blog:- http://sajadhaja.blogspot.in
*/

package com.sajadhaja.training;

import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Rose {
    public static void main(String args[]){
        Scanner in= new Scanner(System.in);
        String strarr[] = {"",""};
        strarr[0]=in.nextLine();
        strarr[1]=in.nextLine();
        ArrayList<Integer> list[] = new ArrayList[2];
        for(int i=0;i<strarr.length;i++){
            StringTokenizer stk=new StringTokenizer(strarr[i],",");
            list[i]=new ArrayList<Integer>();
            while(stk.hasMoreTokens()){
                list[i].add(Integer.parseInt(stk.nextToken()));
            }
        }
        ArrayList<Integer> listcommon = new ArrayList<Integer>(list[1]);
        listcommon.retainAll(list[0]);
        System.out.println(listcommon.size());
    }
}


6) Write a program which will accept a single pair of strings separated by a comma; the program should calculate the sum of ascii values of the characters of each string. The program should then subtract the sum of the ascii values of the second string from the sum of the ascii values of the first string.

Suppose the following input is given to the program:

123ABC,456DEF

Then the sum of the ascii values of the characters in '123ABC' is 348 and in '456DEF' it is 366. The Difference between these numbers is 348 – 366 = -18
The corresponding output to be printed by the program is:

-18


SOLUTIONS:-

/* Author:- Mohammed Sajadh NA
   Blog:- http://sajadhaja.blogspot.in
*/
package com.sajadhaja.training;

import java.util.Scanner;
public class AsciiOperation {
 public static void main(String[] args) {
  boolean condition = false;

   Scanner scanner = new Scanner(System.in);
   String value = scanner.nextLine();
   condition = value.equalsIgnoreCase("exit");
   if(!condition && value.contains(",")){
    calculate(value);
   }
 }

 private static void calculate(String value){
   final String[] event1 = value.split(",");
   int ss = 0;
   for ( int i = 0; i < event1[0].length(); ++i ) {
          char c = event1[0].charAt( i );
          ss += (int) c;
         }
   int sd = 0;
   for ( int i = 0; i < event1[1].length(); ++i ) {
          char c = event1[1].charAt( i );
          sd += (int) c;
         }
   System.out.println(ss-sd); 
 }
}


7) Write a program which will take the year (yyyy) and the numeric sequence of the month (0-11) as its input. The program will return the day on which the 28th of that particular month and year falls. The input can consist of two year-month combinations, one combination per line.

The numeric sequence of months is as follows:

0 – Jan
1 – Feb
2 – March
and so on......

The format for supplying the input is:

1999-5

Where 1999 is the year and 5 is the numeric sequence of the month (corresponding to June). The program should display the day on which June 28, 1999 fell, and in this case the output will be MONDAY.

The output should be displayed in uppercase letters.

Suppose the following INPUT sequence is given to the program:

1999-5
1998-6

Then the output should be:

MONDAY
TUESDAY 



SOLUTIONS:-

/* Author:- Mohammed Sajadh NA
   Blog:- http://sajadhaja.blogspot.in
*/

package com.sajadhaja.training;

import java.text.DateFormatSymbols;
import java.util.Calendar;
import java.util.Scanner;

public class YearMonthDay {
    public static void main(String args[]){
        Scanner in =new Scanner(System.in);
        String a=in.next();
        String b=in.next();
        getDay(a);
        getDay(b);
    }
    public static void getDay(String in){
        String yearmon[]= in.split("-");
        Calendar cal=Calendar.getInstance();
        cal.set(Integer.parseInt(yearmon[0]),Integer.parseInt(yearmon[1]),28);
        int val = cal.get(Calendar.DAY_OF_WEEK);
        System.out.println(new DateFormatSymbols().getWeekdays()[val].toUpperCase() );
    }
}




8) Write a program which will accept three sentences (one sentence per line) and print the words having Initial Caps within the sentences. Below is an example.

Here is an example. If the below three sentences are given to the program as input,

This is a Program
Coding test of Initial Caps
the program Will Test You

Then, the output would look like:

This
Program
Coding
Initial
Caps
Will
Test
You
 

SOLUTIONS:-

/* Author:- Mohammed Sajadh NA
   Blog:- http://sajadhaja.blogspot.in
*/

package com.sajadhaja.training;

import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class StringExamp {
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        String li[]=new String[3];
        li[0]=in.nextLine();
        li[1]=in.nextLine();
        li[2]=in.nextLine();
        capsOut(li[0]);
        capsOut(li[1]);
        capsOut(li[2]);
       
    }
    public static void capsOut(String in){
        String words[]= in.split(" ");
        for(String word:words){
            Pattern pat = Pattern.compile("^[A-Z]");
            Matcher match = pat.matcher(word);
            if(match.find())
                System.out.println(word);
        }
       
    }

}

 

Thursday, 10 January 2013

Hibernate Sample Java Application

The objective of this example is to create event objects and store these events in a database and retrieve them for display using Hibernate. You may want to look at my article if Hibernate is not installed already on your system.

There are two approach to develop hibernate applications. The first one is “Using hibernate XML mapping files” and the other one is “Using JPA or Hibernate annotations”.

 Using Hibernate XML Mapping Files

org.hibernate.tutorial.domain package
Create a new Java package in the src directory(source directory of your project) and enter org.hibernate.tutorial.domain as the package name.
The first class
Create a new Java class(Event.java) in the org.hibernate.tutorial.domain package.
Event class represents the event we want to store in the database; it is a simple JavaBean class with some properties:

Event.java : A simple persistent class

01package org.hibernate.tutorial.domain;
02 
03import java.util.Date;
04 
05public class Event {
06    private Long id;
07 
08    private String title;
09    private Date date;
10 
11    public Event() {}
12 
13    public Long getId() {
14        return id;
15    }
16 
17    private void setId(Long id) {
18        this.id = id;
19    }
20 
21    public Date getDate() {
22        return date;
23    }
24 
25    public void setDate(Date date) {
26        this.date = date;
27    }
28 
29    public String getTitle() {
30        return title;
31    }
32 
33    public void setTitle(String title) {
34        this.title = title;
35    }
36}



The mapping file

Create a new XML file(Event.hbm.xml) which is our mapping file in the org.hibernate.tutorial.domain package.
Hibernate needs to know how to load and store objects of the persistent class. This is where the Hibernate mapping file comes into play. The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.

Event.hbm.xml : A simple hibernate XML mapping

01<?xml version="1.0" encoding="UTF-8"?>
02<!DOCTYPE hibernate-mapping PUBLIC
03    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
05
06<hibernate-mapping package="org.hibernate.tutorial.domain">
07
08    <class name="Event" table="EVENTS">
09        <id name="id" column="EVENT_ID">
10            <generator class="increment"/>
11        </id>
12        <property name="date" type="timestamp" column="EVENT_DATE"/>
13        <property name="title" column="EVENT_TITLE"/>
14    </class>
15
16</hibernate-mapping>
Hibernate configuration
At this point, you should have the persistent class and its mapping file in place. It is now time to configure Hibernate.
Create a new XML file and give this new configuration file the default name hibernate.cfg.xml and place it directly in the source directory(src directory) of your project, outside of any package.
hibernate.cfg.cml : A simple Hibernate XML configuration file
01<?xml version="1.0" encoding="UTF-8"?>
02<!DOCTYPE hibernate-configuration PUBLIC
03        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
05
06<hibernate-configuration>
07
08    <session-factory>
09
10        <!-- Database connection settings -->
11        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
12        <property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:xe</property>
13        <property name="connection.username">username</property>
14        <property name="connection.password">password</property>
15
16        <!-- SQL dialect -->
17        <property name="dialect">org.hibernate.dialect.OracleDialect</property>
18
19        <!-- JDBC connection pool (use the built-in) -->
20        <property name="connection.pool_size">1</property>
21
22        <!-- Enable Hibernate's automatic session context management -->
23        <property name="current_session_context_class">thread</property>
24
25        <!-- Disable the second-level cache  -->
26        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
27
28        <!-- Echo all executed SQL to stdout -->
29        <property name="show_sql">true</property>
30
31        <!-- Drop and re-create the database schema on startup -->
32        <property name="hbm2ddl.auto">update</property>
33
34        <mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>
35
36    </session-factory>
37
38</hibernate-configuration>


Note: If you want to log in to Oracle Database XE as the Administrator you must enter system for the user name and enter the password that was specified when Oracle Database XE was installed.
Note: The configuration above is for the Oracle XE database. If you use an another database management system already installed, you should change some properties in this configuration file. For example, if your database is MySQL, you must replace some properties like this :


01...
02        <!-- Database connection settings -->
03        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
04        <property name="connection.url">jdbc:mysql://localhost/SampleDB</property>
05        <property name="connection.username">root</property>
06        <property name="connection.password"></property>
07
08        <!-- SQL dialect -->
09        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
10...


org.hibernate.tutorial.util package

Create a new Java package in the src directory(source directory of your project) and enter org.hibernate.tutorial.util as the package name.

Startup and helpers

It is time to load and store some Event objects, but first you have to complete the setup with some infrastructure code. You have to startup Hibernate by building a global org.hibernate.SessionFactory object and storing it somewhere for easy access in application code. A org.hibernate.SessionFactory is used to obtain org.hibernate.Session instances. A org.hibernate.Session represents a single-threaded unit of work. The org.hibernate.SessionFactory is a thread-safe global object that is instantiated once.
Create a new Java class(HibernateUtil.java) in the org.hibernate.tutorial.util package that takes care of startup and makes accessing the org.hibernate.SessionFactory more convenient.
HibernateUtil.java : The HibernateUtil class for startup and SessionFactory handling


01package org.hibernate.tutorial.util;
02
03import org.hibernate.SessionFactory;
04import org.hibernate.cfg.Configuration;
05
06public class HibernateUtil {
07
08    private static final SessionFactory sessionFactory = buildSessionFactory();
09
10    private static SessionFactory buildSessionFactory() {
11        try {
12            // Create the SessionFactory from hibernate.cfg.xml
13            return new Configuration().configure().buildSessionFactory();
14        }
15        catch (Throwable ex) {
16            // Make sure you log the exception, as it might be swallowed
17            System.err.println("Initial SessionFactory creation failed." + ex);
18            throw new ExceptionInInitializerError(ex);
19        }
20    }
21
22    public static SessionFactory getSessionFactory() {
23        return sessionFactory;
24    }
25
26}

org.hibernate.tutorial package

Create a new Java package in the src directory(source directory of your project) and enter org.hibernate.tutorial as the package name.
Loading and storing objects

We are now ready to start doing some real work with Hibernate.
Create a new Java class(EventManager.java) with a main() method in the org.hibernate.tutorial package.
EventManager.java : The “HibernateApplication” main application code

01package org.hibernate.tutorial;
02
03import org.hibernate.Session;
04
05import java.util.*;
06
07import org.hibernate.tutorial.domain.Event;
08import org.hibernate.tutorial.util.HibernateUtil;
09
10public class EventManager {
11
12    public static void main(String[] args) {
13        EventManager mgr = new EventManager();
14
15        mgr.createAndStoreEvent("My First Event", new Date());
16
17        Calendar calendar = Calendar.getInstance();
18        calendar.set(Calendar.YEAR, 2012); // Year
19        calendar.set(Calendar.MONTH, 0);   // Month, The first month of the year is JANUARY which is 0
20        calendar.set(Calendar.DATE, 1);    // Day, The first day of the month has value 1.
21        mgr.createAndStoreEvent("My Second Event", calendar.getTime());
22
23        List events = mgr.listEvents();
24        for (int i = 0; i < events.size(); i++) {
25            Event theEvent = (Event) events.get(i);
26            System.out.println(
27                    "Event: " + theEvent.getTitle() + " Time: " + theEvent.getDate()
28            );
29        }
30
31        HibernateUtil.getSessionFactory().close();
32    }
33
34    private void createAndStoreEvent(String title, Date theDate) {
35        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
36        session.beginTransaction();
37
38        Event theEvent = new Event();
39        theEvent.setTitle(title);
40        theEvent.setDate(theDate);
41        session.save(theEvent);
42
43        session.getTransaction().commit();
44    }
45
46    private List listEvents() {
47        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
48        session.beginTransaction();
49        List result = session.createQuery("from Event").list();
50        session.getTransaction().commit();
51        return result;
52    }
53
54}

The final appearance of the application should be as follows:

LastappearanceOfApp 

Now our project is ready. Right click to project or right click to EventManager.java and click Run As–>Java Application.


Events


You will see the events stored in “EVENTS” table in the database if there is not a problem.

Note: If you get a message when you run your application like:
Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
You can add
1<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
line to the hibernate.cfg.xml file to solve this problem.
For more detailed explanation:
http://stackoverflow.com/questions/4588755/hibernate-disabling-contextual-lob-creation-as-createclob-method-threw-error


METHOD 2

Using Annotations


We will use JPA Annotations to replace the Hibernate XML mapping files with inline metadata.
You may want to copy your existing “HibernateApplication” project directory before you make the following changes—you’ll migrate from native Hibernate to standard JPA mappings.
Now delete the src/org.hibernate.tutorial.domain/Event.hbm.xml file. You’ll replace this file with annotations in the src/org.hibernate.tutorial.domain/Event.java class source.
Event.java: Mapping the Event class with Annotations

01package org.hibernate.tutorial.domain;
02
03import java.util.Date;
04
05import javax.persistence.Column;
06import javax.persistence.Entity;
07import javax.persistence.GeneratedValue;
08import javax.persistence.Id;
09import javax.persistence.Table;
10import javax.persistence.Temporal;
11import javax.persistence.TemporalType;
12
13@Entity
14@Table(name="EVENTS")
15public class Event {
16    @Id
17    @GeneratedValue
18    @Column(name="EVENT_ID")
19    private Long id;
20
21    @Column(name="EVENT_TITLE")
22    private String title;
23
24    @Temporal(TemporalType.TIMESTAMP)
25    @Column(name="EVENT_DATE")
26    private Date date;
27
28    public Event() {}
29
30    public Long getId() {
31        return id;
32    }
33
34    private void setId(Long id) {
35        this.id = id;
36    }
37
38    public Date getDate() {
39        return date;
40    }
41
42    public void setDate(Date date) {
43        this.date = date;
44    }
45
46    public String getTitle() {
47        return title;
48    }
49
50    public void setTitle(String title) {
51        this.title = title;
52    }
53}

The other change you need to make to your project, besides deleting the now obsolete XML mapping file, is a change in the Hibernate configuration, in hibernate.cfg.xml.
Replace

1<mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>

line with
1<mapping class="org.hibernate.tutorial.domain.Event"/>
Finally, you should replace

1return new Configuration().configure().buildSessionFactory();

line in HibernateUtil.java with
1Configuration cfg = new Configuration();
2cfg.addAnnotatedClass(org.hibernate.tutorial.domain.Event.class);
3return cfg.configure().buildSessionFactory();
This is all you need to change to run the example application with annotations.Try running it again. You should see the events stored in the “EVENTS” table in your database.

Hibernate Installation/Setup on Eclipse IDE

I will show how to install Hibernate in this blog post and I will set up a small database application that can store events in my another post.Although you can use whatever database and IDE you feel comfortable using, I will use MYSQL and Eclipse IDE. Also I assume that Java is already installed on your system.
You should download the latest production release of Hibernate from the Hibernate website at http://www.hibernate.org/ or http://sourceforge.net/projects/hibernate/files/hibernate3/ and unpack the archive after download.

Note: I have downloaded the latest production release, hibernate-distribution-3.6.6.Final-dist.zip. If there is a newer version when you’re reading this post, I advice you to download and use it.

Create a new Java Project and enter HibernateApplication as project name.

Create lib and src subdirectories in this project. (When you create a new Java Project in Eclipse IDE, src subdirectory will be created automatically.)

Copy JAR files which are listed below, from hibernate distribution that you have downloaded to the lib directory of the “HibernateApplication”project.
Under root directory of the hibernate distrubution:
hibernate3.jar

Under lib/required directory of the hibernate distrubution:
antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
javassist-3.12.0.GA.jar
jta-1.1.jar
slf4j-api-1.6.1.jar

Under lib/jpa directory of the hibernate distrubution:
hibernate-jpa-2.0-api-1.0.1.Final.jar


Download slf4j-1.6.1.zip file from http://www.slf4j.org/download.html, unpack the archive and copy the slf4j-simple-1.6.1.jar file to lib directory of the “HibernateApplication” project.
slf4j-simple-1.6.1.jar


Additionally, you will need the database driver JAR that Hibernate uses to connect to your database. I use MYSQL Database and it’s database driver jar :

Copy this mysqlconnector.jar  to the lib directory of the “HibernateApplication” project

.
Note: You should replace this database driver JAR with a different database driver JAR



After these steps “HibernateApplication” project will look like this:
HibernateApplication_lib
Now I will create a User library on Eclipse IDE. Then, I will add all JAR files in the HibernateApplication\lib directory to this User library and add this User library to the project build path.
Click Window–>Preferences on the top menu bar of Eclipse.
Preferences
Click Java–>Build Path–>User Libraries and click New button then enter “Hibernate”
as the User library name.
User Library
Select “Hibernate” User library that we just created and click Add JARS… button.
Hibernate User Library
Select all JAR files in the lib folder of the “HibernateApplication” project and click Open button to add all JAR files to “Hibernate” User library.
AllHibernateJars
Now “Hibernate” User library is ready and we can add this User library to “HibernateApplication” project build path.
HibernateUserLibrary_Jars_added
Right click to “HibernateApplication” project and click Build Path–>Add Libraries
HibernateApplication_Build_Path
Then, select “User Library” and click Next button.
UserLibrary_selection
Finally, select “Hibernate” User library and click Finish button.
Hibernate_user_library_selection
After adding “Hibernate” User library to “HibernateApplication” project, it will look like this:
Hibernate_User_Library_Finished
Congratulations, you have installed Hibernate on Eclipse IDE