Video in progress

Senior ☕ Core Java

How do you store an enum in the database: ordinal, name, or a separate code?

ordinal is risky: if the enum order changes, all the old rows get a different meaning. name is readable, but renaming a constant requires a migration. In long-lived systems, a separate stable code plus a converter is the most reliable.

📖 Answer

In JPA, the default @Enumerated is ORDINAL. In many projects this is a ticking bomb:

enum Status { NEW, PAID, SHIPPED }   // DB: 0, 1, 2
enum Status { NEW, CANCELLED, PAID, SHIPPED } // now 1 = CANCELLED!

The mistake throws no exception at all: paid orders just start looking cancelled.

Method Pro Con
ORDINAL compact depends on the order, a meaningless number in the DB
STRING (name) readable, order is free renaming = a data migration
a code + AttributeConverter the name and the DB are independent a bit of code
public enum Status {
    NEW("N"), PAID("P"), SHIPPED("S");
    private final String code;
    Status(String code) { this.code = code; }
    public String code() { return code; }
    public static Status ofCode(String c) {
        for (Status s : values()) if (s.code.equals(c)) return s;
        throw new IllegalArgumentException("Noma'lum status kodi: " + c);
    }
}

@Converter(autoApply = true)
class StatusConverter implements AttributeConverter<Status, String> {
    public String convertToDatabaseColumn(Status s) { return s == null ? null : s.code(); }
    public Status convertToEntityAttribute(String c) { return c == null ? null : Status.ofCode(c); }
}

Also note:

  • add CHECK (status IN ('N','P','S')) in the DB, so a wrong value can't be written;
  • values() returns a copy of the array on every call; cache a Map on a hot path;
  • before removing old code, check that none of it is left in the DB.

Hibernate 6 also supports PostgreSQL's native enum type, but adding a value to it is a migration too, so the advantage is small.