Hibernate Framework in Java

  • By Shital Chauhan
  • July 22, 2024
  • JAVA Programming
Hibernate Framework in Java

Hibernate Framework in Java

The framework is a collection of interfaces, classes, and methods in java which gives the RAD (Rapid Application Development). Hibernate is an ORM (Object Relational Mapping) framework that simplifies the database transaction of Java applications. It’s also known as a database framework. It simplifies the interaction of Java applications with databases by mapping classes into relational databases. Explore the Hibernate Framework in Java for efficient ORM, boosting productivity and simplifying complex data mappings in database management.

It is an open-source, lightweight, ORM (Object Relational Mapping) tool. Hibernate implements the specifications of JPA (Java Persistence API) for data persistence.

 

Why Use Hibernate:

  1. Simplifies Database Interactions: Hibernate abstracts the complexities of database interactions, allowing developers to focus on the business logic.
  2. Automatic Table Creation: Hibernate can automatically create and update database tables based on Java class structures.
  3. HQL (Hibernate Query Language): Hibernate provides its own query language, HQL, which is similar to SQL but works with Hibernate’s object-oriented model.
  4. Cache Mechanism: Hibernate includes a powerful caching mechanism that improves performance by reducing the number of database hits.
  5. Lazy Loading: Hibernate supports lazy loading, fetching related data only when it is needed, which improves performance.

 

Implementation of Hibernate application with CRUD operation

Step 1: Setting Up the Development Environment

Before you start using Hibernate, you need to set up your development environment.

  1. Install Java Development Kit (JDK): Ensure that JDK is installed on your system. Hibernate requires Java to run.
  2. Set Up a Database: You can use any relational database such as MySQL, PostgreSQL, Oracle, etc. For this example, we’ll use MySQL.
  3. Add Hibernate Dependencies: You need to add Hibernate dependencies to your project. If you are using Maven, add the following dependencies to your pom.xml:

 

<dependency>

         <groupId>org.hibernate</groupId>

         <artifactId>hibernate-core</artifactId>

         <version>5.7.7.Final</version>

</dependency>

<dependency>

                 <groupId>mysql</groupId>

                 <artifactId>mysql-connector-java</artifactId>

                 <version>8.0.33</version>

</dependency>

 

Step 2: Configuring Hibernate

Hibernate requires configuration to connect to the database. Create a hibernate.cfg.xml file in your project’s src/main/resources directory:

 

 Provide the Configuration information to hibernate with hibernate.cfg.xml file and here we are using the annotation-based approach to implement the hibernate application. 

 

<!DOCTYPE hibernate-configuration PUBLIC

        “-//Hibernate/Hibernate Configuration DTD 3.0//EN”

        “http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”>

<hibernate-configuration>

    <session-factory>

        <property name=”hibernate.dialect”>org.hibernate.dialect.MySQLDialect</property>

        <property name=”hibernate.connection.driver_class”>com.mysql.cj.jdbc.Driver</property>

        <property name=”hibernate.connection.url”>jdbc:mysql://localhost:3306/your_database_name</property>

        <property name=”hibernate.connection.username”>your_username</property>

        <property name=”hibernate.connection.password”>your_password</property>

        <property name=”hibernate.hbm2ddl.auto”>update</property>

        <property name=”hibernate.show_sql”>true</property>

        <property name=”hibernate.format_sql”>true</property>

    </session-factory>

</hibernate-configuration>

 

Step 3: Creating Entity Classes

An entity class in Hibernate represents a table in the database. We provide the mapping information to hibernate via an annotation approach by using annotations like @Entity, @Id, @Column, @Table, etc.

 

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Table;

@Entity

@Table(name = “employees”)

public class Employee {

    @Id

    private int id;

    private String firstName;

    private String lastName; private String email; // Getters and setters}

 

For Free, Demo classes Call: 020-71173125

Registration Link: Java Classes in Pune!

 

Step 4: Writing Hibernate Utility Class

To simplify the creation of SessionFactory, create a Hibernate utility class:

import org. hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class HibernateUtil {

 private static SessionFactory sessionFactory;

static {

        try {

            sessionFactory = new Configuration().configure().buildSessionFactory();

        } catch (Throwable ex) {

            throw new ExceptionInInitializerError(ex);

        }

    }

 public static SessionFactory getSessionFactory() {

        return sessionFactory;

    }

}

Step 5: Performing CRUD Operations

Now, you can use Hibernate to perform CRUD (Create, Read, Update, Delete) operations. Here is an example:

import org.hibernate.Session;

import org.hibernate.Transaction;

 

public class Main {

    public static void main(String[] args) {

        // Create

        Employee employee = new Employee();

        employee.setId(1);

        employee.setFirstName(“Mohan”);

        employee.setLastName(“Das”);

        employee.setEmail(“mohan.das@example.com”);

       Session session = HibernateUtil.getSessionFactory().openSession();

        Transaction transaction = session.beginTransaction();

        session.save(employee);

        transaction.commit();

        session.close();

 

      

     // Read

        session = HibernateUtil.getSessionFactory().openSession();

        Employee retrievedEmployee = session.get(Employee.class, 1);

        System.out.println(retrievedEmployee.getFirstName());

        session.close();

 

        // Update

        session = HibernateUtil.getSessionFactory().openSession();

        transaction = session.beginTransaction();

        retrievedEmployee.setEmail(“john.d.new@example.com”);

        session.update(retrievedEmployee);

        transaction.commit();

        session.close();

       // Delete

        session = HibernateUtil.getSessionFactory().openSession();

        transaction = session.beginTransaction();

        session.delete(retrievedEmployee);

        transaction.commit();

        session.close();

    }

}

Conclusion

Hibernate is a robust and flexible framework that simplifies database operations in Java applications. By mapping Java objects to database tables, it allows developers to interact with databases in an object-oriented manner. 

 

Note: Do watch our latest video: Click Here

Author:-

Shital Chauhan
Call the Trainer and Book your free demo class for Java now!!!

© Copyright 2020 | SevenMentor Pvt Ltd.

Submit Comment

Your email address will not be published. Required fields are marked *

*
*