How do I configure Hibernate with an H2 in-memory database?

Configuring Hibernate with an H2 in-memory database is quite straightforward. Below is a guide for configuring Hibernate with an H2 database in a Spring Boot or standalone Jakarta EE project.


Configuration for Hibernate with H2 in-memory database

1. Add Dependencies

Ensure you have the necessary dependencies in your project. For a Maven project, include the following in your pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

If you’re using Jakarta EE without Spring, you can directly include:

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

<!-- H2 Database -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

2. Configure application.yml or application.properties (if using Spring Boot)

For application.properties:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true

For application.yml:

spring:
  datasource:
    url: jdbc:h2:mem:testdb
    driver-class-name: org.h2.Driver
    username: sa
    password: 
  jpa:
    database-platform: org.hibernate.dialect.H2Dialect
  h2:
    console:
      enabled: true

3. Standalone Hibernate Configuration (Non-Spring)

Create a hibernate.cfg.xml file in the resources folder:

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- JDBC Database connection settings -->
        <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>

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

        <!-- Show SQL -->
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>

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

4. Entity Classes

Define your Hibernate/JPA entity classes. An example:

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 int age;

    // Getters and Setters
}

5. H2 Console (Optional, Spring Boot only)

To access the H2 console for debugging, enable it as shown in the Spring configuration. By default, the H2 console will be available at `http://localhost:8080/h2-console`. You can login with:

  • JDBC URL: jdbc:h2:mem:testdb
  • Username: sa
  • Password: (leave it blank)

6. Configure EntityManagerFactory or SessionFactory (Standalone)

For standalone Hibernate usage, you can programmatically configure a SessionFactory. An example:

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

public class HibernateUtil {

    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

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

After completing these steps, you will have a working setup with Hibernate and an H2 in-memory database. You can now run your application, and the database schema will be automatically created and dropped upon application startup/shutdown.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.