In this tutorial, we’ll create our first Hibernate application. We’ll understand how to create SessionFactory and will use it to interact with MYSQL database to get database version.
1. Create SessionFactory in Hibernate
The starting point of writing a Hibernate program is to create a SessionFactory. Bootstrapping APIs are redesigned in Hibernate 5.0. The way of creating SessionFactory in Hibernate 5.0 is different from the older version. In this tutorial, we’ll discuss creation of fully functional SessionFactory in Hibernate 5.0.
In most cases, the creation of SessionFactory if a 3 step process:
- Build the
ServiceRegistry. - Build the
Metadata. - Use
ServiceRegistryandMetadatato build theSessionFactory.
1.1 Build ServiceRegistry
First step is to create ServiceRegistry. ServiceRegistry holds all services required by Hibernate. Following are different ServiceRegistry interfaces used in most cases:
BootstrapServiceRegistryStandardServiceRegistry
BootstrapServiceRegistry provides the most basic services and can be used in stand-alone environments. In most of the cases, you’ll need to create a StandardServiceRegistry which is done using org.hibernate.boot.registry.StandardServiceRegistryBuilder.
StandardServiceRegistryBuilder standardRegistryBuilder = new StandardServiceRegistryBuilder();
You can also create StandardServiceRegistryBuilder explicitly from BootstrapServiceRegistry.
BootstrapServiceRegistry bootstrapRegistry = new BootstrapServiceRegistryBuilder().build();
StandardServiceRegistryBuilder standardRegistryBuilder =
new StandardServiceRegistryBuilder(bootstrapRegistry);
2. Build the Metadata
The org.hibernate.boot.Metadata object represents the parsed representation of an application domain model and its mapping to a database. To create Metadata, we need to define MetadataSources. MetadataSources is used to define hbm.xml files, orm.xml files or annotated classes.
Following is a code snippet of configuring MetadataSources.
ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().build();
MetadataSources metadataSources = new MetadataSources( standardRegistry )
.addAnnotatedClass( MyEntity.class )
.addAnnotatedClassName( "com.learnitweb.Customer" )
.addResource( "User.hbm.xml" )
.addResource( "Employee.orm.xml" );
Once you have configured the MetadataSources, you can create the Metadata. Following is the typical way of creating Metadata:
Metadata metadata = metadataSources.getMetadataBuilder().build();
1.3 Build the SessionFactory
You can create the SessionFactory with default behavior by calling the buildSessionFactory method on the Metadata object.
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();
Note: ServiceRegistry, Metadata and SessionFactory provide many methods for configuration. We have shown only the basic and commonly used ways to configure.
2. Example – Program to use Hibernate with MySQL
We’ll now create a simple application to use Hibernate with MySQL. We’ll create this application from scratch.
Step 1: Create a Maven project.
We are using STS as IDE to develop this application. We’ll create a Maven project with mysql-connector-java and hibernate-core dependencies. Our pom.xml looks like the following:
pom.xml
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.learnitweb</groupId> <artifactId>HibernateExample</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.27</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.6.3.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>
Step 2: Configuration
Next, we have to configure database connection details. We’ll create hibernate.cfg.xml file and place it in classpath. In Maven project, you can place this file in src/main/resources folder.
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"https://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property>
<property name="connection.username">root</property>
<property name="connection.password">admin</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>
Step 3: Create SessionFactory
A SessionFactory is very expensive to create. So an application should have only one SessionFactory for a given database. We’ll create a HibernateUtil class which will return the SessionFactory if not already created, else it will return the same instance of SessionFactory.
HibernateUtil.java
package com.learnitweb.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 HibernateUtil {
private static StandardServiceRegistry standardServiceRegistry;
private static SessionFactory sessionFactory;
static {
try {
if (sessionFactory == null) {
standardServiceRegistry = new StandardServiceRegistryBuilder().configure().build();
MetadataSources metadataSources = new MetadataSources(standardServiceRegistry);
Metadata metadata = metadataSources.getMetadataBuilder().build();
sessionFactory = metadata.getSessionFactoryBuilder().build();
}
} catch (Exception e) {
e.printStackTrace();
if (standardServiceRegistry != null) {
StandardServiceRegistryBuilder.destroy(standardServiceRegistry);
}
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Step 4: Create client to test
Next step is to write a client to test the application.
Client.java
package com.learnitweb.client;
import org.hibernate.Session;
import com.learnitweb.util.HibernateUtil;
public class Client {
public static void main(String[] args) {
try (Session session = HibernateUtil.getSessionFactory().openSession()) {
String SQL = "Select version()";
String result = (String) session.createNativeQuery(SQL).getSingleResult();
System.out.println("MySQL version is: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output
MySQL version is: 8.0.22
3. Create SessionFactory without hibernate.cfg.xml
You can define all database configuration details in Java code itself. You can define properties as a Map and provide this Map to StandardServiceRegistryBuilder.
HibernateUtil.java with database connection details
package com.learnitweb.util;
import java.util.HashMap;
import java.util.Map;
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;
import org.hibernate.cfg.Environment;
public class HibernateUtil {
private static StandardServiceRegistry standardServiceRegistry;
private static SessionFactory sessionFactory;
static {
try {
if (sessionFactory == null) {
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();
Map<String, String> dbSettings = new HashMap<>();
dbSettings.put(Environment.URL, "jdbc:mysql://localhost:3306/mydb");
dbSettings.put(Environment.USER, "root");
dbSettings.put(Environment.PASS, "admin");
dbSettings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
dbSettings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL8Dialect");
registryBuilder.applySettings(dbSettings);
standardServiceRegistry = registryBuilder.build();
MetadataSources metadataSources = new MetadataSources(standardServiceRegistry);
Metadata metadata = metadataSources.getMetadataBuilder().build();
sessionFactory = metadata.getSessionFactoryBuilder().build();
}
} catch (Exception e) {
e.printStackTrace();
if (standardServiceRegistry != null) {
StandardServiceRegistryBuilder.destroy(standardServiceRegistry);
}
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
