Skip to main content

Enum Mapping in Hibernate 7: The ORDINAL Trap, STRING, PostgreSQL Native Enums and Converters

Hibernate 7.4 enum mapping tested on PostgreSQL 18 and H2: what ORDINAL, STRING, native enum types, converters and @EnumeratedValue store, what a second release reads after a constant is inserted or renamed, why the generated check constraint blocks the new value, why hbm2ddl=update does not fix it, and the migration each change needs.

A status column looks like the easiest thing in a persistence layer: a Java enum on one side, a column on the other. It works on the first day with any mapping. The trouble starts at the second release, when somebody adds, reorders or renames a constant, because the rows written last month are still in the table and they are now read by a different enum. This article maps one enum five ways in Hibernate 7 and then plays the same “release 2” against each: what the database holds, what the new code reads, whether it can write the new value, and the migration each one needs. Everything ran on a real PostgreSQL 18 and on H2, and every line of output below is quoted from a committed transcript.
Versions tested. Hibernate ORM 7.4.17.Final (the newest 7.x GA in maven-metadata.xml on 2026-11-19; 8.0.0.CR1 is listed after it and is not GA), Jakarta Persistence 3.2.0 (where @EnumeratedValue was added), PostgreSQL 18.6 with the 42.7.14 driver, H2 2.4.240, JUnit 6.0.3, JDK 25 (Temurin 25.0.5.1). Plain Hibernate, no Spring: the annotations behave the same under Spring Boot. Companion module: hibernate-demo / enums.

A column cannot hold a Java enum, so Hibernate stores a stand-in

A relational column holds numbers, text, dates. It has no idea what Status.PAID is. So every enum mapping answers one question: which stand-in value do we write for this constant, and how do we turn it back? There are four sensible answers, and the rest of the article is about how each one behaves over time.
Java enumStatus.PAIDORDINAL: its positioncolumn holds 1 (NEW=0, PAID=1, SHIPPED=2)STRING: its namecolumn holds ‘PAID’NAMED_ENUM: a database enum typecolumn of type statusv1 holds the label PAIDConverter or @EnumeratedValue: a code you choosecolumn holds ‘P’Only the third and fourth stand-ins are values you control. The first two are decided by the enum declaration itself.That difference is the whole article: what happens when the declaration changes next month.
The figure shows the four stand-ins for the same constant. The first two are derived from the enum declaration (its position, its name). The last two are values you pick and keep stable. A declaration is something developers edit constantly, which is why the first two are the ones that surprise people.
MappingWhat is storedYou write
@Enumerated(ORDINAL) (the default)position, a small integernothing
@Enumerated(STRING)the constant nameone annotation
@JdbcTypeCode(SqlTypes.NAMED_ENUM)a database enum type (PostgreSQL)one annotation
@Convert with an AttributeConverterany code you choosea converter class
@EnumeratedValue (Jakarta Persistence 3.2)a field of the enum you markone annotation on a field
Going deeper: the vocabulary and where each annotation lives

The default is ORDINAL, and ORDINAL stores a position

