【问题标题】:Hibernate Complex type saveHibernate 复杂类型保存
【发布时间】:2009-04-30 09:55:05
【问题描述】:

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

public enum Gender { MALE,FEMALE }

主类是

public Person { String name; Gender gender; }

如果这个Person类要持久化在一个表中,hbm映射应该怎么做?

【问题讨论】:

    标签: hibernate enums


    【解决方案1】:

    您没有提到您使用的是 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)
        {
        }
    }
    

    这在很多方面都对我很有效。如果您更改枚举中元素的顺序,它仍然有效,这也意味着您可以看到该值在 db 中的含义,从而更轻松地编写临时查询! :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-16
      • 2014-08-08
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多