top of page

What is Hiberanate - Hibernate Help

Hibernate :

Java Hibernate is an object-relational mapping tool(ORM) allowing the mapping of object-oriented models to relational databases for web applications by providing a framework. Mapping of entities in a Java class to tables created in a database and mapping from Java data types to SQL data types is one of the primary functions of Hibernate.


  • Hibernate handles all of the low-level SQL

  • Minimizes the amount of JDBC code you have to develop

  • Hibernate provides the Object Relational Mapping (ORM)

Object Relational mapping:

It is a mapping between java class and database table which is defined by the developer

CRUD using Hibernate:

We will see this in example

· Create Objects

· Read Objects

· Update Objects

· Delete Objects

Hibernate and JDBC:

Hibernate uses JDBC for all databases communications

Environment setup:


1. Java IDE: Preferred IntelliJ

2. Database server: Preferred MySQL

3. Hibernate JAR files and JDBC Driver

Set up:

1. Open MySQL and Open the root connection

2. Paste the below Query in MySQL editor

CREATE USER 'hbstudent'@'localhost' IDENTIFIED BY 'hbstudent';

GRANT ALL PRIVILEGES ON * . * TO 'hbstudent'@'localhost';

ALTER USER 'hbstudent'@'localhost' IDENTIFIED WITH mysql_native_password BY 'hbstudent';

3. And now run the query

4. Now close the root connection and create a new connection with username : “hbstudent” and password : “hbstudent”

5. Now open the new connection that you have created and paste the below Query in the editor and then run the query

CREATE DATABASE  IF NOT EXISTS `hb_student_tracker`;
USE `hb_student_tracker`;

CREATE TABLE `student` (
  `first_name` varchar(45) DEFAULT NULL,
  `last_name` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)

6. Open IntelliJ and create a new Java project with name “Hibernate-tutorial” you can use any name

7. Now in IntelliJ Go To File > Project Structure > Libraries and then click on ‘+’ icon and then Java

8. Now it will ask the location of the JAR files for that unzip the Hibernate file that you have downloaded

9. And inside that go to lib > required and then copy the path of required folder and paste it into the IntelliJ where it is asking for the JAR files

10.And click on apply

11.Now create a file named as “hibernate.cfg.xml” and paste the below code in this file and then copy this file and paste it inside the src foler in project

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"



        <!-- JDBC Database connection settings -->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&amp;serverTimezone=UTC</property>
        <property name="connection.username">hbstudent</property>
        <property name="connection.password">hbstudent</property>

        <!-- JDBC connection pool settings ... using built-in test pool -->
        <property name="connection.pool_size">1</property>

        <!-- Select our SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Echo the SQL to stdout -->
        <property name="show_sql">true</property>

      <!-- Set the current session context -->
      <property name="current_session_context_class">thread</property>


Now everything is set we will just write some code to test the connection

public class Main {

    public static void main(String[] args) {
        String jdbcUrl="jdbc:mysql://localhost:3306/hb_student_tracker?useSSl=false";
        String user ="hbstudent";
        String pass = "hbstudent";
        try {
            System.out.println("Connecting to database");
            Connection myConn= DriverManager.getConnection(jdbcUrl,user,pass);
            System.out.println("Connection Succesfull");

        catch(Exception e){



As we said that hibernate uses JDBC for the connection that’s why we are using the JDBC to check our connection


Connecting to database

Connection Succesfull

Now we will use hibernate for some real motivation

· Create a class called Student

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

public class Student {
       private int id;
       private String firstName;
       private String lastName;
       private String email;
       public Student() {

       public Student(String firstName, String lastName, String email) {
              this.firstName = firstName;
              this.lastName = lastName;
     = email;
       public int getId() {
              return id;

       public void setId(int 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;

       public String getEmail() {
              return email;

       public void setEmail(String email) {
     = email;

       public String toString() {
              return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";


Below mentioned notaions are used with class

@Entity: To let the program know that this is an entity that we are going to map to a database table

@Table: In which database table we are going to map the entity basically using the class name the program is able to find the table but it is good to provide the name explicitly for that use this syntax @Table (name=” table_name”)

Below mentioned notations are used with fields

@Id: TO tell the program that this field is a primary key for the database

@Column(name=”column_name”): To tell the database that this field should be mapped with this column_name

Create a class called

package com.hibernate.demo.entity;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class CreateStudent {

    public static void main(String[] args) {
        // Create Session factory
        SessionFactory seFact= new Configuration().configure("com/hibernate.cfg.xml")
        // Create Session
        Session session = seFact.getCurrentSession();

        try {

//create a student
            System.out.println("Creating Student Object...........");

            Student tempStudent= new Student("Ravi","nainwal","");

            System.out.println("Object Created .........."+tempStudent.toString());

            System.out.println("Begining the transaction..........");

//start transcation

            System.out.println("Saving the session..........");

//save the transaction

            System.out.println("Commiting the session..........");

//commit the transcation


        }finally {



Session Factory: Reads the hibernate config file creates session objects

· Heavy weight objects

· Created only once

Session: Wraps a JDBC connection

· Main object is used to save/retrieve objects

· Short lived objects

· Retrieved from session factory

Now run the main method from create student class and the output will be like below

Now to check that the data is stored in the database or not we will go to the MySQL and check the student table using “select * from student” query

And you will see this output

To retrieve the object from the data base add the below code in the class

System.out.println("Retrieving student object");

Student myStudent = session.get(Student.class,tempStudent.getId());

System.out.println("RETRIEVED DATA : "+ myStudent.toString());

When you will add this code the output will be

To update the values in the database we can use the setter method after the retrieval of the object see below code and add this code to

System.out.println("Update student object");

Student myStudent = session.get(Student.class, id);



To delete the values in the database add below code to the

System.out.println("Delete student object");

Student myStudent = session.get(Student.class, id);



We have done the basic functionalities using hibernate

How does CodersArts helps you ?

CodersArts provide :

  • Spring boot assignment Help

  • Help in development Projects

  • Mentorship from Experts Live 1:1 session

  • Course and Project completions

  • CourseWork help

bottom of page