Hibernate 中的枚举,作为枚举持久化 [英] Enum in Hibernate, persisting as an enum

查看:32
本文介绍了Hibernate 中的枚举,作为枚举持久化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 MySQL 数据库中,有一列gender enum('male','female')"

In my MySQL database, there's the column "gender enum('male','female')"

我已经创建了我的枚举com.mydomain.myapp.enums.Gender",并在我的 Person 实体中定义了性别".

I've created my enum "com.mydomain.myapp.enums.Gender", and in my Person entity I'm defined "Gender gender".

现在我想在我的 MySQL 数据库中保留枚举类型,但是当我启动我的应用程序时,我得到:

Now I'd want to keep the enum type in my MySQL database, but when I launch my application I get:

MyApp.Person 中性别列的列类型错误.找到:枚举,预期:整数

Wrong column type in MyApp.Person for column Gender. Found: enum, expected: integer

这是为什么?这相当于我用@Enumerated(EnumType.ORDINAL)"注释了我的性别",而我没有.EnumType 似乎只能是 ORDINAL 或 STRING,那么我如何指定它应该将该字段视为枚举,而不是 int?(不是说差别太大,但足以让它为此感到不安.)

Why is this? This would be the equivalent as if I'd annotated my "Gender gender" with "@Enumerated(EnumType.ORDINAL)", which I haven't. EnumType seems only to be able to be either ORDINAL or STRING, so how do I specify that it should treat the field as an enum, not as an int? (not that there's much difference, but enough for it to get upset about it.)

推荐答案

我的理解是 MySQL 枚举类型是非常专有的,Hibernate 并没有很好的支持,参见 此评论来自 Gavin King(这个相关问题有点不同,但这不是重要的部分).

My understanding is that MySQL enum type is very proprietary and not well supported by Hibernate, see this comment from Gavin King (this related issue is a bit different but that's not the important part).

因此,我实际上认为您必须使用自己的 UsereType,我建议您使用 中的灵活解决方案 - 工作版本="https://www.hibernate.org/272.html" rel="noreferrer">Java 5 EnumUserType(参见 Appfuse 的 Java 5 Enums Persistence with Hibernate 示例).

So, I actually think that you'll have to use your own UsereType and I'd recommend to use the Flexible solution - working version from the Java 5 EnumUserType (see Appfuse's Java 5 Enums Persistence with Hibernate for an example).

就我个人而言,我只是忘记了使用 MySQL 枚举的想法,我不相信好处"值得(参见 这个答案 了解更多详情).

Personally, I'd just forget the idea to use MySQL enum, I'm not convinced that the "benefits" are worth it (see this answer for more details).

这篇关于Hibernate 中的枚举,作为枚举持久化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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