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"
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>hibernate5_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>hibernate5_demo</name>
<description>Demo </description>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.hsqldb/hsqldb -->
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate
-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.7.Final</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

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;

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

@Id
@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) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}

public UserEntity() {
super();
}

@Override
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"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.archive.autodetection">class,hbm</property>
<property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect
</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver
</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.url">jdbc:hsqldb:mem:testdb
</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping class="com.knf.demo.hibernate.entity.UserEntity"></mapping>
</session-factory>
</hibernate-configuration>

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()
.configure("hibernate.cfg.xml").build();
Metadata metadata = new MetadataSources(standardRegistry).
getMetadataBuilder().build();
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() {
getSessionFactory().close();
}
}

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();
session.beginTransaction();
// Add new User object
UserEntity user = new UserEntity();
user.setId(1);
user.setEmail("dummyuser@mail.com");
user.setFirstName("dummy");
user.setLastName("dummy");
// Add new User object
UserEntity user1 = new UserEntity();
user1.setId(2);
user1.setEmail("dummyuser1@mail.com");
user1.setFirstName("dummy1");
user1.setLastName("dummy1");
session.save(user1);
session.save(user);
session.getTransaction().commit();
List<UserEntity> userList = session.createQuery
("SELECT a FROM UserEntity a", UserEntity.class).getResultList();
System.out.println("List of users:" + userList);
HibernateUtil.shutdown();
}

}

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