Hibernate 5 + RDBMS with example

Hello everyone, Today we are giving an example of testing your hibernate code using HSQLDB in-memory database.

Hibernate is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database. Object-relational mapping (ORM) is a programming technique for converting data between incompatible type systems in object-oriented programming languages.

HSQLDB is an open-source lightweight Java database. It can be embedded in Java applications. HSQLDB database can be configured to run as an in-memory database, which designates that data will not persist on the disk.

Hibernate HSQLDB In-Memory Database Example

Directory Structure

Maven Dependencies[pom.xml]

<project xmlns="http://maven.apache.org/POM/4.0.0"
<description>Demo </description>
<!-- https://mvnrepository.com/artifact/org.hsqldb/hsqldb -->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate
-core -->

Creating the JPA Entity Class/Persistent class [UserEntity.class]

Let's create a UserEntity persistent class that is mapped to a database "user" table.

package com.knf.demo.hibernate.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "user")
public class UserEntity {

@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column(name = "email")
private String email;

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;

public UserEntity(int id, String firstName, String lastName, String email) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;

public UserEntity() {

public String toString() {
return "UserEntity [id=" + id + ", firstName=" +
firstName + ", lastName=" + lastName + ", email=" + email
+ "]";


Create a Hibernate configuration file - hibernate.cfg.xml

hibernate.cfg.xml file contains database related configurations and session related configurations. Database configuration includes jdbc connection url, DB user credentials, driver class and hibernate dialect.

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<property name="hibernate.archive.autodetection">class,hbm</property>
<property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect
<property name="hibernate.show_sql">true</property>
<property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.url">jdbc:hsqldb:mem:testdb
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping class="com.knf.demo.hibernate.entity.UserEntity"></mapping>

Create a Hibernate utility Class[HibernateUtil.class]

Engender a helper class to bootstrap hibernate SessionFactory. In most Hibernate applications, the SessionFactory should be instantiated once during application initialization. The single instance should then be utilized by all code in a particular process, and any Session should be engendered utilizing this single SessionFactory.The SessionFactory is thread-safe and can be shared, a Session is a single-threaded object.

package com.knf.demo.hibernate.util;

import org.hibernate.HibernateException;
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 HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();

private static SessionFactory buildSessionFactory() {
try {
StandardServiceRegistry standardRegistry =
new StandardServiceRegistryBuilder()
Metadata metadata = new MetadataSources(standardRegistry).
return metadata.getSessionFactoryBuilder().build();

} catch (HibernateException he) {
System.out.println("Session Factory creation failure");
throw he;

public static SessionFactory getSessionFactory() {
return sessionFactory;

public static void shutdown() {

Create the main App class[Hibernate5DemoApplication.class]

package com.knf.demo;

import java.util.List;

import org.hibernate.Session;

import com.knf.demo.hibernate.entity.UserEntity;
import com.knf.demo.hibernate.util.HibernateUtil;

public class Hibernate5DemoApplication {

public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
// Add new User object
UserEntity user = new UserEntity();
// Add new User object
UserEntity user1 = new UserEntity();
List<UserEntity> userList = session.createQuery
("SELECT a FROM UserEntity a", UserEntity.class).getResultList();
System.out.println("List of users:" + userList);


Execute the Application

Console Output

Popular posts from this blog

Spring boot video streaming example-HTML5

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

DataTable-Pagination example with Spring boot, jQuery and ajax

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Node JS mini projects with source code - free download

Spring boot web project free download:User Registration System

Java - Blowfish Encryption and decryption Example