Hibernate In-memory Database Example

In a developing environment, we need a quick database with less burden and if our database tables get modified frequently, then we have to use an in-memory database. There are many in-memory databases. We will see the h2 database with an example.

H2 is a relational database management system written in Java. It can be embedded in Java applications or run in the client-server model.

The features of the in-memory database are :

1). Very fast, open-source, JDBC API.
2). Browser-based Console application.
2). Small footprint: around 2 MB jar file size.
4). It can be used as a dependency or a single jar.
5). You don't want them to fail when some data/schema in the database changes.
6). An in-memory database is created when an application starts up and destroyed when the application is stopped.
7). It requires no project setup or infrastructure.
8). It needs zero Configuration.
9). It has zero Maintainance.
10). It is easy to use for Learning, POCs, and Unit Tests.
11). H2 also provides a web console to maintain the database.

Maven dependencies

<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.20.Final</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.200</version> </dependency>

hibernate.cfg.xml

<?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> <property name="hibernate.connection.driver_class">org.h2.Driver</property> <property name="hibernate.connection.url">jdbc:h2:mem:test</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.connection.password"></property> <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">create-drop</property> <mapping class="com.javacodestuffs.hibernate.entity.Student"></mapping> <property name="hibernate.current_session_context_class">thread</property> </session-factory> </hibernate-configuration>

package com.javacodestuffs.hibernate.util; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; public class HibernateUtil2 { private static SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { if (sessionFactory == null) { SessionFactory sf = new Configuration().configure().buildSessionFactory(); You can select a different XML configuration file using: SessionFactory sf = new Configuration() .configure("hibernate.cfg.xml") .buildSessionFactory(); } return sessionFactory; } catch (Exception ex) { System.out.println("Execption occured during session factory creation"+ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { getSessionFactory().close(); } }

Student.java

package com.javacodestuffs.hibernate.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; @Entity @Table(name = "Student", uniqueConstraints = { @UniqueConstraint(columnNames = "roll_number"), @UniqueConstraint(columnNames = "phone") }) public class Student implements Serializable { private static final long serialVersionUID = -1798070786993154676L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "roll_number", unique = true, nullable = false) private Integer rollNumber; @Column(name = "first_name", unique = false, nullable = false, length = 100) private String firstName; @Column(name = "last_name", unique = false, nullable = false, length = 100) private String lastName; @Column(name = "phone", unique = true, nullable = false, length = 100) private String phone; @Column(name = "student_class", unique = true, nullable = false, length = 100) private String studClass; //@Getters //@Setters }

To run the application we have the main class

import org.hibernate.Session; import com.javacodestuffs.hibernate.entity.Student; public class SeesionFactoryTest { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); //Add new Student object Student student = new Student(); student.setPhone("1234567890"); student.setStudClass("9th"); student.setAddress("Flat no 312,Chandani Chowk Pune - 411038"); student.setFirstName("Bala"); student.setLastName("K"); session.save(student); session.getTransaction().commit(); HibernateUtil.shutdown(); } }

In this article, we have seen Hibernate In-memory Database Example  with examples. All source code in the article can be found in the GitHub repository.