Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc. In this article, let us see a Hibernate Example using XML along with MySQL database in eclipse.
Requirements:
- Eclipse
- Maven
- Hibernate
- MySQL
- JDK 6 onwards
Example
As we are going to check about the maven kind of project, let us see the pom.xml
XML
< modelVersion >4.0.0</ modelVersion >
< groupId >com.geeksforgeeks</ groupId >
< artifactId >HibernateSampleExample</ artifactId >
< packaging >jar</ packaging >
< version >1.0-SNAPSHOT</ version >
< name >HibernateSampleExample</ name >
< dependencies >
< dependency >
< groupId >junit</ groupId >
< artifactId >junit</ artifactId >
< version >3.8.1</ version >
< scope >test</ scope >
</ dependency >
< dependency >
< groupId >org.hibernate</ groupId >
< artifactId >hibernate-core</ artifactId >
< version >4.3.5.Final</ version >
</ dependency >
< dependency >
< groupId >mysql</ groupId >
< artifactId >mysql-connector-java</ artifactId >
< version >5.1.6</ version >
</ dependency >
</ dependencies >
< build >
< pluginManagement >
< plugins >
< plugin >
< groupId >org.apache.maven.plugins</ groupId >
< artifactId >maven-compiler-plugin</ artifactId >
< version >3.1</ version >
< configuration >
< source >1.7</ source >
< target >1.7</ target >
</ configuration >
</ plugin >
</ plugins >
</ pluginManagement >
</ build >
</ project >
|
For Hibernate, we should keep the details on the “hibernate.cfg.xml” file which specifies what kind of database and its credentials, its required drivers, etc., are placed. In this example, we are going to use MySQL and hence
hibernate.connection.driver_class = com.mysql.jdbc.Driver
The advantage of hibernate is it will create a mapping of a database table with a Java application class file. That is also specified in an XML file. Let us create a table in MySQL first
-- Here "geeksforgeeks" is the name of the database
-- "GeekUserDetails" is the name of the table
-- geekUserId is the Primary Key
CREATE TABLE geeksforgeeks.GeekUserDetails (
geekUserId INT (5) NOT NULL,
geekUsername VARCHAR (20) NOT NULL,
numberOfPosts INT(5) NOT NULL,
CREATED_BY VARCHAR (20) NOT NULL,
CREATED_DATE DATE NOT NULL,
PRIMARY KEY ( geekUserId )
)
Let us see the mapping file in Hibernate. i.e. each and every column has to be mapped between a table and class. First, let us create POJO(Model class) in Java for that
Java
import java.util.Date;
public class GeekUserDetails {
private int geekUserId;
private String geekUsername;
private int numberOfPosts;
public int getNumberOfPosts() { return numberOfPosts; }
public int getGeekUserId() { return geekUserId; }
public void setGeekUserId( int geekUserId)
{
this .geekUserId = geekUserId;
}
public String getGeekUsername() { return geekUsername; }
public void setGeekUsername(String geekUsername)
{
this .geekUsername = geekUsername;
}
public void setNumberOfPosts( int numberOfPosts)
{
this .numberOfPosts = numberOfPosts;
}
private String createdBy;
private Date createdDate;
public String getCreatedBy() { return createdBy; }
public void setCreatedBy(String createdBy)
{
this .createdBy = createdBy;
}
public Date getCreatedDate() { return createdDate; }
public void setCreatedDate(Date createdDate)
{
this .createdDate = createdDate;
}
}
|
Now, the mapping file related to the POJO file.
resources/geekuser.hbm.xml
XML
<? xml version = "1.0" encoding = "UTF-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
< hibernate-mapping >
< class name = "com.geeksforgeeks.GeekUserDetails" table = "GeekUserDetails" >
< id name = "geekUserId" type = "int" column = "geekUserId" >
< generator class = "assigned" />
</ id >
< property name = "geekUsername" >
< column name = "geekUsername" />
</ property >
< property name = "numberOfPosts" type = "int" >
< column name = "numberOfPosts" />
</ property >
< property name = "createdBy" >
< column name = "CREATED_BY" />
</ property >
< property name = "createdDate" type = "date" >
< column name = "CREATED_DATE" />
</ property >
</ class >
</ hibernate-mapping >
|
Now, let us see the main configuration file
resources/hibernate.cfg.xml
XML
<? xml version = "1.0" encoding = "utf-8" ?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
< hibernate-configuration >
< session-factory >
< property name = "hibernate.connection.driver_class" >com.mysql.jdbc.Driver</ property >
< property name = "hibernate.connection.username" >root</ property >
< property name = "hibernate.connection.password" >XXXX</ property >
< property name = "hibernate.dialect" >org.hibernate.dialect.MySQLDialect</ property >
< property name = "show_sql" >true</ property >
< property name = "format_sql" >true</ property >
< property name = "hbm2ddl.auto" >update </ property >
< mapping resource = "geekuser.hbm.xml" />
</ session-factory >
</ hibernate-configuration >
|
After creating the mapping between the MySQL table and Java class via “geekuser.hbm.xml” and “hibernate.cfg.xml”, let us try to do a simple insertion of a record in the table Let us try to run that via a java application file. We need to look upon certain files like HibernateUtil.java. We need to create the SessionFactory from hibernate.cfg.xml. Hence first all the entries in this XML have to be satisfied before entering into the main code. Otherwise need to provide the required code to throw the exception.
Java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory
= buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try {
return new Configuration()
.configure()
.buildSessionFactory();
}
catch (Throwable ex) {
System.err.println(
"SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void shutdown()
{
getSessionFactory().close();
}
}
|
GeekUserDetailsTest.java -> Session is getting created by using HibernateUtil.java. Hibernate SessionFactory has three methods namely getCurrentSession(), openSession() and openStatelessSession(). In our code, we are using openSession(). If it is not given, we will get into exception as Exception in thread “main” org.hibernate.HibernateException: No CurrentSessionContext configured! For openSession(), it will always open a new session and it has to be closed
Java
import java.util.Date;
import org.hibernate.Session;
public class GeekUserDetailsTest {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
GeekUserDetails geekUser = new GeekUserDetails();
geekUser.setGeekUserId( 1 );
geekUser.setGeekUsername( "GeekUser1" );
geekUser.setNumberOfPosts( 100 );
geekUser.setCreatedBy( "GeekUser1" );
geekUser.setCreatedDate( new Date());
session.save(geekUser);
session.getTransaction().commit();
session.close();
}
}
|
Once this file is run as a “Java application”, we can able to see a record is inserted into the “GeekUserDetails” table

Video explanation about the code:
Conclusion
Using hibernate.cfg.xml (main XML file defining the database JDBC details, SQL dialects, etc.,) a mapping file that maps the columns of a table and a POJO class. (Here it is geekuser.hbm.xml) we can do all the CRUD operations easily in Hibernate.
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
14 Feb, 2022
Like Article
Save Article