If you write nothing, JPA stores the position of the constant: NEW is 0, PAID is 1, SHIPPED is 2. Spelling it out with @Enumerated(EnumType.ORDINAL) changes nothing; the DDL transcript shows that the unannotated field and the explicit one produce the same column. Entity and enum, from Variants.java (the other entities in that file differ only in the annotation on status):
public enum StatusV1 { NEW, PAID, SHIPPED }
@Entity(name = "OrdV1")
@Table(name = "orders")
public static class OrdV1 implements Row {
    @Id
    public Long id;
    @Enumerated(EnumType.ORDINAL)
    public StatusV1 status;
Hibernate 7 also creates a check constraint so that a number outside the enum cannot be stored. Here is the DDL it produced, read back from the database catalog (transcript 01-ddl.txt):
-- @Enumerated(ORDINAL)
   column type: smallint
   check: CHECK (((status >= 0) AND (status <= 2)))
So the column is a smallint limited to 0 to 2. Keep that check in mind: it is both the only thing standing between you and silent corruption in the next section, and the thing that will block your new constant.
Going deeper: the same on H2, and the other mappings side by side On H2 the ORDINAL column is TINYINT with "STATUS" BETWEEN 0 AND 2. The full per-mapping DDL on both databases is in 01-ddl.txt. Two notes from that file: on H2 a plain @Enumerated(STRING) becomes an ENUM column, while on PostgreSQL it becomes varchar(255) plus a check listing the names; and @JdbcTypeCode(SqlTypes.NAMED_ENUM) on H2 gives an unconstrained CHARACTER VARYING with no check at all, because H2 has no named types. Test enum constraints on the database you ship, not on H2.

Insert one constant in the middle and old rows change meaning

Release 2 adds CANCELLED between NEW and PAID, because that is where it reads best:
public enum StatusMid { NEW, CANCELLED, PAID, SHIPPED }
To reproduce a deployment honestly, the test writes three orders with the release 1 classes, then opens a second SessionFactory with the release 2 classes on the same database, with schema generation off, as in production (T02_ReleaseTest.java). Output from 02-release-two.txt on PostgreSQL:
Stored in the table (never changed)row 1: 0row 2: 1row 3: 2Release 1 enum: what the numbers meant0 NEW1 PAID2 SHIPPEDRelease 2 enum: what they mean now0 NEW1 CANCELLED2 PAID3 SHIPPEDRow 2 was a paid order. Release 2 reads the stored 1 and shows CANCELLED. Row 3 was shipped and now reads as PAID.No error, no log line, no changed row: the arrows are drawn by the enum declaration alone.The only thing that stops this at write time is a database check constraint, covered below.
The figure is the whole bug. The table never changed; the list that interprets the numbers did, so the stored 1 now means CANCELLED. The transcript confirms it:
-- ORDINAL, CANCELLED inserted in the middle   (release 2 enum: NEW, CANCELLED, PAID, SHIPPED)
   stored by release 1 : [1 | 0, 2 | 1, 3 | 2]
   release 2 reads     : [NEW, CANCELLED, PAID]
   release 2 writes SHIPPED : FAILS org.hibernate.exception.ConstraintViolationException <- org.postgresql.util.PSQLException
                         ERROR: new row for relation "orders" violates check constraint "orders_status_check"
Read the two results together. The paid order is now cancelled and the shipped one is now paid, with no error. And writing SHIPPED fails, because SHIPPED is now position 3 and the release 1 check only allows 0 to 2.
The check constraint is what turns a loud failure into a quiet one, or the reverse. Inserting at the end hides the corruption (nothing existing moves) but the first write of the new constant is refused. Inserting in the middle corrupts reads at once. If someone has dropped the generated check, a stored position outside the enum fails with a raw java.lang.ArrayIndexOutOfBoundsException: in 07-queries.txt a stored 7 on a three-constant enum reads as Index 7 out of bounds for length 3.
Going deeper: appending instead, and what the matrix says on H2 too Appending CANCELLED as the last constant keeps old rows correct (release 2 reads : [NEW, PAID, SHIPPED] in the transcript) but still fails on the first write of the new value, for the check-constraint reason above. The same transcript repeats every scenario on H2 with different error text: Check constraint violation for ordinals, and for H2’s ENUM column Value not permitted for column. Everything is asserted in T02_ReleaseTest.java, so a Hibernate upgrade that changes any of it fails the build.

STRING stores the name: safer, but the name becomes a contract

@Enumerated(EnumType.STRING) writes PAID as the text PAID. Inserting or reordering constants no longer moves anything, which fixes the previous section:
@Entity(name = "StrV1")
@Table(name = "orders")
public static class StrV1 implements Row {
    @Id
    public Long id;
    @Enumerated(EnumType.STRING)
    public StatusV1 status;
The cost is that the constant’s name is now persisted data. Rename PAID to PAYMENT_RECEIVED in the enum and every old row names a constant that no longer exists. Transcript 02-release-two.txt:
-- STRING, PAID renamed PAYMENT_RECEIVED   (release 2 enum: NEW, PAYMENT_RECEIVED, SHIPPED)
   stored by release 1 : [1 | NEW, 2 | PAID, 3 | SHIPPED]
   release 2 reads     : FAILS java.lang.IllegalArgumentException
                         No enum constant com.ankurm.enums.Variants.StatusRen.PAID
This one is at least loud: the query that touches the old row throws, and the message names the missing constant. An IDE rename of an enum constant is a one-click refactor that now needs a data migration, which is the part IDEs cannot do for you. Adding a constant is refused by the check for the same reason as before; writing CANCELLED on PostgreSQL fails with the same orders_status_check violation.
Going deeper: the names in the generated check On PostgreSQL the check lists the names, so a rename needs the order drop the check, update the rows, add the check, in that sequence (the rows would violate the old check, and the new constant would violate the old one). The exact statements are in the migrations accordion below, and 01-ddl.txt shows the check text Hibernate generates for STRING.

Why adding a constant fails, and why hbm2ddl=update does not help

The failures above share one cause. Hibernate generated the column and its check once, from release 1’s enum, and nothing regenerates them when release 2 starts.
1. The Java enum (you edit this in every release)NEW, PAID, SHIPPED becomes NEW, PAID, SHIPPED, CANCELLED2. The mapping (ORDINAL, STRING, converter …)decides what is written and how it is read back; adding a constant changes nothing here3. The column and its check constraint (created once)status in (NEW, PAID, SHIPPED) refuses CANCELLED until somebody changes it with SQLLayer 1 moves with the code, layer 3 moves only with a migration. Every failure in this article is the gap between them.
The figure puts the three layers side by side. A release edits the top one. The check lives in the bottom one, so the code that reads fine in tests (on a fresh schema, where Hibernate builds the check from the new enum) fails in production on the first write of the new value. That is the classic “works on my machine, fails after deploy” shape for enums. The tempting fix is hibernate.hbm2ddl.auto=update. The test starts release 2 with update on a database created by release 1 and then writes CANCELLED (T04_UpdateTest.java, 05-hbm2ddl-update.txt):
== PostgreSQL 18
-- ORDINAL
   write CANCELLED : FAILS ERROR: new row for relation "orders" violates check constraint "orders_status_check"
-- STRING
   write CANCELLED : FAILS ERROR: new row for relation "orders" violates check constraint "orders_status_check"
-- NAMED_ENUM
   write CANCELLED : FAILS ERROR: invalid input value for enum statusv1: "CANCELLED"
All three still fail after update, on H2 too. The test asserts this, so it is a measured result for 7.4.17, not a memory. Use a migration tool (Flyway or Liquibase) for enum changes.
Going deeper: the migration each change needs, run for real on PostgreSQL 18 Each recipe below was executed by T05_FixTest.java and the result is in 06-migrations.txt. For the ORDINAL insert-in-the-middle, the data has to be renumbered first:
db1.exec("alter table orders drop constraint orders_status_check");
db1.exec("update orders set status = status + 1 where status >= 1");
db1.exec("alter table orders add constraint orders_status_check check (status between 0 and 3)");
For appending to a STRING column, or renaming (note the order: drop, update, add):
db1.exec("alter table orders drop constraint orders_status_check");
db1.exec("update orders set status = 'PAYMENT_RECEIVED' where status = 'PAID'");
db1.exec("alter table orders add constraint orders_status_check check (status in ('NEW', 'PAYMENT_RECEIVED', 'SHIPPED'))");
And the result lines, quoted:
== ORDINAL: insert CANCELLED between NEW and PAID
   stored    : [1 | 0, 2 | 2, 3 | 3]
   release 2 reads : [NEW, PAID, SHIPPED]
== STRING: rename PAID to PAYMENT_RECEIVED
   release 2 reads : [NEW, PAYMENT_RECEIVED]

PostgreSQL native enums: the database enforces the list

PostgreSQL can declare a type of its own, CREATE TYPE statusv1 AS ENUM (...), and a column of that type accepts only its labels. Hibernate maps to it with one extra annotation:
@Entity(name = "NatV1")
@Table(name = "orders")
public static class NatV1 implements Row {
    @Id
    public Long id;
    @Enumerated(EnumType.STRING)
    @JdbcTypeCode(SqlTypes.NAMED_ENUM)
    public StatusV1 status;
Hibernate created the type and a column of that type, and no check constraint is needed because the type is the constraint (01-ddl.txt):
-- @Enumerated(STRING) + @JdbcTypeCode(NAMED_ENUM)
   column type: statusv1
   enum labels: NEW, PAID, SHIPPED
You do not have to annotate every attribute. Setting hibernate.type.prefer_native_enum_types=true makes a plain @Enumerated(STRING) use the native type on PostgreSQL; the transcript 04-prefer-native.txt shows column type: character varying(255) with the setting off and column type: statusv1 with it on. On H2 the setting changes nothing, because H2 shows ENUM either way.
ADD VALUEappended at the endADD VALUE BEFOREinserted in the middleRENAME VALUErows follow the renameDROP VALUEnot implementedADD VALUE then use it, in one transactionrefused with: unsafe use of new value (run the ALTER TYPE in its own earlier migration step)Native enums make adding and renaming cheap and removing impossible. Check constraints are the reverse: every change, removal included, is one DROP and one ADD.
The figure summarises what a native type lets you do afterwards. Adding and renaming are cheap, one statement each and the rows follow. Removing a label is impossible. The transcript 03-native-enum.txt has the exact messages:
   write CANCELLED before ALTER TYPE : org.hibernate.exception.DataException <- org.postgresql.util.PSQLException
                                       ERROR: invalid input value for enum statusv1: "CANCELLED"
   after ALTER TYPE statusv1 ADD VALUE 'CANCELLED' : OK, rows [1 | PAID, 10 | CANCELLED]
   RENAME VALUE 'PAID' TO 'PAYMENT_RECEIVED' : row 1 is now [PAYMENT_RECEIVED]
   ALTER TYPE ... DROP VALUE : ERROR: dropping an enum value is not implemented
   ADD VALUE then INSERT using it in ONE transaction : ERROR: unsafe use of new value "CANCELLED" of enum type statusv1
Two native-enum traps. First, a database that ships a list of labels cannot also lose one: plan renames, not removals. Second, the “unsafe use of new value” error means ADD VALUE and the first write that uses it cannot share a transaction. With Flyway that means the ALTER TYPE goes in its own earlier migration, not alongside the code that inserts the value.
Going deeper: label order is not the declaration order ORDER BY on a native enum sorts by label position, not by name. In this run Hibernate created the type for an enum declared NEW, PAID, SHIPPED, CANCELLED with the labels in alphabetical order, so ORDER BY status returned [CANCELLED, NEW, PAID, SHIPPED]. A type written by hand in workflow order sorted as [NEW, PAID, SHIPPED, CANCELLED]. I did not read Hibernate’s source for why the labels come out alphabetical; the observation is from the transcript 03-native-enum.txt. If you need workflow order from ORDER BY, own the CREATE TYPE in a migration and map with hbm2ddl off. Also see the PostgreSQL docs on enumerated types and ALTER TYPE.

Converters and @EnumeratedValue: store a code you control

The robust answer is to stop persisting anything that developers edit. Give each constant a short code, store the code, and the position and the name become free to change. Classic JPA does this with an AttributeConverter:
public enum CodedV1 {
    NEW("N"), PAID("P"), SHIPPED("S");

