Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA Enum ORDINAL vs STRING

It's possible to define enumerations in JPA using either

@Enumerated(EnumType.ORDINAL) 

or

@Enumerated(EnumType.STRING) 

I wonder what are advantages and disadvantages of those two definitions?

I heard that ORDINAL performs better (is faster) than STRING with EclipseLink.
Is that true?

like image 313
jst99 Avatar asked Jul 22 '11 11:07

jst99


People also ask

What is enum type ordinal?

ordinal() tells about the ordinal number(it is the position in its enum declaration, where the initial constant is assigned an ordinal of zero) for the particular enum.

How does enum ordinal work?

The ordinal() method returns the order of an enum instance. It represents the sequence in the enum declaration, where the initial constant is assigned an ordinal of '0' . It is very much like array indexes. It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap .

What annotation is used if enum is used in an entity?

The most common option to map an enum value to and from its database representation in JPA before 2.1 is to use the @Enumerated annotation.

How do I map an enum to a column in a database?

To map the Enum to a String database column type, you need to specify the EnumType. STRING value when using the @Enumerated annotation. As expected, the String representation of the Java Enum was used to populate the associated database column value.


2 Answers

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'; 
like image 111
Bohemian Avatar answered Oct 04 '22 06:10

Bohemian


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.

like image 30
Bozho Avatar answered Oct 04 '22 07:10

Bozho