Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum tables in Hibernate/NHibernate

We are using NHibernate, and one of the common patterns we have for storing enum-like information is to define separate tables for the enum, and just make a reference to the ID in the main entity/table that uses the enum. A simple example:

Message
-------
ID (bigint PK)
MessageTypeID (bigint FK)
Body (varchar)

MessageType
-----------
ID (bigint PK)
Value (varchar)

The MessageType table contains a small number of enum values like: SMS, MMS, PSMS, etc.

Is it worth putting enum values in separate tables like this? I guess the pro of the enum is that you can more easily extend it in the future and it's more normalized, but the con is that you have to do a join every time you fetch a Message. Is there a breaking point where you would choose one over the other?

like image 939
Andy White Avatar asked Mar 03 '09 02:03

Andy White


2 Answers

Using enums implies to do not use another table as you are doing right now. It's also faster as you said and so much simpler.

In both cases you can add more options, but the question is: if you add another item in the table are you going to need to recompile the application to add such feature?

I mean, if your application design is coupled and to support a new message type you need to recompile (maybe because you need to include the SMS implementation), it's not worth it to have a separate table, and you should use enums

On the other side, if either your entity lacks of logic (such a Countries, or States table), or your application can plug in a new message type without recompile you should use another table. For this, you could change your table to something like this:

MessageType
-----------
ID (bigint PK)
Value (varchar)
ImplementationType (varchar) (ie: Xyz.SMSSender, Xyz)

Or you could have a separated configuration file, where you can customize the injected dependencies.

like image 57
Diego Jancic Avatar answered Sep 25 '22 01:09

Diego Jancic


I would create a enum in your code with matching ID to your MessageType table. Then on your classes just use that and nHibernate should be able to map it properly.

I've been straying from enum tables, especially when that data does not need to be managed data. Are you going to be adding more and more MessageType's as you go?

like image 26
hunter Avatar answered Sep 22 '22 01:09

hunter