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.



Benefits:

  • 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:

Requirements:


1. Java IDE: Preferred IntelliJ

2. Database server: Preferred MySQL


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`;

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(45) DEFAULT NULL,
  `last_name` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

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"
       "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

 <hibernate-configuration>

    <session-factory>

        <!-- 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>
 
    </session-factory>

 </hibernate-configuration>

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

Main.java

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){
            e.printStackTrace();
        }

    }


}

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

Output:

Connecting to database

Connection Succesfull

Now we will use hibernate for some real motivation

· Create a class called Student


Student.java

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

@Entity
@Table(name="Student")
public class Student {
       @Id
       @Column(name="id") 
       private int id;
       @Column(name="first_name")
       private String firstName;
       @Column(name="last_name")
       private String lastName;
       @Column(name="email")
       private String email;
       
       
       public Student() {
       }


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

       
       public void setId(int id) {
              this.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) {
              this.email = email;
       }

       @Override
       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 CreateStudent.java

CreateStudent.java

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")
                .addAnnotatedClass(Student.class).buildSessionFactory();
        // Create Session
        Session session = seFact.getCurrentSession();


        try {

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

            Student tempStudent= new Student("Ravi","nainwal","RaviNainwal2@gmail.com");

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

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

//start transcation
            session.beginTransaction();

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

//save the transaction
            session.save(tempStudent);

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

//commit the transcation
            session.getTransaction().commit();

            System.out.println("Done..........");

        }finally {

            seFact.close();
        }
        //
    }




}

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

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

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

myStudent.setFirstName("Karan");

Output:

To delete the values in the database add below code to the createStudent.java

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

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

session.delete(myStudent);

Output:

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