• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A (dangerous) idea for persisting enums

 
Juan Tamayo
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone,

I have been trying to store a Java enum in my database using JPA/EclipseLink. After looking through many options, none of which seems to be "perfect" I thought a small trick might work. I can create an enum with "two" representations: a short one to store in the DB and a descriptive one to use in my code. It would be something like this:



Then I can annotate my persistent fields like this:



so I can store "CR" in the DB, and write something like this in my Java code:



Is this a dumb idea? Will it explode a year from now? I think it covers many cases except the switch statement, where the compiler complains because Status.CREATED is not a constant (which I think it is).

Thanks for your suggestions!!

Juan M
 
Angel Taveras
Ranch Hand
Posts: 84
Eclipse IDE Hibernate Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It seens ok, but i don't understand the use of the static fields on the ENUM, you just could use a Constructor with an String to make the representation that i believe you wanna to achieve with
those static fields,

Regards,
 
Raf Szczypiorski
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you think storing "CR" instead of "CREATED" is much better? If you are concerned about storage, why don't you like storing an int (Enumerated(EnumType.ORDINAL))?
 
Angel Taveras
Ranch Hand
Posts: 84
Eclipse IDE Hibernate Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Raf said i prefer to store in the DB base the whole name it will make more sense in term of usability when making the querys. Or
you can use the ordinals just as Raf said but you have to take into consideration that when you wanna aggregate new members to
the ENUM must be on the bottom of the already defined members,

Regards
 
Juan Tamayo
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are several reasons behind my solution:

1. I don't want to store the Ordinal in the DB because it is too brittle: I can ruin my data by only rearranging the constants, or by adding another one in the middle of the existing ones.
2. I don't want to store the entire enum name because it might change (a refactoring, for example, to make the code clearer) and because it might be too long (VISIT_SCHEDULING_PENDING, for example).

I think this way the names in Java are clear, and the constants in the DB are short.

Regards,

Juan M
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic