Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisting Enums in database tables

I have an order which has a status (which in code is an Enum). The question is how to persist this. I could:

  1. Persist the string in a field and then map back to enum on data retrieval.
  2. Persist this as an integer and then map back to enum on data retrieval.
  3. Create separate table for enum value and do a join on data retrieval.

Thoughts?

like image 833
leora Avatar asked Mar 23 '09 16:03

leora


People also ask

Can we store enum in database?

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.

Can enum values be persisted?

Enum values are persisted in the database, regardless of the enum that is extended. Therefore, when an enum is made extensible, the enum values that are used on any system will prevail.

What is enum in database?

An ENUM is a string object with a value chosen from a list of permitted values that are enumerated explicitly in the column specification at table creation time.


1 Answers

If this is a fixed list (which it seems it is, or else you shouldn't store it as an enum), I wouldn't use #1.

The main reason to use #3 over #2 is for ease of use with self-service querying utilities. However, I'd actually go with a variant of #2: Store the value as an integer and map to an enum on data retrieval. However, also create a table representing the enum type, with the value as the PK and the name as another column. That way it's simple, quick, and efficient to use with your code, but also easy to get the logical value with self-service querying and other uses that don't use your data access code.

like image 77
Jonathan Rupp Avatar answered Oct 02 '22 20:10

Jonathan Rupp