Video in progress
What risk comes from storing an enum field without @Enumerated, or with EnumType.ORDINAL?
By default an enum is stored as ORDINAL, that is, its position number (0, 1, 2). If someone adds a new value in the middle or reorders them, the old numbers in the database take on a different meaning, and no error shows up anywhere.
📖 Answer
enum OrderStatus { NEW, PAID, SHIPPED }
@Entity
class Order {
private OrderStatus status; // no @Enumerated -> ORDINAL
}
In the database: NEW=0, PAID=1, SHIPPED=2. A year later a requirement arrives: an "awaiting payment" state:
enum OrderStatus { NEW, AWAITING_PAYMENT, PAID, SHIPPED }
Now 1 in the database is AWAITING_PAYMENT and 2 is PAID. All the shipped orders suddenly became "paid but not shipped". No exception, no migration error, just wrong data.
The right way:
@Enumerated(EnumType.STRING)
@Column(length = 32)
private OrderStatus status;
With STRING the name of the value is stored, and you can freely reorder. The price is a few extra bytes, which is almost never a problem.
STRING has a condition too: if you rename an enum value, you have to update the database as well. If an unknown string is left in the database, reading throws IllegalArgumentException.
If you need a short code in the database (say, "N", "P"), you can write an AttributeConverter<OrderStatus, String> and keep the code inside the enum.
Sign up to mark studied questions and save your progress.