Open In App
Related Articles

Hibernate Example using XML in Eclipse

Improve Article
Save Article
Like Article

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.


  • Eclipse 
  • Maven
  • Hibernate
  • MySQL
  • JDK 6 onwards


As we are going to check about the maven kind of project, let us see the pom.xml



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,
 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


import java.util.Date;
// We can check that column name in "GeekUserDetails" is
// matching with each and every field here. It is always good
// to have the same column name and field name here
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.



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
      <!-- com.geeksforgeeks.GeekUserDetails 
         is the name of the java class
          GeekUserDetails is the name of the table -->
    <class name="com.geeksforgeeks.GeekUserDetails" table="GeekUserDetails">
        <id name="geekUserId" type="int" column="geekUserId">
            <generator class="assigned"/>
        <property name="geekUsername">
            <column name="geekUsername"/>
        <property name="numberOfPosts" type = "int">
            <column name="numberOfPosts"/>
        <property name="createdBy">
            <column name="CREATED_BY"/>
        <property name="createdDate" type="date">
            <column name="CREATED_DATE"/>

Now, let us see the main configuration file



<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<!-- Main configuration file -->
        <!-- As we are connecting MySQL, com.mysql.jdbc.
             Driver is required(JDBC driver class) -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
          <!-- Here geeksforgeeks is the name of the database 
             that we are connecting(JDBC URL) -->
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/geeksforgeeks</property>
          <!-- Username to connect to MySQL -->
        <property name="hibernate.connection.username">root</property>
          <!-- Password to connect to MySQL, Provide your correct password -->
        <property name="hibernate.connection.password">XXXX</property>
          <!-- Dialect required between hibernate and MySQL -->
         <!-- This property makes Hibernate generate the
              appropriate SQL for MySQL here -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <property name="">update </property>
          <!-- We need to provide the exact mapping file 
             which we have created earlier -->
        <mapping resource="geekuser.hbm.xml" />

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 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.


import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
    private static final SessionFactory sessionFactory
        = buildSessionFactory();
    private static SessionFactory buildSessionFactory()
        try {
            // We need to create the SessionFactory from
            // hibernate.cfg.xml
            return new Configuration()
        catch (Throwable ex) {
            // Make sure you log the exception, as it might
            // be swallowed
            // In case of any exception, it has to be
            // indicated here
                "SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
    public static SessionFactory getSessionFactory()
        return sessionFactory;
    public static void shutdown()
        // Close caches and connection pools
} -> Session is getting created by using 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


import java.util.Date;
import org.hibernate.Session;
public class GeekUserDetailsTest {
    public static void main(String[] args) {
        // open the session
        Session session = HibernateUtil.getSessionFactory().openSession();
        // For doing any CRUD operation, 
        // let us start a transaction
        // Create an object of GeekUserDetails
        GeekUserDetails geekUser = new GeekUserDetails();
        // Set all the details required 
        // to insert into the table
        geekUser.setCreatedDate(new Date());
        // Just a save statement is enough which 
        // automatically creates an insert statement;
        // commit will help to complete
        // the changes in the table
        // close the session

Once this file is run as a “Java application”, we can able to see  a record is inserted into the “GeekUserDetails” table

Data is inserted via hibernate session

Video explanation about the code:


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
Similar Reads
Complete Tutorials