🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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.
@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;
}
@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
}
@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
- Create a Simple Maven Project
- Project Directory Structure
- Add jar Dependencies to pom.xml
- Create Enum - ProjectStatus.java
- Creating the JPA Entity Class(Persistent class)
- Create a Hibernate configuration file - Java Configuration
- Create ProjectDao Class
- 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>
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.
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
 
 
 
![[NEW] Full-Stack Java Development with Spring Boot 3 & React Build 5 Spring Boot Projects with Java: Line-by-Line Coding](https://img-c.udemycdn.com/course/750x422/5338984_4d3a_5.jpg) 
 
 
 
 
 
 
 
 
 
 
Useful tutorial.
ReplyDelete