简体   繁体   English

Java - 使用 Hibernate (HBM) 在数据库中引用枚举(数值)

[英]Java - Referring Enum (number value) in database using Hibernate (HBM)

I am trying to convert the text field in a giant Postgres table which has the values like (1, 2, 3, 4, __ALL) into an enum.我正在尝试将具有 (1, 2, 3, 4, __ALL) 等值的巨大 Postgres 表中的文本字段转换为枚举。 The plan is to update the text field to an enum in the database.计划是将文本字段更新为数据库中的枚举。

I understand that I can't do Enum as follows in Java;我知道我不能在 Java 中按如下方式执行 Enum;

public enum MyEnum {
 1,2,3,4; 
}

I can either do as;我可以这样做;

public enum MyEnum {
  _1,_2,_3,_4;
}

Or:或者:

public enum QuartileNumber {
   ONE("1"), TWO("2"), THREE("3"), FOUR("4"), __ALL("__ALL");
}

My hibernate mapping looks like this;我的休眠映射看起来像这样;

<property name="quartileNumber" column="quartile_number">
      <type name="com.altosresearch.model.PostgreSQLEnumType">
        <param name="enumClass">com.altosresearch.model.QuartileNumber</param>
        <param name="type">12</param>
      </type>
</property> 

Using this mapping and my Java enum (QuartileNumber);使用此映射和我的 Java 枚举 (QuartileNumber);

QuartileNumbers.valueOf("__ALL") - returns '_ALL' (the expected enumClass of com.altosresearch.model.QuartileNumber) QuartileNumbers.valueOf("__ALL") - 返回 '_ALL'(com.altosresearch.model.QuartileNumber 的预期 enumClass)

QuartileNumbers.valueOf("ONE") - returns 'ONE' (which will be obviously rejected in the database as it doesn't match one of the DB enum values (1, 2, 3, 4, __ALL). QuartileNumbers.valueOf("ONE") - 返回 'ONE'(显然会在数据库中被拒绝,因为它与数据库枚举值之一(1、2、3、4、__ALL)不匹配。

So, I am able to insert correctly only the value '__ALL' into the table.因此,我只能将值 '__ALL' 正确插入到表中。 Need suggestions to insert values 1, 2, 3, 4 as well here.需要建议在此处插入值 1、2、3、4。 Thanks!谢谢!

Note: Trying to use the same existing values in the database ('1','2','3','4','__ALL') to avoid the code changes.注意:尝试使用数据库中相同的现有值('1'、'2'、'3'、'4'、'__ALL')以避免代码更改。

What can help here is to use the AttributeConverter for the Enum.在这里可以提供帮助的是将 AttributeConverter 用于枚举。

Here is a link from Thorben Janssen https://thoughts-on-java.org/jpa-21-type-converter-better-way-to/这是来自 Thorben Janssen 的链接https://thoughts-on-java.org/jpa-21-type-converter-better-way-to/

how to save in the DB values : 1,2,3,4,__ALL from the Enum definition:如何在数据库中保存值:枚举定义中的 1,2,3,4,__ALL :

public enum QuartileNumber {
   ONE("1"), TWO("2"), THREE("3"), FOUR("4"), __ALL("__ALL");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM