简体   繁体   English

Java enum int值只能与JPA顺序存储吗?

[英]Java enum int value can only be stored sequentially with JPA?

I have a simple enum as follows: 我有一个简单的枚举,如下所示:

public enum Tax {
    NONE(10), SALES(20), IMPORT(30);

    private final int value;
    private Tax(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}


@Entity
public Person {

.........

   private TAX tax = TAX.NONE;
   public TAX getTax() {
      return tax;
   }

   public void setTax(Tax tax) {
      this.tax = tax;
   }

.............
}

When saving a Person object in database via JPA, the value saved in the database is 0 for the object's tax field with the value being TAX.NONE. 通过JPA将Person对象保存在数据库中时,该对象的tax字段在数据库中保存的值为0,其值为TAX.NONE。

Why not 10 saved in the database? 为什么不10保存在数据库中? How can I let JPA save 10 for TAX.NONE in database via JPA? 如何让JPA通过JPA在数据库中为TAX.NONE保存10?

Thanks! 谢谢!

JPA stores the identity of the enum value in the database, either its index (ordinal) or its name (string). JPA将枚举值的标识存储在数据库中,它的索引(常规)或名称(字符串)。 There's no built-in way to retrieve the correct enum instance from a field on the enum, and multiple instances could have the same field value. 没有内置方法可以从枚举中的字段检索正确的枚举实例,并且多个实例可能具有相同的字段值。 If you really want to store a secondary field value in the database, you could write your own converter for your persistence provider. 如果您确实想在数据库中存储辅助字段值,则可以为持久性提供程序编写自己的转换器。

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

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