It\'s possible to define enumerations in JPA using either
@Enumerated(EnumType.ORDINAL)
or
@Enumerated(EnumType.STRING)
It depends on your application, if there are more chances that you will add more enums use the String type, if there are more chances that you will change the name of your enums use Ordinal.
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.STRING)
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 occupe more size than an ordinal data. Maybe are usefull 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