Hibernate - Create Custom Dialect

In this tutorial, I'm going to show you how to create a custom Hibernate dialect.

Hibernate is an ORM (Object-Relational Mapping) tool for Java. It supports various database platforms such as PostgreSQL, Oracle, MySQL, and many more. In order to support different database platforms, Hibernate uses different dialects for each platform. Hibernate has a default dialect for each platform. For example, PostgreSQLDialect for PostgreSQL and MySQLDialect for MySQL. If you use Spring framework, you need to define which dialect to use using spring.jpa.properties.hibernate.dialect property.

  spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

The available dialects are located in the org.hibernate.dialect package. Prior to Hibernate 6, you have to use the dialect that depends on the database version you use. For example, you have to use PostgreSQL10Dialect for PostgreSQL 10 or above. For MySQL 8, you have to use MySQL8Dialect. Since Hibernate 6, those version specific classes have been deprecated. The non version specific classes(e.g. PostgreSQLDialect, MySQLDialect) are preferred since they can handle all versions.

Create Custom Hibernate Dialect

Sometimes, it's necessary to override the default one. To do so, you just need to create a new class that extends the default one for your database platform. For example, if you use PostgreSQL, you need to create a class that extends PostgreSQLDialect. Inside the class, you can override any method you want to override. Below is an example that override the getTimeZoneSupport methods.

  package com.woolha.hibernate.dialect;

  import org.hibernate.dialect.PostgreSQLDialect;
  import org.hibernate.dialect.TimeZoneSupport;

  public class MyCustomDialect extends PostgreSQLDialect {

    @Override
    public TimeZoneSupport getTimeZoneSupport() {
      return TimeZoneSupport.NATIVE;
    }
  }

Then, you need to tell Hibernate that you have a custom dialect by updating the application property to point to the class you've created.

  spring.jpa.properties.hibernate.dialect=com.woolha.hibernate.dialect.MyCustomDialect

To make sure that you've done the correct thing, you can check the current dialect used by your application.

  @Service
  @RequiredArgsConstructor
  public class MyService {

    private final EntityManager entityManager;
  
    public void test() {
      System.out.println(entityManager.getEntityManagerFactory().getProperties().getOrDefault("hibernate.dialect", "").toString());
    }
  }

The list of methods you can override can be seen in the org.hibernate.dialect.Dialect abstract class. It's possible to override the public and protected methods.

Summary

To use a custom dialect, you can create a class that extends the default one. Then, change the application property to use the custom one.