Hibernate Enum Column Mapping Example

In this article, we will show you how a Java enum type is persisted into a database in hibernate applications.

This tutorial is upgraded to use Hibernate 6+ and Java 17.

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

There are two strategies to store enum values in the database:
@Enumerated(EnumType.ORDINAL) → Store the enum values according to the ordinal position (i.e. 0, 1, 2 … ) of the enum value.
@Enumerated(EnumType.STRING) → Store the enum values according to the name of the enum value. The default is EnumType.ORDINAL.
 
Let's look at how to map enum types using @Enumerated annotation with the below snippets.
 
Consider the following ProjectStatus enum type:
package net.javaguides.hibernate.entity;

public enum ProjectStatus {
    OPEN,
    INPROGESS,
    RESUME,
    COMPLETED,
    CLOSED;
}
Let's use and map this enum in a 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
}
The enum type value String is mapped using @Enumerated annotation:
    @Enumerated(EnumType.STRING)
    @Column(name = "project_status")
    private ProjectStatus projectStatus;

Hibernate Enum Column Mapping Complete Example

Let's develop a simple hibernate application to demonstrate enum type mapping with a database table column.

Technologies and tools used

  • Hibernate 6.1.7.Final
  • IDE - Eclipse
  • Maven 3.5.3
  • Java 17
  • MySQL - 8.0.32

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 the How to Create a Simple Maven Project in Eclipse article to create a 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.32</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>6.1.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>17</source>
                    <target>17</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
Note that we are using Hibernate 6+, Java 17, and MySQL 8+.

4. Create Enum - ProjectStatus.java

Create ProjectStatus enum class and add the 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.
package net.javaguides.hibernate.entity;

import jakarta.persistence.*;

@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 is 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 the project_status column can hold either a 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 the 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.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 with the following content:
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.persist(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 to the 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 is available on my GitHub Repository - https://github.com/RameshMF/Hibernate-ORM-Tutorials

Conclusion

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

Comments

Post a Comment

Leave Comment