Hibernate 5 - Enum Type Mapping example


Technologies used:   JDK 1.8.0_121 | Hibernate 5.2.6.Final | Maven 3.9.9 | MySQL 5.7.12 | Eclipse Mars.2 (4.5.2)

In this post, we will show you how a Java enum type is persisted into a database.

An enum type is mapped to a database via the @javax.persistence.Enumerated annotation.

There are two strategies to store enum values in the database -

  • @Enumerated(EnumType.ORDINAL) →  Store the enum values  according the ordinal position (i.e. 0 , 1, 2 … ) of enum value.
  • @Enumerated(EnumType.STRING) →  Store the enum values according to the name of enum value.

The default is EnumType.ORDINAL.

 

Consider the following enum types -

Phone.java

package com.boraji.tutorial.hibernate.entity;

public enum Phone {
   MOBILE, LANDLINE
}

AddressType.java

package com.boraji.tutorial.hibernate.entity;

public enum AddressType {
   PERMANENT, COMMUNICATION
}

 

Create an Address entity annotated with @Enitity as follows.

Address.java

package com.boraji.tutorial.hibernate.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "ADDRESS")
public class Address {

   @Id
   private long id;

   @Column(name = "CITY")
   private String city;

   @Column(name = "STATE")
   private String state;

   @Enumerated(EnumType.STRING)
   @Column(name = "ADDRESS_TYPE")
   private AddressType addressType;

   @Enumerated(EnumType.ORDINAL)
   @Column(name="PHONE")
   private Phone phone;

   //Getters and setters are omitted for brevity
}

Here the EnumType.STRING strategy is used for the AddressType field so the ADDRESS_TYPE column can hold either PERMANENT or COMMUNICATION value.

Similarly the EnumType.ORDINAL strategy is used for the Phone field so the PHONE column can hold either 0 or 1 value.

 

Create a helper class to bootstrap hibernate and add Address entity to the MetadataSources for mapping as follows.

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 com.boraji.tutorial.hibernate.entity.Customer;

public class HibernateUtil {
  private static StandardServiceRegistry registry;
  private static SessionFactory sessionFactory;

  public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
      try {
        StandardServiceRegistryBuilder registryBuilder = 
            new StandardServiceRegistryBuilder();

        Map<String, String> settings = new HashMap<>();
        settings.put("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
        settings.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/BORAJI");
        settings.put("hibernate.connection.username", "root");
        settings.put("hibernate.connection.password", "admin");
        settings.put("hibernate.show_sql", "true");
        settings.put("hibernate.hbm2ddl.auto", "create-drop");

        registryBuilder.applySettings(settings);

        registry = registryBuilder.build();

        MetadataSources sources = new MetadataSources(registry)
            .addAnnotatedClass(Customer.class);

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

        sessionFactory = metadata.getSessionFactoryBuilder().build();
      } catch (Exception e) {
        System.out.println("SessionFactory creation failed");
        if (registry != null) {
          StandardServiceRegistryBuilder.destroy(registry);
        }
      }
    }
    return sessionFactory;
  }

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

 

Now create a main class and run application.

MainApp.java

package com.boraji.tutorial.hibernate;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.boraji.tutorial.hibernate.entity.Address;
import com.boraji.tutorial.hibernate.entity.AddressType;
import com.boraji.tutorial.hibernate.entity.Phone;
import com.boraji.tutorial.hibernate.util.HibernateUtil;

public class MainApp {
   public static void main(String[] args) {
      Session session = null;
      Transaction transaction = null;
      try {
         session = HibernateUtil.getSessionFactory().openSession();
         transaction = session.getTransaction();
         transaction.begin();

         Address address = new Address();
         address.setId(1l);
         address.setCity("Palmer");
         address.setState("Alaska");
         address.setAddressType(AddressType.COMMUNICATION);
         address.setPhone(Phone.LANDLINE);
         
         session.save(address);
         transaction.commit();
         
         System.out.println("Address is added successfully.");
         
      } catch (Exception e) {
         if (transaction != null) {
            System.out.println("Transaction is being rolled back.");
            transaction.rollback();
         }
         e.printStackTrace();
      } finally {
         if (session != null) {
            session.close();
         }
      }
      HibernateUtil.shutdown();
   }
}

Output

Hibernate: create table ADDRESS (id bigint not null, ADDRESS_TYPE varchar(255), CITY varchar(255), PHONE integer, STATE varchar(255), primary key (id))
Hibernate: insert into ADDRESS (ADDRESS_TYPE, CITY, PHONE, STATE, id) values (?, ?, ?, ?, ?)
Address is added successfully.

MySQL Console output

mysql> select * from address;
+----+---------------+--------+-------+--------+
| id | ADDRESS_TYPE  | CITY   | PHONE | STATE  |
+----+---------------+--------+-------+--------+
|  1 | COMMUNICATION | Palmer |     1 | Alaska |
+----+---------------+--------+-------+--------+

 

 

 

Download Source: