将枚举映射到具有hibernate注释的表 [英] Mapping enum to a table with hibernate annotation

查看:89
本文介绍了将枚举映射到具有hibernate注释的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表DEAL和表DEAL_TYPE。我想映射这段代码:

I have a table DEAL and a table DEAL_TYPE. I would like to map this code:

public class Deal {
   DealType type;
}

public enum DealType {
   BASE("Base"), EXTRA("Extra");
}

问题是数据已经存在。我很难将类映射到数据库。

The problem is that the data already exist in the database. And I'm having a hard time mapping the classes to the database.

数据库看起来像这样:

   TABLE DEAL {
      Long id;
      Long typeId;
   }

   TABLE DEAL_TYPE {
       Long id;
       String text;
   }

我知道我可以使用一个简单的@OneToMany关系从交易类型,但我宁愿使用枚举。这是可能的吗?

I know I could use a simple @OneToMany relationship from deal to deal type, but I would prefer to use an enum. Is this possible?

我几乎可以使用EnumType.ORDINAL类型工作。但是不幸的是,我的交易类型表中的ID不是顺序的,不能从1开始。

I almost got it working by using a EnumType.ORDINAL type. But unfortunately, my IDs in my deal type table are not sequential, and do not start at 1.

任何建议?

推荐答案

Hibernate在Enum的可怕之处。这是一个奇怪的失败,否则相当不错的ORM。解决它的最简单的方法是将您的Enum声明为自定义的休眠类型。幸运的是,Hibernate写了一个示例实现,你可以逐字逐句地将它们加载到你的应用程序中:

Hibernate is kind of terrible at Enum's. It's a strange failing of an otherwise pretty good ORM. The "easiest" way to get around it is to declare your Enum a custom hibernate type. Fortunately, Hibernate wrote an example implementaiton which you can crib verbatim into your app:

http://www.hibernate.org/265.html

他们甚至包括如何使用它的说明。这是当我最终需要持久枚举时使用的模式。

They even include instructions on how to use it. This is the pattern I use whenever I end up with the need to persist enums.

这篇关于将枚举映射到具有hibernate注释的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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