Title here
Summary here
Hereβs a complete step-by-step guide for setting up our Student Management Application using Hibernate with H2 (In-Memory Database) from scratch.
We will set up Hibernate with an H2 in-memory database it helps to quickly test and understand Hibernate without needing an external database.
pom.xml
Modify your pom.xml
to include Hibernate and H2 database dependencies.
<dependencies>
<!-- Hibernate Core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>6.3.1.Final</version>
</dependency>
<!-- H2 Database (In-Memory) -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.1.214</version>
<scope>runtime</scope>
</dependency>
<!-- Hibernate Annotations -->
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>6.0.6.Final</version>
</dependency>
<!-- Logging Dependencies -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.7</version>
</dependency>
</dependencies>
β Why H2?
hibernate.cfg.xml
)Modify hibernate.cfg.xml
to use H2 instead of MySQL.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- H2 Database Connection -->
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.url">jdbc:h2:mem:testdb</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>
<!-- Hibernate Dialect for H2 -->
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<!-- Show SQL Queries in Console -->
<property name="hibernate.show_sql">true</property>
<!-- Automatically create tables -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Entity Mapping -->
<mapping class="com.example.model.Student"/>
</session-factory>
</hibernate-configuration>
β Key Changes
jdbc:h2:mem:testdb
β Uses H2 in-memory database.hibernate.dialect
β Uses H2Dialect.hibernate.hbm2ddl.auto=update
β Automatically creates tables.Student
Entityπ Student.java
(Entity class)
package com.example.model;
import jakarta.persistence.*;
@Entity
@Table(name = "students")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String firstName;
private String lastName;
private String email;
public Student() {}
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
// Getters and Setters
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 + "'}";
}
}
β Explanation
@Entity
β Marks this as a Hibernate entity.@Table(name = "students")
β Maps the class to students
table.@Id
β Primary Key.@GeneratedValue(strategy = GenerationType.IDENTITY)
β Auto-increment ID.π HibernateUtil.java
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 {
return new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("SessionFactory creation failed: " + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void shutdown() {
getSessionFactory().close();
}
}
β Why?
SessionFactory
.π Create Main.java
package com.example;
import com.example.model.Student;
import com.example.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class Main {
public static void main(String[] args) {
// Open Hibernate Session
Session session = HibernateUtil.getSessionFactory().openSession();
// Begin Transaction
Transaction transaction = session.beginTransaction();
// Create a Student Object
Student student = new Student("John", "Doe", "john.doe@example.com");
// Save the Student Object
session.save(student);
// Commit Transaction
transaction.commit();
// Close Session
session.close();
System.out.println("Student saved successfully!");
}
}
β Expected Output
Hibernate: create table students (id integer not null auto_increment, email varchar(255), first_name varchar(255), last_name varchar(255), primary key (id))
Hibernate: insert into students (email, first_name, last_name) values (?, ?, ?)
Student saved successfully!