Hibernate Maven Example: Step-by-Step Tutorial

In this tutorial, we'll walk through how to set up a basic Hibernate project using Maven. Hibernate is a powerful ORM (Object-Relational Mapping) framework that simplifies database interactions in Java applications. We'll create a simple example to demonstrate how to configure Hibernate, create an entity, and perform basic CRUD operations.

Prerequisites

Before we start, ensure you have the following:

  • Java Development Kit (JDK) installed
  • Apache Maven installed
  • An IDE (Integrated Development Environment) like IntelliJ IDEA or Eclipse

Step 1: Setting Up the Project

Create a Maven Project

  1. Open your IDE and create a new Maven project.
  2. Define the project coordinates (groupId, artifactId, version) in the pom.xml file.

Project Structure

Your project structure should look like this:

hibernate-maven-example
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── example
│   │   │           └── hibernate
│   │   │               ├── App.java
│   │   │               ├── model
│   │   │               │   └── Student.java
│   │   │               ├── util
│   │   │               │   └── HibernateUtil.java
│   │   │               └── dao
│   │   │                   └── StudentDao.java
│   │   └── resources
│   │       └── hibernate.cfg.xml
└── pom.xml

Step 2: Adding Dependencies

Add the necessary dependencies for Hibernate and H2 database (or any other database of your choice) in the pom.xml file.

pom.xml

<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-maven-example</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- Hibernate Core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>6.1.6.Final</version>
        </dependency>

        <!-- H2 Database -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>2.1.214</version>
        </dependency>

        <!-- JUnit for testing -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

Step 3: Configuring Hibernate

Create the Hibernate configuration file (hibernate.cfg.xml) in the src/main/resources directory.

hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="hibernate.connection.driver_class">org.h2.Driver</property>
        <property name="hibernate.connection.url">jdbc:h2:~/test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</property>
        <property name="hibernate.connection.username">sa</property>
        <property name="hibernate.connection.password"></property>

        <!-- JDBC connection pool settings -->
        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">20</property>
        <property name="hibernate.c3p0.timeout">300</property>
        <property name="hibernate.c3p0.max_statements">50</property>
        <property name="hibernate.c3p0.idle_test_period">3000</property>

        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="hibernate.current_session_context_class">thread</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="hibernate.show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hibernate.hbm2ddl.auto">update</property>

        <!-- Names the annotated entity class -->
        <mapping class="com.example.hibernate.model.Student"/>
    </session-factory>
</hibernate-configuration>

Step 4: Creating the Entity Class

Create an Entity class Student in the com.example.hibernate.model package.

Student.java

package com.example.hibernate.model;

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

@Entity
public class Student {

    @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 5: Creating the Hibernate Utility Class

Create a utility class HibernateUtil to manage the Hibernate SessionFactory.

HibernateUtil.java

package com.example.hibernate.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

    private static SessionFactory sessionFactory;

    static {
        try {
            Configuration configuration = new Configuration();
            configuration.configure("hibernate.cfg.xml");
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Step 6: Creating the DAO Class

Create a DAO (Data Access Object) class StudentDao to perform CRUD operations.

StudentDao.java

package com.example.hibernate.dao;

import com.example.hibernate.model.Student;
import com.example.hibernate.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.List;

public class StudentDao {

    public void saveStudent(Student student) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();
            session.save(student);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public void updateStudent(Student student) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();
            session.update(student);
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

    public Student getStudentById(Long id) {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            return session.get(Student.class, id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public List<Student> getAllStudents() {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            return session.createQuery("from Student", Student.class).list();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void deleteStudent(Long id) {
        Transaction transaction = null;
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            transaction = session.beginTransaction();
            Student student = session.get(Student.class, id);
            if (student != null) {
                session.delete(student);
            }
            transaction.commit();
        } catch (Exception e) {
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }
}

Step 7: Creating the Main Application Class

Create a main application class App to test the CRUD operations.

App.java

package com.example.hibernate;

import com.example

.hibernate.dao.StudentDao;
import com.example.hibernate.model.Student;

public class App {

    public static void main(String[] args) {
        StudentDao studentDao = new StudentDao();

        // Create student
        Student student = new Student();
        student.setName("John Doe");
        student.setEmail("john.doe@example.com");
        studentDao.saveStudent(student);

        // Update student
        student.setName("Jane Doe");
        studentDao.updateStudent(student);

        // Get student by ID
        Student retrievedStudent = studentDao.getStudentById(student.getId());
        System.out.println("Retrieved Student: " + retrievedStudent.getName());

        // Get all students
        studentDao.getAllStudents().forEach(s -> System.out.println(s.getName()));

        // Delete student
        studentDao.deleteStudent(student.getId());
    }
}

Step 8: Running the Application

To run the application, execute the App class. This will perform the following operations:

  1. Create a new student.
  2. Update the student's name.
  3. Retrieve the student by ID and print the student's name.
  4. Retrieve all students and print their names.
  5. Delete the student.

Conclusion

In this tutorial, we have walked through setting up a basic Hibernate project using Maven. We configured Hibernate, created an entity class, and performed basic CRUD operations. Hibernate simplifies database interactions in Java applications, making it easier to manage complex data models. By following this tutorial, you should now have a good understanding of how to use Hibernate in a Maven-based project.


Comments