Hibernate MySQL Database Tutorial

This tutorial will guide you through setting up Hibernate with a MySQL database and Java 21, creating a simple application that demonstrates basic CRUD operations. 

Introduction

Hibernate is an Object-Relational Mapping (ORM) framework that simplifies database interactions in Java applications. By mapping Java classes to database tables, Hibernate allows developers to interact with databases using standard Java objects, reducing the need for manual SQL queries.

In this tutorial, we will:

  1. Set up a Maven project with Hibernate and MySQL dependencies.
  2. Configure Hibernate to connect to a MySQL database.
  3. Create an entity class that maps to a database table.
  4. Implement basic CRUD operations using Hibernate.
  5. Write a main method to perform these CRUD operations and print sample output.

Step 1: Set Up Your Project

1.1 Create a Maven Project

Open your IDE and create a new Maven project.

1.2 Add Dependencies

Update your pom.xml file to include the necessary dependencies for Hibernate and MySQL.

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>hibernate-mysql-tutorial</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- Hibernate ORM -->
        <dependency>
            <groupId>org.hibernate.orm</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>6.4.0.Final</version>
        </dependency>

        <!-- MySQL Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.33</version>
        </dependency>

        <!-- JUnit for testing -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.10.0</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>5.10.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.10.1</version>
                <configuration>
                    <source>21</source>
                    <target>21</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

1.3 Configure Hibernate

Create a file named hibernate.cfg.xml in the src/main/resources directory to configure Hibernate.

<!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/hibernate_db</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.show_sql">true</property>
    </session-factory>
</hibernate-configuration>

Replace hibernate_db with your database name, and root and password with your MySQL credentials.

Step 2: Create the Entity Class

Create an entity class User that will be mapped to a table in the database.

package com.example.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;

    // Getters and setters
    public Long getId() {
        return id;
    }

    public void setId(Long 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 3: Create the Hibernate Utility Class

Create a utility class HibernateUtil to manage the Hibernate SessionFactory.

package com.example.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }
}

Step 4: Perform CRUD Operations

4.1 Create a User

package com.example.main;

import com.example.entity.User;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class CreateUser {
    public static void createUser() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            transaction = session.beginTransaction();
            User user = new User();
            user.setName("Ramesh Fadatare");
            user.setEmail("[email protected]");
            session.save(user);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

4.2 Read a User

package com.example.main;

import com.example.entity.User;
import com.example.util.HibernateUtil;
import org.hibernate.Session;

public class ReadUser {
    public static void readUser(Long userId) {
        Session session = HibernateUtil.getSessionFactory().openSession();

        try {
            User user = session.get(User.class, userId);
            if (user != null) {
                System.out.println("User details: " + user.getName() + ", " + user.getEmail());
            } else {
                System.out.println("User not found!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

4.3 Update a User

package com.example.main;

import com.example.entity.User;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class UpdateUser {
    public static void updateUser(Long userId, String newName, String newEmail) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            User user = session.get(User.class, userId);
            if (user != null) {
                transaction = session.beginTransaction();
                user.setName(newName);
                user.setEmail(newEmail);
                session.update(user);
                transaction.commit();
            } else {
                System.out.println("User not found!");
            }
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

4.4 Delete a User

package com.example.main;

import com.example.entity.User;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class DeleteUser {
    public static void deleteUser(Long userId) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction transaction = null;

        try {
            User user = session.get(User.class, userId);
            if (user != null) {
                transaction = session.beginTransaction();
                session.delete(user);
                transaction.commit();
            } else {
                System.out.println("User not found!");
            }
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

Step 5: Write the Main

Method to Call CRUD Operations

package com.example.main;

public class MainApp {
    public static void main(String[] args) {
        // Create a new user
        CreateUser.createUser();
        System.out.println("User created!");

        // Read the created user
        ReadUser.readUser(1L);

        // Update the created user
        UpdateUser.updateUser(1L, "Ramesh Updated", "[email protected]");
        System.out.println("User updated!");

        // Read the updated user
        ReadUser.readUser(1L);

        // Delete the user
        DeleteUser.deleteUser(1L);
        System.out.println("User deleted!");

        // Try to read the deleted user
        ReadUser.readUser(1L);
    }
}

Sample Output

User created!
User details: Ramesh Fadatare, [email protected]
User updated!
User details: Ramesh Updated, [email protected]
User deleted!
User not found!

Conclusion

In this tutorial, we have successfully set up a Hibernate project using Hibernate 6.4, MySQL 8.0, and Java 21. We created an entity class and configured Hibernate to connect to a MySQL database. We performed basic CRUD operations (Create, Read, Update, Delete) to demonstrate how to interact with the database using Hibernate. This guide provides a solid foundation for building more complex Hibernate-based applications.

Comments