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.
First of all, in order to save enum values in a relational database using JPA, you don't have to do anything. By default, when an enum is a part of an entity, JPA maps its values into numbers using the ordinal() method. What it means is that without customizations JPA stores enum value as numbers.
Enum types are more convenient for coding. For infrequent releases, or if you often have new/deleted/changed values, use a database table. For static sets of values, or if you release code all the time, use an enum.
Learn to create Java enum where each enum constant may contain multiple values. We may use any of the values of the enum constant in our application code, and we should be able to get the enum constant from any of the values assigned to it.
The Enum constructor can accept multiple values.
Try the answers to this question: Ways to save enums in database
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With