Today we are going to understand how to put Hibernate into an execution using the Eclipse Integrated Development Environment(IDE) application.
As you know that Hibernate is a middleware used for object-relational mapping(ORM) and for performing efficient object persistence.
So, in the next section, we are going to create a Java class which will be mapped to a table in database(Oracle Express Edition 10g) and its objects will be persisted, using the Hibernate.
Creating a Java Project in Eclipse
To begin creating you first Hibernate program in Eclipse, you will have to create a new Java Project by clicking on -
File -->Java Project in the Eclipse window, as shown in the picture below.
Let us name this project HibernateProgram and click on Finish button, as shown in the picture below.
Next, after naming this Java project, we will create a package, which will contain all the Java code files representing our Model class(whose objects needs to be persisted)
and the class that makes the Hibernate work and create an object-relational mapping(ORM) and object persistence.
In order to create a package, we will have to right click on the src folder in our Java Project and click on New--> Package, as shown
in the picture below.
Next, we name this package - decodejava.
Advertisement
Adding a POJO/Entity class
As explained above, under this package, we are going to create a class that will contain all the Java code files
representing our Model class(whose objects needs to be persisted)
and the class that makes the Hibernate work and create an object-relational mapping(ORM) and object persistence.
So, let's create our first class under this package, by right clicking on decodejava package and click on New --> Class, as shown in the picture below.
Next, we are going to name this class - UserData and click on Finish button.
This class is also known as Model Class. This object will be mapped to a database table and its
object will be persisted by the Hibernate.
This is a simple Java class whose objects needs to be persisted/saved, these objects are also known as Plain Old Java Objects(POJO) or Entity class.
Some may even refer to such class whose objects needs to be persisted as the Model class.
UserData.java
package decodejava;
public class UserData
{
//public no-arg constructor
public UserData()
{
}
private int id;
private String name;
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;
}
}
Adding the class that calls the Hibernate API
Next, we are going to create another class under the package, by right clicking on decodejava package and click on
New --> Class, as we did in the previous step.
We are going to name this class - Hiber and click on Finish button.
This class will perform some create, retrieve, update, delete(CRUD) operations on the UserData object using the Hibernate API, which
will lead object persistence and an object-relational mapping(ORM) in the database.
The Hiber class creates a Configuration object, used to configure the Hibernate. This is the first object we use when using the Hibernate.
This object is used to specify the location of a configuration file and
mapping document used by Hibernate. Using Configuration object we can create a SessionFactory object, which is eventually used to create a Session
object to perform the object persistence operations.
Hiber.java
package decodejava;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Hiber
{
public static void main(String[] args)
{
//Creating the Configuration object.
Configuration cfg = new Configuration().configure("hibernate.cfg.xml").addResource("userdata.hbm.xml");
//Using the Configuration object to creagte a SessionFactory object.
SessionFactory sf = cfg.buildSessionFactory();
//Using the SessionFactory object to create a Session object.
Session session = sf.openSession();
//Creating the first object
UserData ob1 = new UserData();
ob1.setId(1);
ob1.setName("Adam");
//Creating the second object
UserData ob2 = new UserData();
ob2.setId(2);
ob2.setName("Ahmad");
//Creating the third object
UserData ob3 = new UserData();
ob3.setId(3);
ob3.setName("Amit");
session.beginTransaction();
session.save(ob1); //Saving the first object.
session.save(ob2); //Saving the second object
session.save(ob3); //Saving the third object
session.getTransaction().commit();
session.close();
ob1 = null;
//Creating a new Session to retrieve and modify the object.
session= sf.openSession();
session.beginTransaction();
ob1 =(UserData)session.get(UserData.class, 1);
ob2 =(UserData)session.get(UserData.class, 3);
//Modifying the username of Id=3
ob1.setName("Mitch");
//Saving the modified object in database
session.saveOrUpdate(ob1);
//Deleting the user with id=3
session.delete(ob2);
//Committing the transaction
session.getTransaction().commit();
//Closing the session
session.close();
ob1 = null;
ob2 = null;
ob3 = null;
//Creating a new Session to retrieve the objects.
session= sf.openSession();
session.beginTransaction();
ob1 = (UserData)session.get(UserData.class,1);
ob2 = (UserData)session.get(UserData.class,2);
ob3 = (UserData)session.get(UserData.class,3);
System.out.println("Retrieving the saved objects");
//Retrieving details of the first user.
System.out.println("First User");
System.out.println("Id : " + ob1.getId() + " Name : " + ob1.getName());
//Retrieving details of the second user.
System.out.println("Second User");
System.out.println("Id : " + ob2.getId() + " Name : " + ob2.getName());
session.getTransaction().commit();
//closing the session
session.close();
//closing the heavyweight SessionFactory object
sf.close();
}
}
Adding JARs
We are going to add some JARs files to our Java project. These JARs make the Hibernate work with our database using a specific JDBC Driver for our particular
database.
In order to do this, let's right click on our project HibernateProgam and click on Properties.
In the next window, we need to click on Java Build Path on the left and click on the Libraries tab on the right side of window.
In this window, we need to click on the Add External JARs, as shown in the picture below.
Next, we are going to go to a folder named required(within our Hibernate installation folder)
and select all the JARs in it and click on Open button.
Next, you will be shown the added multiple JARs to your project, to finalize it, click the OK button.
Finally, we are going to add one more JAR file by performing the same steps in our previous step.
This is a specific JDBC JAR file(ojdbc14.jar) required by Hibernate to connect to our database(Oracle Express Edition 10g) and perform
object-relational mapping and object persistence.
Adding a configuration file
Next, we are going to add a configuration file to our project. In order to create this configuration file, we need to right-click on our package decodejava
and click on New --> File, as shown in the picture below.
Next, we are going to name this configuration file as hibernate.cfg.xml,
this should be the default name of this hibernate configuration file and it allows Hibernate to easily locate it.
This configuration document ends with an extension .cfg.xml,
and it is named as hibernate.cfg.xml.
This configuration file is an xml file and it allows us to specify the following features -
A database to which Hibernate connects to perform object-relational mapping and object persistence.
The JDBC driver class for our specific database, used by the Hibernate to connect to the database.
The username and password of database, using which the Hibernate connects to the database.
An SQL Dialect, used by the Hibernate to instruct the database.
A Entity/POJO class which will be mapped to a database table by Hibernate.
A command to echo all the SQL commands which are executed by the Hibernate on stdout.
The mapping entity class, used by Hibernate to correctly map the class to a database table.
hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
<property name="connection.username">system</property>
<property name="connection.password">promila21</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.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">create</property>
<!-- Names the mapping entity class -->
<mapping class ="decodejava.UserData"/>
</session-factory>
</hibernate-configuration>
Adding the mapping-resource file
Following the same steps using which we created and added the configuration file in our project, we are going to create and add a mapping-resource file within our package decodejava.
This file allows Hibernate to map the Model class to a table in the database and perform the object-relational mapping. This is also an XML file and we are going to name this
file userdata.cfg.xml.
This mapping document ends with an extension .hbm.xml,
hence, we have named it userdata.hbm.xml.
This mapping document tells Hibernate -
The name of the class to be mapped to a database table.
The name of the database table to be created.
The specific field, which is to be made the primary key in this table.
The data-type of each property in the class, which is going to mapped to a column in a table.
userdata.hbm.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name = "decodejava.UserData" table = "userdata">
<id name = "id" column = "id" type = "int">
<generator class="native"/>
</id>
<property name = "name" column = "Name" type = "string"/>
</class>
</hibernate-mapping>
This mapping document has <hibernate-mapping> as the root element and its child element <class>, containing all the class elements.
The name attribute within the <class> element defines the name of the class to be mapped to a database table.
The table attribute within the <class> element defines the name of database table to be created for the class.
The id element maps a property within the class to the primary key of the database table.
the name child attribute refers to the name of a property in the class.
The column child attribute refers to name of a column in the database table.
The type child attribute specifies the data type of the property within the class, which will be mapped to SQL data type.
The property element maps a property within the class to a column in the database table.
the name child attribute refers to the name of a property in the class.
The column child attribute refers to the column name in the database table.
Execution
Finally, after executing Hiber class, you will get the following output within the Console window. This output shows you all the SQL commands executed by the Hibernate within the database to map the Java class to a database table and perform all the
activities of saving, modifying and retrieving and displaying the objects of UserData, as specified in the Hiber class, as shown below.
Hibernate: create sequence hibernate_sequence start with 1 increment by 1
Hibernate: create table userdata (id number(10,0) not null, Name varchar2(255 char), primary key (id))
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into userdata (Name, id) values (?, ?)
Hibernate: insert into userdata (Name, id) values (?, ?)
Hibernate: insert into userdata (Name, id) values (?, ?)
Hibernate: select userdata0_.id as id1_0_0_, userdata0_.Name as Name2_0_0_ from userdata userdata0_ where userdata0_.id=?
Hibernate: select userdata0_.id as id1_0_0_, userdata0_.Name as Name2_0_0_ from userdata userdata0_ where userdata0_.id=?
Hibernate: update userdata set Name=? where id=?
Hibernate: delete from userdata where id=?
Hibernate: select userdata0_.id as id1_0_0_, userdata0_.Name as Name2_0_0_ from userdata userdata0_ where userdata0_.id=?
Hibernate: select userdata0_.id as id1_0_0_, userdata0_.Name as Name2_0_0_ from userdata userdata0_ where userdata0_.id=?
Hibernate: select userdata0_.id as id1_0_0_, userdata0_.Name as Name2_0_0_ from userdata userdata0_ where userdata0_.id=?
Retrieving the saved objects
First User
Id : 1 Name : Mitch
Second User
Id : 2 Name : Ahmad
Additionally you can see the updated contents of the table as shown below.