views:

190

answers:

1

i need to persist an object whose one of the properties is an enum. This whole structure have to be saved in a single table. The enum defines the possible genders

public enum Gender { MALE,FEMALE }

The main class is

public Person { String name; Gender gender; }

If this Person class has to be persisted in a single table, how should the hbm mapping be?

+2  A: 

You haven't mentioned if you are using Java or .Net but I will give you the solution that I found for .Net and so you can translate it to Java if need be. I found a post which suggests the use of a generic type which allows you to declare the enum as a field in the table as text so you can see the name of the value in the table.

Click Me!

I changed mine slightly to restrict the length of the column.

/// <summary>
/// This class allows enums to be stored as a string in the database
/// </summary>
/// <typeparam name="T">The Enum Type</typeparam>
public class EnumMapper<T> : EnumStringType
{
    /// <summary>
    /// The default constructor which defines that the maximum length of
    /// an enum string column in the datbase is 30 characters.
    /// </summary>
    public EnumMapper() : base(typeof(T), 30)
    {
    }
}

This has worked great for me in a number of ways. If you change the order of the elements in the enum, it still works and it also means you can see what the value means in the db making writing ad-hoc queries easier! :)

Penfold