Hibernate is a powerful, high-performance Object-Relational Mapping (ORM) framework for Java. It simplifies the development of Java applications to interact with databases by mapping Java classes to database tables. This module will cover the basics of Hibernate, its configuration, and how to use it to perform CRUD (Create, Read, Update, Delete) operations.

Key Concepts

  1. ORM (Object-Relational Mapping): A technique that allows you to query and manipulate data from a database using an object-oriented paradigm.
  2. Hibernate Configuration: Setting up Hibernate to connect to a database.
  3. Hibernate Annotations: Using annotations to map Java classes to database tables.
  4. Session Factory: A factory for Session objects.
  5. Session: A single-threaded, short-lived object representing a conversation between the application and the database.
  6. Transaction: A unit of work that is either completely performed or completely undone.
  7. Query: An object-oriented representation of a database query.

Setting Up Hibernate

Step 1: Add Hibernate Dependencies

To use Hibernate, you need to add the necessary dependencies to your project. If you are using Maven, add the following dependencies to your pom.xml:

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.4.30.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.4.30.Final</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.23</version>
    </dependency>
</dependencies>

Step 2: Create Hibernate Configuration File

Create a hibernate.cfg.xml file in the src/main/resources directory:

<!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</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: Create Entity Classes

Create a simple entity class, Student, and annotate it with Hibernate annotations:

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

@Entity
@Table(name = "students")
public class Student {
    @Id
    private int id;
    private String name;
    private String email;

    // Getters and Setters
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Step 4: Create Hibernate Utility Class

Create a utility class to manage the Hibernate SessionFactory:

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) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        getSessionFactory().close();
    }
}

Performing CRUD Operations

Create Operation

import org.hibernate.Session;
import org.hibernate.Transaction;

public class CreateStudent {
    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            transaction = session.beginTransaction();
            Student student = new Student();
            student.setId(1);
            student.setName("John Doe");
            student.setEmail("[email protected]");
            session.save(student);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

Read Operation

import org.hibernate.Session;

public class ReadStudent {
    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();

        try {
            Student student = session.get(Student.class, 1);
            System.out.println("ID: " + student.getId());
            System.out.println("Name: " + student.getName());
            System.out.println("Email: " + student.getEmail());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

Update Operation

import org.hibernate.Session;
import org.hibernate.Transaction;

public class UpdateStudent {
    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            transaction = session.beginTransaction();
            Student student = session.get(Student.class, 1);
            student.setEmail("[email protected]");
            session.update(student);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

Delete Operation

import org.hibernate.Session;
import org.hibernate.Transaction;

public class DeleteStudent {
    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            transaction = session.beginTransaction();
            Student student = session.get(Student.class, 1);
            session.delete(student);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

Practical Exercises

Exercise 1: Create a New Entity

  1. Create a new entity class Course with fields id, name, and description.
  2. Annotate the class with Hibernate annotations.
  3. Write a program to save a new Course object to the database.

Exercise 2: Perform CRUD Operations

  1. Write programs to perform CRUD operations on the Course entity.
  2. Ensure that you handle transactions and exceptions properly.

Solutions

Solution to Exercise 1

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

@Entity
@Table(name = "courses")
public class Course {
    @Id
    private int id;
    private String name;
    private String description;

    // Getters and Setters
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

Solution to Exercise 2

import org.hibernate.Session;
import org.hibernate.Transaction;

public class CourseCRUD {
    public static void main(String[] args) {
        // Create
        createCourse(1, "Java Programming", "Learn Java from scratch");

        // Read
        readCourse(1);

        // Update
        updateCourse(1, "Advanced Java Programming");

        // Delete
        deleteCourse(1);
    }

    public static void createCourse(int id, String name, String description) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            transaction = session.beginTransaction();
            Course course = new Course();
            course.setId(id);
            course.setName(name);
            course.setDescription(description);
            session.save(course);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    public static void readCourse(int id) {
        Session session = HibernateUtil.getSessionFactory().openSession();

        try {
            Course course = session.get(Course.class, id);
            System.out.println("ID: " + course.getId());
            System.out.println("Name: " + course.getName());
            System.out.println("Description: " + course.getDescription());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    public static void updateCourse(int id, String newName) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            transaction = session.beginTransaction();
            Course course = session.get(Course.class, id);
            course.setName(newName);
            session.update(course);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    public static void deleteCourse(int id) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            transaction = session.beginTransaction();
            Course course = session.get(Course.class, id);
            session.delete(course);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

Conclusion

In this module, you learned the basics of Hibernate, including how to set it up, configure it, and perform CRUD operations. Hibernate simplifies database interactions in Java applications by providing an ORM framework. You also practiced creating and manipulating entities using Hibernate. In the next module, you will learn about building real-world applications using Java frameworks and libraries.

Java Programming Course

Module 1: Introduction to Java

Module 2: Control Flow

Module 3: Object-Oriented Programming

Module 4: Advanced Object-Oriented Programming

Module 5: Data Structures and Collections

Module 6: Exception Handling

Module 7: File I/O

Module 8: Multithreading and Concurrency

Module 9: Networking

Module 10: Advanced Topics

Module 11: Java Frameworks and Libraries

Module 12: Building Real-World Applications

© Copyright 2024. All rights reserved