Hibernate Setup in Eclipse with CRUD operations

Lets develop hibernate applicaton for CRUD operations

Step 1 )
First create simple java desktop application project in eclipse and name it is Hibernate Practice1 as below
New project

Eclipse Project

Click finish.
Step 2)
Adding required jar files into project’s build path as shown below

Click on properties

properties

Click on Add Library to make separate library for hibernate jars.

.Add Library

Select user library and click next
And next click on user libraries and in new window click on New
Give the name of the library as Hibernatejars and say ok

new user library

Now select created user library and click on Add Jars on the right side and add all the jars related to hibernate by browsing to appropriate location in your system.

Step 3)
Now add database driver jar to project’s buildpath as below
I am using mysql so I am adding mysql jar.

Right click on project -> properties ->AddExternalJars
Browse to appropriate location and add it.
Now project setup with respect to jars is done.

Step 4)
First create hibernate.cfg.xml inside src folder and add all the attributes related to database like url,username,password etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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="hbm2ddl.auto">update</property>  
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
        <property name="connection.url">jdbc:mysql://localhost:3306/HibernateDB</property>  
        <property name="connection.username">root</property>  
        <property name="connection.password">kb</property>  
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="show_sql">true</property>
    <mapping resource="com/kb/hbmFiles/Employee.hbm.xml"/>  
    </session-factory>  
</hibernate-configuration>  
<?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="hbm2ddl.auto">update</property>  
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>  
        <property name="connection.url">jdbc:mysql://localhost:3306/HibernateDB</property>  
        <property name="connection.username">root</property>  
        <property name="connection.password">kb</property>  
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="show_sql">true</property>
    <mapping resource="com/kb/hbmFiles/Employee.hbm.xml"/>  
    </session-factory>  
</hibernate-configuration>  

Now create our pojo class Employee.java inside src/com/kb/model

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.kb.model;
 
public class Employee {
    private int id;
    private String name;
    private String designation;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDesignation() {
        return designation;
    }
    public void setDesignation(String designation) {
        this.designation = designation;
    }
 
}
package com.kb.model;

public class Employee {
	private int id;
	private String name;
	private String designation;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDesignation() {
		return designation;
	}
	public void setDesignation(String designation) {
		this.designation = designation;
	}

}

Create Employee.hbm.xml mapping file under src/com/kb/hbmFiles folder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?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="com.kb.model.Employee" table="Employee">  
    <id name="id">  
     <generator class="assigned"></generator>  
    </id>  
            
    <property name="name"></property>  
    <property name="designation"></property>  
            
  </class>  
            
 </hibernate-mapping>  
<?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="com.kb.model.Employee" table="Employee">  
    <id name="id">  
     <generator class="assigned"></generator>  
    </id>  
            
    <property name="name"></property>  
    <property name="designation"></property>  
            
  </class>  
            
 </hibernate-mapping>  

Now create our Client which will do the CRUD operation.
Create a class inside com/kb/Dao

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.kb.Dao;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
 
import com.kb.model.Employee;
 
public class InteractWithDB {
 
    public static void main(String[] args) {
        
           //creating configuration object  
        Configuration cfg=new Configuration();  
        
        cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  
          
        //creating seession factory object  
        SessionFactory factory=cfg.buildSessionFactory();  
 
Employee emp = new Employee();//Transient Object since it is not associated with hibernate session
        //creating session object  
        Session session=factory.openSession();  
          
        //creating transaction object  
        Transaction t=session.beginTransaction();  
              
        Employee e1=new Employee(); 
        e1.setId(115);  
        e1.setName("kb");
        e1.setDesignation("se");
        session.save(e1); //Persistent Object since it is attached to hibernate session 
          
    System.out.println("successfully saved");
        
        //Retrieving from DB
        Employee retrievedEmp =(Employee) session.get(Employee.class, e1.getId());
        System.out.println(" retrieved employee details ----");
        System.out.println("name :"+retrievedEmp.getName());
        System.out.println("designation "+retrievedEmp.getDesignation());
        
        retrievedEmp.setDesignation("TL");
        //updating existing employee's designation
        session.update(retrievedEmp);      
        
        Employee retrievedUpdatedEmp = 
(Employee)session.get(Employee.class, e1.getId());
        System.out.println(" retrieved employee details ----");
        System.out.println("name :"+retrievedUpdatedEmp.getName());
        System.out.println("designation "+retrievedUpdatedEmp.getDesignation());
        
        //deleting existing employee
        session.delete(retrievedUpdatedEmp);
        
        t.commit();
//here we can say it is detached object as it went to DB now.
        session.close();  
    }
}
package com.kb.Dao;

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

import com.kb.model.Employee;

public class InteractWithDB {

	public static void main(String[] args) {
		
		   //creating configuration object  
	    Configuration cfg=new Configuration();  
	    
	    cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file  
	      
	    //creating seession factory object  
	    SessionFactory factory=cfg.buildSessionFactory();  

Employee emp = new Employee();//Transient Object since it is not associated with hibernate session
	    //creating session object  
	    Session session=factory.openSession();  
	      
	    //creating transaction object  
	    Transaction t=session.beginTransaction();  
	          
	    Employee e1=new Employee(); 
	    e1.setId(115);  
	    e1.setName("kb");
	    e1.setDesignation("se");
	    session.save(e1); //Persistent Object since it is attached to hibernate session 
	      
	System.out.println("successfully saved");
	    
	    //Retrieving from DB
	    Employee retrievedEmp =(Employee) session.get(Employee.class, e1.getId());
	    System.out.println(" retrieved employee details ----");
	    System.out.println("name :"+retrievedEmp.getName());
	    System.out.println("designation "+retrievedEmp.getDesignation());
	    
	    retrievedEmp.setDesignation("TL");
	    //updating existing employee's designation
	    session.update(retrievedEmp);	   
	    
	    Employee retrievedUpdatedEmp = 
(Employee)session.get(Employee.class, e1.getId());
	    System.out.println(" retrieved employee details ----");
	    System.out.println("name :"+retrievedUpdatedEmp.getName());
	    System.out.println("designation "+retrievedUpdatedEmp.getDesignation());
	    
	    //deleting existing employee
	    session.delete(retrievedUpdatedEmp);
	    
	    t.commit();
//here we can say it is detached object as it went to DB now.
	    session.close();  
	}
}

That’s all. Our hibernate application is ready now.
Run the client and see the CRUD effect in the corresponding database.

Thanks for reading and appreciate your comments.

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on