    public final String code;

    CodedV1(String code) {
        this.code = code;
    }
@Converter
public static class CodedV1Converter implements AttributeConverter<CodedV1, String> {
    @Override
    public String convertToDatabaseColumn(CodedV1 v) {
        return v == null ? null : v.code;
    }

    @Override
    public CodedV1 convertToEntityAttribute(String db) {
        return db == null ? null : CodedV1.of(db);
    }
}
@Entity(name = "ConvV1")
@Table(name = "orders")
public static class ConvV1 implements Row {
    @Id
    public Long id;
    @Convert(converter = CodedV1Converter.class)
    public CodedV1 status;
Jakarta Persistence 3.2 made the converter unnecessary for this case. Mark the code field with @EnumeratedValue and tell the attribute to use it:
public enum EvV1 {
    NEW("N"), PAID("P"), SHIPPED("S");

    @EnumeratedValue
    private final String code;

    EvV1(String code) {
        this.code = code;
    }
}
@Entity(name = "EvEntV1")
@Table(name = "orders")
public static class EvEntV1 implements Row {
    @Id
    public Long id;
    @Enumerated(EnumType.STRING)
    public EvV1 status;
Both stored the codes N, P, S. Now release 2 inserts CANCELLED in the middle and renames PAID, and the old rows read back correctly:
-- CONVERTER (codes N/P/S), CANCELLED inserted + PAID renamed   (release 2 enum: NEW, CANCELLED(C), PAYMENT_RECEIVED(P), SHIPPED)
   stored by release 1 : [1 | N, 2 | P, 3 | S]
   release 2 reads     : [NEW, PAYMENT_RECEIVED, SHIPPED]
   release 2 writes CANCELLED : FAILS org.hibernate.exception.ConstraintViolationException <- org.postgresql.util.PSQLException
                         ERROR: new row for relation "orders" violates check constraint "orders_status_check"
Reads survive both changes untouched, which no other mapping managed. The write still fails, and that surprised me while building the module: Hibernate generated a check constraint even for the converter, listing the converted codes (01-ddl.txt), so C is refused until the check is replaced. The migration is one drop and one add, with no data touched; see the recipe in the section above. The same holds for @EnumeratedValue, which produced the identical check.
Two things that go wrong with codes. A converter has to throw on an unknown code, and it does: a stored X (after the check was dropped) fails the read with Unknown CodedV1 code 'X' inside a PersistenceException, as the transcript 07-queries.txt shows. And @EnumeratedValue on a String code needs @Enumerated(EnumType.STRING) on the attribute: without it Hibernate refuses to start, because the default ORDINAL wants an integer code. The message, from 01-ddl.txt, is @EnumeratedValue for EnumType.ORDINAL must be placed on a field whose type is byte, short, or int.
Going deeper: queries and sorting with codes HQL on a converted attribute works as usual: with a parameter the SQL is where cv1_0.status=?, and with an enum literal written in the HQL text Hibernate inlines the code, where cv1_0.status='P' (07-queries.txt). ORDER BY sorts by what is stored, so the same four constants sorted as [NEW, PAID, SHIPPED, CANCELLED] under ORDINAL, [CANCELLED, NEW, PAID, SHIPPED] under STRING, and by code [C, N, P, S] under the converter. If the order matters to a report, sort in the query with a case expression or an explicit sort column rather than relying on the stand-in.

Which one should you use?

Results from this module, per mapping, after the three changes a release usually makes. “Reads” means whether existing rows stay correct; “write” means whether the new constant can be stored on the generated schema.
MappingInsert in the middleRename a constantNew constant needs
ORDINALold rows silently re-labelledsafe (the position does not move)check change, plus renumbering if inserted in the middle
STRINGsafeold rows throw on readcheck change
NAMED_ENUM (PostgreSQL)saferename with ALTER TYPE ... RENAME VALUEALTER TYPE ... ADD VALUE in its own transaction
Converter / @EnumeratedValuesafesafecheck change only, no data touched
The ORDINAL rename is safe only because the position does not move; the same fact is what breaks the insert. The sources for each cell are the transcripts 02-release-two.txt and 06-migrations.txt.
Going deeper: the two “safe” cells that were also run An ORDINAL rename and a STRING insert in the middle were each run rather than assumed (PostgreSQL section of 02-release-two.txt):
-- ORDINAL, PAID renamed PAYMENT_RECEIVED   (release 2 enum: NEW, PAYMENT_RECEIVED, SHIPPED)
   release 2 reads     : [NEW, PAYMENT_RECEIVED, SHIPPED]
-- STRING, CANCELLED inserted in the middle   (release 2 enum: NEW, CANCELLED, PAID, SHIPPED)
   release 2 reads     : [NEW, PAID, SHIPPED]
Note that safe here means the reads are right; the new constant still needs the check change in every row of the table above except the native enum.
The honest default. If the column is new and the values are a closed, small set that business code depends on, store a code you control (@EnumeratedValue on Jakarta Persistence 3.2, or a converter on older versions) and give the column a check or a lookup table. Use STRING when readable data matters more than renames. Use a native enum on PostgreSQL if you are happy to own ALTER TYPE migrations and never remove a label. Avoid ORDINAL for anything that outlives one release. And if the set of values changes often or is edited by users, an enum is the wrong tool: a lookup table with a foreign key is.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.