Several Implementation Approaches for Mapping Enum Classes to Database Fields

Bota5ky
1 min readMar 21, 2024

--

Background

For some database fields, although they only have a few limited content types, their formats do not completely adhere to SCREAMING_SNAKE_CASE. Therefore, some settings are needed to ensure that Spring Data JPA maps the values correctly.

Implementation Approaches

Enum class Color:

public enum Color {
RED,
GREEN,
BLUE
}

The default implementation maps the ORDINAL value of the enum value:

@Entity
public class Entity {
@Enumerated(EnumType.ORDINAL) // default mapping, same without annotation
private Color color;

// other properties and methods
}

If you need to map the name of the enum value, use:

@Enumerated(EnumType.STRING)

These are two common approaches, but sometimes the situation may be more complicated. For example, if the database stores the lowercase name of the enum value. Then you need to use AttributeConverter. In fact, not only enum classes, but also other special classes that need custom storage can all be implemented with this converter.

Here we implement AttributeConverter based on enum classes:

public abstract class EnumConverter<E extends Enum<E>> implements AttributeConverter<E, String> {
@Override
public String convertToDatabaseColumn(E attribute) {
return attribute != null ? attribute.name().toLowerCase(Locale.ROOT) : null;
}

@Override
public E convertToEntityAttribute(String dbData) {
return dbData != null ? Enum.valueOf(attributeType(), dbData.toUpperCase(Locale.ROOT)) : null;
}

protected Class<E> attributeType() {
throw new UnsupportedOperationException("attributeType() must be overridden in concrete subclass");
}
}

Specific enum classes only need to implement the attributeType() method.

A more customizable approach is to directly implement AttributeConverter and implement the convertToDatabaseColumn() and convertToEntityAttribute() methods.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Bota5ky
Bota5ky

Written by Bota5ky

负箧曳屣,行深山巨谷中。

No responses yet

Write a response