Hibernate Complex类型保存

时间:2009-04-30 09:55:06

标签: hibernate enums

我需要持久保存一个属性为枚举的对象。整个结构必须保存在一个表中。 枚举定义了可能的性别

public enum Gender { MALE,FEMALE }

主要课程是

public Person { String name; Gender gender; }

如果此Person类必须保存在单个表中,hbm映射应该如何?

1 个答案:

答案 0 :(得分:2)

你没有提到你是使用Java还是.Net但是我会给你找到我为.Net找到的解决方案,所以你可以根据需要将它翻译成Java。我发现了一个帖子,它建议使用泛型类型,它允许你将枚举声明为表格中的字段作为文本,这样你就可以看到表格中值的名称。

Click Me!

我稍微改变了我的方法以限制色谱柱的长度。

/// <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)
    {
    }
}

这在很多方面对我有用。如果你改变枚举中元素的顺序,它仍然可以工作,这也意味着你可以看到数据库中的值意味着什么,使得编写即席查询更容易! :)