Video in progress
How do you map PostgreSQL's native enum type in Hibernate 6, and when is it better or worse than `varchar` + a `check` constraint?
In PostgreSQL you create the type with create type ... as enum; in Hibernate 6 you put @Enumerated(EnumType.STRING) and @JdbcTypeCode(SqlTypes.NAMED_ENUM) on the field. The database rejects a wrong value itself and the value is stored compactly, but changing the enum in a migration is heavier than with varchar + check.
📖 Answer
create type order_status as enum ('NEW', 'PAID', 'SHIPPED');
create table orders (id bigint primary key, status order_status not null);
@Enumerated(EnumType.STRING)
@JdbcTypeCode(SqlTypes.NAMED_ENUM)
@Column(columnDefinition = "order_status")
private Status status;
NAMED_ENUM tells Hibernate to send the parameter with exactly this type, not as a plain varchar. Without it, PostgreSQL gives column "status" is of type order_status but expression is of type character varying. In older projects people worked around this with columnDefinition and a cast in the SQL.
The advantages: strict values at the database level, 4-byte storage, and the type itself serves as documentation in psql.
The downsides show up more in migrations:
- a new value is
alter type order_status add value 'REFUNDED'. Before PostgreSQL 12 this didn't work inside a transaction, which required a special setting in Flyway; - after removing or renaming a value, running alongside the old code (a zero-downtime deploy) is hard;
- native SQL and clients in other languages must know this type too.
varchar + check (status in ('NEW','PAID','SHIPPED')) gives almost the same protection, and replacing the constraint is a plain migration. So I choose a native enum only when the values are truly stable, and varchar + check otherwise.
Whichever variant you pick, avoid EnumType.ORDINAL in Java: if the order changes, the data is silently corrupted.
Sign up to mark studied questions and save your progress.