Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to store enum values in database - String or Int

Tags:

I have a number of enums in my application which are used as property type in some classes.

What is the best way to store these values in database, as String or Int?

FYI, I will also be mapping these attribute types using fluent Nhibernate.

Sample code:

public enum ReportOutputFormat {     DOCX,     PDF,     HTML }  public enum ReportOutputMethod {     Save,     Email,     SaveAndEmail }  public class ReportRequest {     public Int32 TemplateId     {         get { return templateId; }         set { templateId = value; }     }     public ReportOutputFormat OutputFormat     {         get { return outputFormat; }         set { outputFormat = value; }     }      public ReportOutputMethod OutputMethod     {         get { return outputMethod; }         set { outputMethod = value; }     } } 
like image 529
inutan Avatar asked Oct 23 '09 09:10

inutan


People also ask

Is enum string or int?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

Should I use enum or int?

Both ints and enums can use both switch or if-then-else, and memory usage is also minimal for both, and speed is similar - there's no significant difference between them on the points you raised. However, the most important difference is the type checking. Enums are checked, ints are not.

Should I use enums or strings?

Strings are general things, enums are specific. Partly, it is to prevent mistakes. Using strings you can have spelling and case differences that can cause mistakes. If you misspell/mis-case an enum you will get a compile error.

How is enum stored 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.


1 Answers

The implementation is easy in both cases, and performance differences should be minor.

Therefore, go for the meaning : the Strings are more meaningful than numbers, so use the String.

like image 123
KLE Avatar answered Sep 21 '22 10:09

KLE