如何在 Hibernate 中映射一组枚举类型? [英] How to map a set of enum type in Hibernate?

查看:21
本文介绍了如何在 Hibernate 中映射一组枚举类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在hibernate中,是否可以定义一个类到一组枚举的映射?

In hibernate, is it possible to define a mapping for a class to a set of enums?

我已经能够找到有关如何定义集合映射的示例,并且能够找到有关如何映射枚举的单独示例,但我无法弄清楚如何为类定义枚举.

I've been able to find examples of how to define mappings of Sets and I've been able to find separate examples for how to map Enums, but I cannot figure out how to define a of Enums for a class.

谁能给我举个例子?

这是在现有应用程序之上构建的,因此我无法更改数据库架构.

This is being built on top of an existing application, so I cannot alter the database schema.

这是我希望建模的关系.Wicket 是一个普通的类,WicketType 是一个 Java 枚举.

This is the relation I wish to model. Wicket is a normal class and WicketType is a Java Enum.

+----------------+    +------------+    +------------+
| Wicket         |    | Ref Table  |    | WicketType |
+----------------+    +------------+    +------------+
| INT     | W_ID |    |            |    | W_TypeId   |
| ....    |      | FK | W_ID       | FK | WicketType |
| INT     | TYPE |----| W_TypeId   |----|            |
+----------------+    +------------+    +------------+

再次感谢

推荐答案

不做你需要的吗?

为了详细说明轻率的初始响应,参考提供了一种使用枚举的序数来映射枚举的方法.

To elaborate on the flippant initial response, the reference provides a means to use the ordinal of the enum to map enumerations.

在这种情况下,它实际上比看起来更简单,因为您将枚举托管在一个集合中,您需要为 WicketType 提供一个访问器到 IntEnumUserType 的子类型,超类型将负责映射实例的序数.

In this case it's actually simpler than it looks, because you are hosting the enums in a set, you need to provide an accessor for the WicketType to the sub-type of IntEnumUserType, the super-type will take care of mapping the ordinal to the instance.

package test;

public class WicketTypeState extends IntEnumUserType<WicketType> {
    private WicketType wicketType;

public WicketTypeState() {
    // we must give the values of the enum to the parent.
    super(WicketType.class, WicketType.values());
}

    public WicketType getWicketType() {
        return wicketType;
    }

    public void setWicketType(final WicketType wicketType) {
        this.wicketType = wicketType;
    }
}

定义枚举表的映射:

<hibernate-mapping package="test">  
  <class name="Wicket" table="Wicket">
    <id name="id" column="ID"/>
    <set name="wicketTypes" table="WicketType" inverse="true">
      <key column="ID"/>
      <one-to-many class="test.WicketTypeState"/>
    </set>
  </class>
</hibernate-mapping>

然后对于具有枚举集合的类型,为该属性定义一个集合映射:

Then for the type with the set of enums, define a set mapping for that property:

<hibernate-mapping package="test">
  <class name="WicketTypeState" lazy="true" table="WicketType">
    <id name="WicketType" 
      type="test.WicketTypeState"/>
  </class>
</hibernate-mapping>

这适用于我的盒子(tm),如果您需要更多信息,请告诉我.

This worked on my box(tm), let me know if you need any more info.

这篇关于如何在 Hibernate 中映射一组枚举类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