Hibernate 5 - Enum Type Mapping Example

In this article, we will show you how a Java enum type is persisted into a database in hibernate applications.
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 -
  1. @Enumerated(EnumType.ORDINAL) → Store the enum values according the ordinal position (i.e. 0 , 1, 2 … ) of enum value.
  2. @Enumerated(EnumType.STRING) → Store the enum values according to the name of enum value. The default is EnumType.ORDINAL.
Let's look at how to map enum types using @javax.persistence.Enumerated annotation with below snippets.
Consider the following enum types -
package net.javaguides.hibernate.entity;

public enum ProjectStatus {
    OPEN,
    INPROGESS,
    RESUME,
    COMPLETED,
    CLOSED;
}
Let's use and map this enum in Project entity class -
@Entity
@Table(name = "project")
public class Project {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "project_name")
    private String projectName;

    @Enumerated(EnumType.STRING)
    @Column(name = "project_status")
    private ProjectStatus projectStatus;

    // getter and setters
}
Let's develop a simple hibernate application to demonstrate enum type mapping with a database table column.

Technologies and tools used

  • Hibernate 5.3.7.Final
  • IDE - Eclipse Noen
  • Maven 3.5.3
  • JavaSE 1.8
  • MySQL - 8.0.13

Development Steps

  1. Create a Simple Maven Project
  2. Project Directory Structure
  3. Add jar Dependencies to pom.xml
  4. Create Enum - ProjectStatus.java
  5. Creating the JPA Entity Class(Persistent class)
  6. Create a Hibernate configuration file - Java Configuration
  7. Create ProjectDao Class
  8. Create the Main class and Run an Application

1. Create a Simple Maven Project

Use How to Create a Simple Maven Project in Eclipse article to create simple Maven project in Eclipse IDE.

2. Project Directory Structure

The project directory structure for your reference - 

3. Add jar Dependencies to 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>
    <parent>
        <groupId>net.javaguides.hibernate</groupId>
        <artifactId>hibernate-tutorial</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <artifactId>hibernate-enum-type-example</artifactId>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</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>

4. Create Enum - ProjectStatus.java

Create ProjectStatus enum class and add following code to it.
package net.javaguides.hibernate.entity;

public enum ProjectStatus {
 OPEN, INPROGESS, RESUME, COMPLETED, CLOSED;
}

5. Creating the JPA Entity Class(Persistent class)

Let's create a Project persistent class that is mapped to a database table.
A simple Persistent class should follow some rules:
  • A no-arg constructor: It is recommended that you have a default constructor at least package visibility so that hibernate can create the instance of the Persistent class by newInstance() method.
  • Provide an identifier property: It is better to assign an attribute as id. This attribute behaves as a primary key in a database.
  • Declare getter and setter methods: The Hibernate recognizes the method by getter and setter method names by default.
  • Prefer non-final class: Hibernate uses the concept of proxies, that depends on the persistent class. The application programmer will not be able to use proxies for lazy association fetching.
Create a Project entity class under net.javaguides.hibernate.entity package as follows.
package net.javaguides.hibernate.entity;

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

@Entity
@Table(name = "project")
public class Project {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "project_name")
    private String projectName;

    @Enumerated(EnumType.STRING)
    @Column(name = "project_status")
    private ProjectStatus projectStatus;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getProjectName() {
        return projectName;
    }

    public void setProjectName(String projectName) {
        this.projectName = projectName;
    }

    public ProjectStatus getProjectStatus() {
        return projectStatus;
    }

    public void setProjectStatus(ProjectStatus projectStatus) {
        this.projectStatus = projectStatus;
    }
}
Here the EnumType.STRING strategy is used for the ProjectStatus field so the project_status column can hold either PERMANENT or COMMUNICATION value.
Similarly the EnumType.ORDINAL strategy can be used for project_status column can hold either 0 or 1 value.

6. Create a Hibernate configuration file - Java Configuration

The HibernateUtil Java configuration file contains information about the database and mapping file. Create a helper class to bootstrap hibernate and add Project entity to the MetadataSources for mapping as follows.

Dialects are an important feature in Hibernate. They enable you to implement a database-independent persistence layer by transparently adapting your mappings and queries. So, make sure to always use the correct dialect for your database system and version.
package net.javaguides.hibernate.util;

import java.util.Properties;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.service.ServiceRegistry;

import net.javaguides.hibernate.entity.Student;

public class HibernateUtil {
    private static SessionFactory sessionFactory;
    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {
                Configuration configuration = new Configuration();

                // Hibernate settings equivalent to hibernate.cfg.xml's properties
                Properties settings = new Properties();
                settings.put(Environment.DRIVER, "com.mysql.cj.jdbc.Driver");
                settings.put(Environment.URL, "jdbc:mysql://localhost:3306/hibernate_db?useSSL=false");
                settings.put(Environment.USER, "root");
                settings.put(Environment.PASS, "root");
                settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");

                settings.put(Environment.SHOW_SQL, "true");

                settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");

                settings.put(Environment.HBM2DDL_AUTO, "create-drop");

                configuration.setProperties(settings);

                configuration.addAnnotatedClass(Project.class);

                ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties()).build();

                sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sessionFactory;
    }
}

Create ProjectDao Class

Let's create a separate ProjectDao class to separate out hibernate related stuff.
package net.javaguides.hibernate.dao;

import java.util.List;

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

import net.javaguides.hibernate.entity.Project;
import net.javaguides.hibernate.util.HibernateUtil;

public class ProjectDao {
    public void saveProject(Project project) {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            // start a transaction
            Transaction transaction = session.beginTransaction();
            // save the project object
            session.save(project);
            // commit transaction
            transaction.commit();
        }
    }

    public List < Project > getProjects() {
        try (Session session = HibernateUtil.getSessionFactory().openSession()) {
            return session.createQuery("from Project", Project.class).list();
        }
    }
}

7. Create the main App class and Run an Application

Let's test Hibernate application to connect MySQL database.
package net.javaguides.hibernate;

import java.util.List;

import net.javaguides.hibernate.dao.ProjectDao;
import net.javaguides.hibernate.entity.Project;
import net.javaguides.hibernate.entity.ProjectStatus;

public class MainApp {
    public static void main(String[] args) {
        ProjectDao projectDao = new ProjectDao();
        Project project = new Project();
        project.setProjectName("TPO");
        project.setProjectStatus(ProjectStatus.INPROGESS);
        projectDao.saveProject(project);

        List < Project > projects = projectDao.getProjects();
        projects.forEach(s - > {
            System.out.println(s.getProjectName());
            System.out.println(s.getProjectStatus());
        });
    }
}

Output



GitHub Repository

The complete source code of this article available on my GitHub Repository - https://github.com/RameshMF/Hibernate-ORM-Tutorials

Conclusion

In this article, we have shown you how to use Java enum type to persist a JPA entity into a database.
You can learn more about Hibernate ORM Framework at Hibernate Tutorial

References

Comments