Hibernate 5 - Basic configuration example without hibernate.cfg.xml

Hibernate 5 - Basic configuration example

In this post, we will show you how to create or configure a simple Hibernate application without using hibernate.cfg.xml.

Technologies and tools used for this application are -

  • Hibernate 5.2.6.Final
  • Eclipse Mars.2 (4.5.2)
  • Maven 3.3.9
  • JavaSE 1.8
  • PostgreSQL 9.6.1

 

Project Structure

Review the following project structure.

Let us proceed to write a simple application, which will print the version of the PostgreSQL database.

 

Step 1 – Create a maven project

Refer this article to learn - How to create a maven project in eclipse.

 

Step 2 - Add jar dependencies to pom.xml

Open pom.xml file and add required Hibernate and PostgreSQL dependencies to it.

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.boraji.tutorial.hibernate</groupId>
  <artifactId>hibernate-config-example</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>hibernate-tutorial</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <!-- PostgreSQL  -->
    <dependency>
      <groupId>org.postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <version>9.4.1212.jre7</version>
    </dependency>
    <!-- Hibernate 5.2.6 Final -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.6.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 3 - Create a Hibernate utility class

Create a class named as HibernateUtil.java and write the following code in it.

HibernateUtil.java

package com.boraji.tutorial.hibernate;

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;

/**
 * @author imssbora
 */
public class HibernateUtil {
   private static StandardServiceRegistry registry;
   private static SessionFactory sessionFactory;

   public static SessionFactory getSessionFactory() {
      if (sessionFactory == null) {
         try {

            // Create registry builder
            StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder();

            // Hibernate settings equivalent to hibernate.cfg.xml's properties
            Map<String, String> settings = new HashMap<>();
            settings.put(Environment.DRIVER, "org.postgresql.Driver");
            settings.put(Environment.URL, "jdbc:postgresql://localhost:5432/BORAJI");
            settings.put(Environment.USER, "postgres");
            settings.put(Environment.PASS, "admin");
            settings.put(Environment.DIALECT, "org.hibernate.dialect.PostgreSQL9Dialect");

            // Apply settings
            registryBuilder.applySettings(settings);

            // Create registry
            registry = registryBuilder.build();

            // Create MetadataSources
            MetadataSources sources = new MetadataSources(registry);

            // Create Metadata
            Metadata metadata = sources.getMetadataBuilder().build();

            // Create SessionFactory
            sessionFactory = metadata.getSessionFactoryBuilder().build();

         } catch (Exception e) {
            e.printStackTrace();
            if (registry != null) {
               StandardServiceRegistryBuilder.destroy(registry);
            }
         }
      }
      return sessionFactory;
   }

   public static void shutdown() {
      if (registry != null) {
         StandardServiceRegistryBuilder.destroy(registry);
      }
   }
}

As you can see in the above example, the applySettings() method of the  StandardServiceRegistryBuilder class is used for loading configuration details, required for bootstrapping a Hibernate application. 

 

Step 4 - Create a main class and run application

Here is the main class to check the database version.

MainApp.java

package com.boraji.tutorial.hibernate;

import org.hibernate.Session;

/**
 * @author imssbora
 */
public class MainApp {
  public static void main(String[] args) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();

    // Check database version
    String sql = "select version()";

    String result = (String) session.createNativeQuery(sql).getSingleResult();
    System.out.println(result);

    session.getTransaction().commit();
    session.close();

    
    HibernateUtil.shutdown();
  }
}

Output

PostgreSQL 9.6.1, compiled by Visual C++ build 1800, 64-bit

You can download this application from the below link..