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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • A Spring Boot App With Half the Startup Time
  • Zero-Downtime Deployments for Java Apps on Kubernetes

Trending

  • MQTT, Kafka, NATS, or Zenoh? Choosing Edge-to-Cloud Messaging by Traffic Pattern
  • Architecture Review Boards for Generative AI: A Framework for Governance, Risk Management, and Responsible Adoption
  • Why AI Agents Need a Shared Enterprise Ontology
  • New York City Taxi Trips: Putting Neo4j and DuckDB to Work

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Apr. 17, 23 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
14.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • A Spring Boot App With Half the Startup Time
  • Zero-Downtime Deployments for Java Apps on Kubernetes

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook