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.

--

--