Hibernate for beginners | Hibernate Tutorial with Example | ORM tool

Hibernate for beginners | Hibernate Tutorial with Example | ORM tool



Hibernate is an Object/ Relational Mapping solution for Java environments. It reduces the development cost by reducing paradigm mismatch between how data is represented in objects versus relational databases.

Hibernate takes care of the mapping from Java classes to database tables and provides data query and retrieval facilities. This tutorial is designed for the beginners of Hibernate and expects you to have some knowledge about Java and SQL. I’m going to use MySQL database and Eclipse IDE in this tutorial.

By following this tutorial you will get the knowledge of;
1. Setup the Development Environment for Hibernate
2. Create POJO Classes
3. Create Mapping Files
4. Hibernate Configuration
5. Create Startup Helper Class
6. Create Test Class to Load and Store Objects

Let's start.

1. Setup the Development Environment for Hibernate

First you need to set up the development environment. Following things are needed if you want to try Hibernate with MySQL using Eclipse IDE.

1. Hibernate distribution bundle – Download
2. MySQL installed in your Computer – Download
3. JDBC driver for MySQL – Download
4. slf4j logging backend – Download
5. Eclipse IDE – Download

1.1 Setup the Database

I'm going to use simple database named "userdata" which has two tables named "users" and "tasks". Figure 1 illustrates the structure of the database and there "id" column is the Primary Key of both tables and it is set to AUTO_INCREMENT.

1.2 Create New Project

In this tutorial I’m going to show how to Retrieve, Add, Delete and Update data in a MySQL database. There I’ll create simple Java Project and you can use this tutorial to create web applications too.

First create new project in Eclipse using appropriate name, I’ll give "MyFirstHibernateApp".


You need to manually account for all the needed dependencies, so let’s create new folder called "lib" inside the "MyFirstHibernateApp" by right clicking on it as shown in following Figure 3.

