JPA Enum ORDINAL vs STRING

It's likely that ORDINAL is more efficient, but that's minor. There are a few downsides to ORDINAL:

  • it is less readable in the database
  • if you reorder your enum definitions the database will not be consistent.

With STRING you can't rename your enums.

Pick one of them and use it throughout the whole application - be consistent.

If your database is going to be used by other clients/languages - use STRING, it's more readable.


I always go STRING.

Speed is rarely the most important issue - readability and maintainability are more important.

I use STRING because it's a lot easier to manually inspect rows from the database, but more importantly, I can do two things, without touching the database, the ORDINAL can't handle:

  1. I can change the order of my enums
  2. I can insert new enums in the middle of the enum list

Both of these changes will alter the ordinal values of the enums already in use in the database, thus breaking existing data if you are using ORDINAL.

If you change an enum value (not that common), handling it is simple:

UPDATE table SET enum_column = 'NEW_ENUM_NAME' where enum_column = 'OLD_ENUM_NAME';

I prefer the use of Ordinal but this really depends on the use.

By example:

You have a enum, to save all your user states, in this case the order doesn't matter, and you can add more states in the future (Best use is @Enumerated(EnumType.ORDINAL)):

public enum UserStates { ACTIVE, DELETED, PENDING }

But now, you have an enum, to save the Plantes in the Solar System (Best use @Enumerated(EnumType.STRING)):

public enum Planets {MERCURY,VENUS,EARTH,MARS,JUPITER,SATURN,URANUS,NEPTUNE,PLUTO,NINE}

Now think that you want reorder your planets, with @Enumerated(EnumType.ORDINAL) you can't, because your database can't know the new order in your Java file.

You can reorder your Plantes using @Enumerated(EnumType.STRING) because your Planet is linked to the enum name, not the enum order.

Anyway, you can modify your @Enumerated(EnumType.ORDINAL)enums because they are linked to the order, but you can't change your @Enumerated(EnumType.STRING)enums because they will use like new enums.

String types are more readable in the Database, but will occupy more size than an ordinal data. Maybe are useful if the database is used by more clients, but it's better have a good documentation of the software than save 1000 times "EARTH" than "4"

USERSTATE
------------
ID | STATE |
------------
1 | 1
2 | 2
3 | 1

Planets
------------
ID | Name |
------------
1 | EARTH
2 | EARTH
3 | MARS
4 | EARTH