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

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

问题描述

我有一个表 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 在 Enums 中有点糟糕.这是一个原本相当不错的 ORM 的奇怪失败.解决它的最简单"方法是将您的 Enum 声明为自定义休眠类型.幸运的是,Hibernate 编写了一个示例实现,您可以将其逐字写入您的应用程序:

Hibernate is kind of terrible at Enums. 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 implementation 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.

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

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