Video in progress

When persisting an enum field, would you choose EnumType.ORDINAL or EnumType.STRING?

Almost always STRING. ORDINAL stores the enum's position number, and if a new value is added in the middle or the order changes, the old data in the database silently takes on the wrong meaning.

📖 Answer

public enum Status { NEW, PAID, SHIPPED }

@Enumerated(EnumType.STRING)
@Column(length = 20)
private Status status;

If you don't write @Enumerated, the default is ORDINAL. This catches a lot of people.

Why ORDINAL is dangerous: the database has 1 stored for PAID. Then someone changes the enum to NEW, CANCELLED, PAID, SHIPPED. Now every old 1 reads as CANCELLED. There's no error, just wrong data.

The price of STRING is a bit more space, which usually doesn't matter.

You still need to be careful with STRING: renaming an enum value requires a migration (UPDATE orders SET status = ...).

Hibernate 6 also supports PostgreSQL's native enum type and other options. If the code in the database differs from the enum name (say, "P"), you can write an AttributeConverter.