Today we are going to understand how to put Hibernate into an execution without using any Integrated Development Environment(IDE) application
like Eclipse, NetBeans etc.
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.
POJO/Entity class
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 an 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;
}
}
Class that makes hibernate work
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 Configuration object is used to configure the Hibernate. This is the first object we use when using 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, 3);
//Modifying the username of Id=3
ob1.setName("Rohan");
//Saving the modified object in database
session.saveOrUpdate(ob1);
//Committing the trasaction
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());
//Retrieving details of the third user.
System.out.println("Third User");
System.out.println("Id : " + ob3.getId() + " Name : " + ob3.getName());
session.getTransaction().commit();
//closing the session
session.close();
//closing the heavyweight SessionFactory object
sf.close();
}
}
Advertisement
Mapping Document
This mapping document is essentially required by Hibernate to map the class and its instance variables/properties to a database table and its columns.
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.
This mapping document ends with an extension .hbm.xml,
hence, we have named it userdata.hbm.xml.
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.
Hibernate Configuration File
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 resource file, used by Hibernate to correctly map the class to a database table.
This configuration document ends with an extension .cfg.xml,
and it is named as hibernate.cfg.xml.
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"/>
<!--Naming the mapping resource file -->
<mapping resource ="userdata.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Directory Structure of Hibernate Project
The picture above depicts how and where to arrange POJO/Entity(.java) file and the other the class(that calls the hibernate into action)
in a specific directory structure.
Project Folder - HibernateProgram is the name of our Project and it is a top-level directory.
This project folder contains the main package of our project i.e. decodejava,
which contains POJO/Entity class file i.e. Hiber.java
and the class that calls the hibernate into action i.e. UserData.java.
Besides this, the project folder also contains two important files put hibernate project in action, such as -
The hibernate configuration file i.e. hibernate.cfg.xml, and,
The hibernate mapping document i.e. userdata.hbm.xml.
Compilation
First, compile the UserData.java, Model class.
Second, in order compile the Hiber.java class you have to take two steps -
1) To set ojdbc14.jar(JDBC JAR file required to connect to Oracle database) to the classpath or put this JAR file in the folder "C:\Program Files\Java\jre1.8.0_144\lib\ext", where jre1.8.0_44 is our version of Java installed on our system.
2) To include all the JARs in the required folder of Hibernate installation folder,
in the classpath, while compiling this class. Our Hibernate version is 5.25.
And finally, after executing Hiber class, you will get the following output on the command prompt, shown below.
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.