Hi all in this blog we ‘ll learn about @Enumerated annotation of jpa. We use this annotation when we have to map our entity column value with Enum. Enum stands for enumeration, It’s a special type of class that defines a fixed set of constant.
For example say we have a user entity class and here we have a column with name role. These role can be user, admin, guest. So instead of hardcoding it we can create Enum and define these roles there and use these Role Enum value in our JPA Entity using @Enumerated annotation.
In short @Enumerated is a JPA annotation that tells how to store an Enum value in database using our entity class.
Let’s see what we ‘ll cover in this blog
- Why we should use @Enumerated annotation.
- Property of @Enumerated
- What happen if we don’t use @Enumerated annotation and try to save enum in JPA entity.
- How to use it in JPA
Why we should use @Enumerated annotation
We use @Enumerated annotation when we want to save value from a Enum. Using enum we can define a specific set of constant and use them accordingly. Like we mention above suppose i want to define a role for each user. And the set of role are Admin, User, Guest. So we ‘ll create a enum with these roles and set value as per our need.
Property of @Enumerated
There are two property use by @Enumerated in JPA. And they are:
@Enumerated(EnumType.ORDINAL)
@Enumerated(EnumType.STRING)Code language: CSS (css)
EnumType.ORDINAL is the default property of @Enumerated annotation. Means if we just annotated our entity class field with @Enumerated it ‘ll use EnumType.ORDINAL, we don’t need to define it explicitly it’s the default behaviour.
EnumType.ORDINAL is not the recommended approach because it save the value on the basis of defined index. Say you have define 3 constant in your enum (ADMIN, USER, GUEST). And if you save the value as USER then in your table you ‘ll see the role value as 1 because USER is at first index.
So see how risky it is suppose if you change your order of enum in future then it ‘ll make existing records inconsitent.
So it’s always recommended to use EnumType.STRING property for storing the enum values.
What happen if we don’t use @Enumerated annotation and try to save enum in JPA entity.
The answer is it saves value as per EnumType.ORDINAL because for enum JPA by default use EnumType.ORDINAL.
How to use it in JPA
We have learned about @Enumerated annotation. Let’s see how can we use it in our code. So we ‘ll create a spring boot project with PostgreSQL database. We create a entity class and a enum and try to save value on the basis of this enum.
Just create a spring boot project and add below dependency in your pom.xml file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>Code language: HTML, XML (xml)
Add below property for JPA and your PostgreSQL connectivity. Just change the database name and schema as per your project.
spring.application.name=EnumeratedJPAExample
# PostgreSQL Configuration
spring.datasource.url=jdbc:postgresql://localhost:5432/javadream?currentSchema=vasu
spring.datasource.username=postgres
spring.datasource.password=postgres
# Hibernate Configuration
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Code language: PHP (php)
Create a enum for Role and define the constant as per your requirement.
package com.javadream.EnumeratedJPAExample.enums;
public enum Role {
ADMIN,
USER,
GUEST;
}Code language: PHP (php)
Create a repository to save the details in DB
package com.javadream.EnumeratedJPAExample.repository;
import com.javadream.EnumeratedJPAExample.entity.UserDetail;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserDetailRepository extends JpaRepository<UserDetail, Long> {
}Code language: CSS (css)
It’s time to create Entity class with Role as a column.
package com.javadream.EnumeratedJPAExample.entity;
import com.javadream.EnumeratedJPAExample.enums.Role;
import jakarta.persistence.*;
import lombok.Data;
@Entity
@Table(name = "user_details")
@Data
public class UserDetail {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String emailAddress;
private String mobileNumber;
@Enumerated(EnumType.ORDINAL) // same as @Enumerated
private Role role;
}Code language: CSS (css)
You can see we are using the EnumType.ORDINAL property. It’s upto you either use @Enumerated(EnumType.ORDINAL) or use only @Enumerated both are same because by default it use ORDINAL EnumType.
Now create the logic to save details in database. For this example we are using the CommandLineRunner interface to save the data. Put logic in controller as per your need or for testing do the below changes in your main class.
package com.javadream.EnumeratedJPAExample;
import com.javadream.EnumeratedJPAExample.entity.UserDetail;
import com.javadream.EnumeratedJPAExample.enums.Role;
import com.javadream.EnumeratedJPAExample.repository.UserDetailRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@RequiredArgsConstructor
@Slf4j
public class EnumeratedJpaExampleApplication implements CommandLineRunner {
private final UserDetailRepository userDetailRepository;
public static void main(String[] args) {
SpringApplication.run(EnumeratedJpaExampleApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
UserDetail userDetail = new UserDetail();
userDetail.setName("Vasu Rajput");
userDetail.setEmailAddress("vasu@gmail.com");
userDetail.setMobileNumber("8077777777");
userDetail.setRole(Role.GUEST);
UserDetail savedUser = userDetailRepository.save(userDetail);
log.info("User saved successfully: {} ", savedUser.getId());
}
}Code language: JavaScript (javascript)
Run it and see the database. As GUEST is defined at 2 index so your role column should have value as 2. Just validate your database table after project run succesfully.

See the value for role column is 2. Now try to change the EnumType from ORDINAL to STRING. In your entity class just change the EnumType on Role property. Do below change in your UserDetail class.
@Enumerated(EnumType.STRING)
private Role role;Code language: CSS (css)
Now run your project again and see the database and validate role column value.

Hope you enjoy this blog. If you like this blog please share this with other and help us to grow. Please provide your feedback in our comment section.
If you need blog on specific topic please mention in our comment section we ‘ll try to cover that in our upcoming blogs.