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; } } }
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.
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.
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.
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.
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.
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