DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • Leverage Amazon BedRock Chat Model With Java and Spring AI
  • Using Spring AI to Generate Images With OpenAI's DALL-E 3
  • Implementing Row-Level Security

Trending

  • How Can Developers Drive Innovation by Combining IoT and AI?
  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • Integration Isn’t a Task — It’s an Architectural Discipline
  • AI-Driven Root Cause Analysis in SRE: Enhancing Incident Resolution
  1. DZone
  2. Coding
  3. Java
  4. Solve the Java Spring Boot Enum

Solve the Java Spring Boot Enum

This article explains how to solve the Java Spring Boot enum ArrayIndexOutOfBoundsException using a method that is proven to work.

By 
Ajay Sodhi user avatar
Ajay Sodhi
·
Apr. 17, 23 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
13.1K Views

Join the DZone community and get the full member experience.

Join For Free

I had a hard time solving the org.hibernate.type.descriptor.java.EnumJavaTypeDescriptor.fromOrdinal(EnumJavaTypeDescriptor.java:76)error that I got while reading the value from the database.

Background

While using the Spring Boot application, I saved some values in the database as an INT that I had to map back with the enum UserRole. The challenge: I used id and name in the enum, but instead of starting the id value from 0, I started the ID value from 1.

This is the point the story started to challenge itself.

The actual problem is instead of mapping the id of the enum while populating the object back to the Java object. It started reading the ordinal value. And I was feeling clueless even after debugging.

Every blog that I was reading was suggesting to change the id to 0 so that the underlying exception (shown below) can be avoided.

Java
 
ERROR 13992 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2] with root cause
java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2 ...


My POJO mappings were:

User POJO

Java
 
@Entity
@Table(name = "USER")
@Getter
@Setter
@NoArgsConstructor(force = true)
public class User {

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

  @Column(name = "ROLE")
  @NotNull(message = "Role is required")
  @JsonAlias("roleId")
  private UserRole roleId;

  @Column(name = "NAME")
  @NotNull(message = "User Name is required")
  private Sting name;

}


UserRole POJO

Java
 
public enum UserRole {

  ADMIN(1, "Admin"),
  USER(2, "User");

  private final int id;
  private final String name;

  private UserRole(final int id, final String name) {
    this.id = id;
    this.name = name;
  }

  public int getId() {
    return id;
  }

  public String getName() {
    return name;
  }

  public static UserRole valueOf(final Integer id) {
    if (id == null) {
      return null;
    }
    for (UserRole type : UserRole.values()) {
      if (type.id == id) {
        return type;
      }
    }
    return null;
  }
}


Solution

When such a situation arises where you have to manipulate the DB values as per your enum, you can use the: 

javax.persistence.Converter

Here's How!

I added the following code to the User POJO:

Java
 
  @Convert(converter = UserRole.UserRoleConverter.class)
  @Column(name = "ROLE")
  @NotNull(message = "Role is required")
  @JsonAlias("roleId")
  private UserRole roleId;


And the below code to the UserRole POJO:

Java
 
  @Converter(autoApply = true)
  public static class UserRoleConverter implements
      AttributeConverter<UserRole, Integer> {

    @Override
    public Integer convertToDatabaseColumn(UserRole attribute) {
      if (attribute == null) {
        throw new BadRequestException("Please provide a valid User Role.");
      }

      return attribute.getId();
    }

    @Override
    public UserRole convertToEntityAttribute(Integer dbData) {
      return UserRole.valueOf(dbData);
    }
  }


This converter maps the value fetched from the DB to the enum value by internally calling the valueOf() method.

I was facing this error, and this approach solved the problem for me. I am pretty sure it will solve your problem too.

Do let me know in the comments if you find the solution useful. :)

Java (programming language) Spring Boot Error message

Opinions expressed by DZone contributors are their own.

Related

  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • Leverage Amazon BedRock Chat Model With Java and Spring AI
  • Using Spring AI to Generate Images With OpenAI's DALL-E 3
  • Implementing Row-Level Security

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!