views:

714

answers:

3

It is a quite common situation in our applications that some entity have to be represented by an enum: for example types, categories, status, and things like that.

Often, there are conditions or flows in the code that use the values to decide between one action or another, so the values have to be "known" in some way for the application (i.e. it has to be able to refer to a specific instance to decide instead of referencing the class in a whole). That is why we use enums instead of just a regular class.

The problem is that these entities also need to be stored (or at least referenced) in the database, as fields of other entities. We usually create a table for each entity, to be capable of having referencial integrity checks in these columns, and also that the data have a "meaning" in the database alone without the need to refer to the enum to find out what each id means.

Ideally, the data for these entities should be populated from the data in the enum, but nowadays we have the values duplicated in the db initialization scripts.

It becomes a bit more complicated when an ORM like Hibernate is used.

I'd like to know how other people handles this kind of situation.

I'm not fully comfortable with the idea of having a duplication between an enum and a database table, but I haven't found a better solution yet.

+2  A: 

Try the answers to this question: Ways to save enums in database

Mr. Will
It's a very simmilar question, I haven't found it before. Still, it looks like there is no easy solution, as none of the responses seems to solve the problems.
Sam
+1  A: 

I have the same issue for my JPA/Hibernate app. What I do is dynamically create the enum entry in the database as they're encountered. In this was it auto-populates as needed.

Steve Kuo
A: 

I have the same problem in my application and unfortunately can not see anyone answering it. i would like the ability to automatically match the enum values with that of stored in database. Is there any automatic way?

nataraj