Now copy following files into that folder.
1. hibernate3.jar (Can be found in distribution bundle)
2. All artifacts in the lib/required directory in distribution bundle
3. All artifacts in the lib/jpa directory in distribution bundle
4. All files from either the lib/bytecode/cglib or lib/bytecode/javassist directory
5. One of the slf4j logging (I'll use slf4j-simple-1.6.1.jar found inside slf4j-1.6.1.zip)
6. mysql-connector-java-5.1.15-bin.jar (JDBC driver for MySQL )

Then you can configure the built path. To do that, right click on project "MyFirstHibernateApp" in Package Explorer and select Build Path --> Configure Build Path... Then go to Libraries tab and browse lib folder you created earlier. Then add external jars by selecting all jar files that you copied to lib folder in one of previous step. (Check Figure 4).


Now you will be able to see the referenced libraries as follow (Figure 5).


2. Create POJO Classes

Next, I'll create two classes that represent the user and task we want to store in the database. Those are simple JavaBean classes with some properties which uses standard JavaBean naming conventions for property getter and setter methods and private visibility for the fields.

To create new class right click on "MyFirstHibernateApp" and select New --> Class. Then give appropriate package name, I’ll give "com.hib" as figure 6. You can generate getter and setters easily by selecting variable declaration and selecting Source --> Generate Getters and Setters…


User Class
?
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.hib;

public class User {
 private Integer id;
 private String firstName;
 private String lastName;
  
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
}
Task Class
?
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
package com.hib;

public class Task {

 private Integer id;
 private Integer userID;
 private String title;
 private String description;
  
 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public Integer getUserID() {
  return userID;
 }
 public void setUserID(Integer userID) {
  this.userID = userID;
 }
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public String getDescription() {
  return description;
 }
 public void setDescription(String description) {
  this.description = description;
 }
}
The id property holds a unique identifier value for a particular user and task. All persistent entity classes will need such an identifier property if you want to use the full feature set of Hibernate.

3. Create Mapping Files

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.

Right click on the "src" folder and select New --> File and paste following code there. Save it as user.hbm.xml.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

<hibernate-mapping>
 <class name="com.hib.User" table="users" >
  <id name="id" type="int" column="id" >
   <generator class="native"/>
  </id>

  <property name="firstName">
   <column name="first_name" />
  </property>
  <property name="lastName">
   <column name="last_name"/>
  </property>
 </class>
</hibernate-mapping>
Tasks.java should also have a mapping file, so create another file and paste following code. Save it as task.hbm.xml
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

<hibernate-mapping>
 <class name="com.hib.Task" table="tasks">
  <id name="id" type="int" column="id" >
   <generator class="native"/>
  </id>

  <property name="userID">
   <column name="user_id" />
  </property> 
  <property name="title">
   <column name="title" />
  </property>
  <property name="description">
   <column name="description"/>
  </property>
 </class>
</hibernate-mapping>
In the above mapping file you can see the mapping of the unique identifier property to the tables primary key. As we do not want to care about handling this identifier, we configure Hibernate's identifier generation strategy for a surrogate primary key column by giving class="native". If it is not AUTO_INCREMENT one we should use class="assign".

The id element is the declaration of the identifier property. The name="id" mapping attribute declares the name of the JavaBean property and tells Hibernate to use the getId() and setId() methods to access the property. The column attribute tells Hibernate which column of the "users" and "tasks" tables holds the primary key value. Similar to the id element, the name attribute of the property element tells Hibernate which getter and setter methods to use.

4. Hibernate Configuration

Now you have the persistent class and its mapping file in place. Let’s configure Hibernate.

Right click on the "src" folder and select New --> File and paste following code there. Save it as hibernate.cfg.xml. Here you have to give the username and password according to your MySQL account. In my case username is root and there is no password.
?
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
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<hibernate-configuration>
 <session-factory>
  <!-- Database connection settings -->
  <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="connection.url">jdbc:mysql://localhost/userdata</property>
  <property name="connection.username">root</property>
  <property name="connection.password"></property>
   
  <!-- JDBC connection pool (use the built-in) -->
  <property name="connection.pool_size">1</property>
   
  <!-- SQL dialect -->
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
   
  <!-- Enable Hibernate's automatic session context management -->
  <property name="current_session_context_class">thread</property>

  <!-- Disable the second-level cache -->
  <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
   
  <!-- Echo all executed SQL to stdout -->
  <property name="show_sql">true</property>
   
  <!-- Drop and re-create the database schema on startup -->
  <property name="hbm2ddl.auto">update</property>
   
  <!-- Mapping files -->
  <mapping resource="user.hbm.xml"/>
  <mapping resource="task.hbm.xml"/>
   
 </session-factory>
</hibernate-configuration>
5. Create Startup Helper Class

You have to startup Hibernate by creating a global org.hibernate.SessionFactory object and storing it somewhere for easy access in your 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. We will create a HibernateUtil helper class that takes care of startup and makes accessing the org.hibernate.SessionFactory more convenient.

To create new class right click on "com.hib" package and select New --> Class and give Name as HibernateUtil.java and paste the following code in class file.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.hib;

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

public class HibernateUtil {
 private static final SessionFactory sessionFactory = buildSessionFactory();
 private static SessionFactory buildSessionFactory() {
  try {
   // Create the SessionFactory from hibernate.cfg.xml
   return new Configuration().configure().buildSessionFactory();
  }
  catch (Throwable ex) {
   // Make sure you log the exception, as it might be swallowed
   System.err.println("Initial SessionFactory creation failed." + ex);
   throw new ExceptionInInitializerError(ex);
  }
 }
 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
}
6. Create Test Class to Load and Store Objects

Now it’s time to do some real work using Hibernate. Following test class illustrate how we can Add, Retrieve, Update and Delete data in a MySQL database.

To create new class right click on "com.hib" package and select New --> Class and give Name as Test.java and paste the following code in class file.
?
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package com.hib;

import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {
   
  Test tst = new Test();
   
  /**
   * adding records
   */
  tst.addUser("Saranga", "Rath");
  tst.addUser("Isuru", "Sampath");
  tst.addUser("Saranga", "Jaya");
  tst.addUser("Prasanna", "Milinda");
   
  tst.addTask(1, "Call", "Call Pubudu at 5 PM");
  tst.addTask(1, "Shopping", "Buy some foods for Kity");
  tst.addTask(2, "Email", "Send birthday wish to Pubudu");
  tst.addTask(2, "SMS", "Send message to Dad");
  tst.addTask(2, "Office", "Give a call to Boss");
   
  /**
   *  retrieving data
   */
  tst.getFullName("Saranga");
   
  /**
   * full updating records
   */
  User user = new User();
  user.setId(1);
  user.setFirstName("Saranga");
  user.setLastName("Rathnayake");
  tst.updateUser(user);
   
  /**
   * partial updating records
   */
  tst.updateLastName(3, "Jayamaha");

  /**
   * deleting records
   */
  User user1 = new User();
  user1.setId(4);
  tst.deleteUser(user1);
 }

 private void addUser(String firstName, String lastName) {
   
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
    
   User user = new User();
    
   user.setFirstName(firstName);
   user.setLastName(lastName);
    
   session.save(user);
    
   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }

 private void addTask(int userID, String title, String description) {
   
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
    
   Task task = new Task();
    
   task.setUserID(userID);
   task.setTitle(title);
   task.setDescription(description);
    
   session.save(task);
    
   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }
  
 private void updateLastName(int id, String lastName) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   String hqlUpdate = "update User u set u.lastName = :newLastName where u.id = :oldId";
   int updatedEntities = session.createQuery( hqlUpdate )
   .setString( "newLastName", lastName )
   .setInteger( "oldId", id )
   .executeUpdate();

   trns.commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
   
 }

 private void updateUser(User user) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
    
   session.update(user);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }

 private void getFullName(String firstName) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
   List<User> users = session.createQuery("from User as u where u.firstName = :firstName")
   .setString( "firstName", firstName )
   .list();
   for (Iterator<User> iter = users.iterator(); iter.hasNext();) {
    User user = iter.next();
    System.out.println(user.getFirstName() +" " + user.getLastName());
   }
   trns.commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }
  
 private void deleteUser(User user) {
  Transaction trns = null;
  Session session = HibernateUtil.getSessionFactory().openSession();
  try {
   trns = session.beginTransaction();
    
   session.delete(user);

   session.getTransaction().commit();
  } catch (RuntimeException e) {
   if(trns != null){
    trns.rollback();
   }
   e.printStackTrace();
  } finally{
   session.flush();
   session.close();
  }
 }
}
If you have setup the database and followed the above steps correctly you should get following output.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into users (first_name, last_name) values (?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: insert into tasks (user_id, title, description) values (?, ?, ?)
Hibernate: select user0_.id as id0_, user0_.first_name as first2_0_, user0_.last_name as last3_0_ from users user0_ where user0_.first_name=?
Saranga Rath
Saranga Jaya
Hibernate: update users set first_name=?, last_name=? where id=?
Hibernate: update users set last_name=? where id=?
Hibernate: delete from users where id=?
Hibernate use Hibernate Query Language (HQL) which is powerful than SQL and fully object-oriented. You can get good knowledge about HQL by following HQL Documentation.

I have included the source files of this tutorial with the database. You can download it from

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.