使用枚举作为ID [英] Using enum as id

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

问题描述

使用JPA,我们可以将枚举定义为实体的ID吗?

Using JPA, can we define an enum as id of an entity?

我尝试了以下操作:

public enum AssetType {
   ....
}

@Entity
@IdClass(AssetType.class)
public class Adkeys {

   private AssetType type;

   @Id
   @Enumerated(EnumType.STRING)
   @Column(nullable = false)
   public AssetType getType() {
      return type;
   }

}

它使用OpenJPA抱怨:

Using OpenJPA, it complains:

org.apache.openjpa.persistence.ArgumentException:由类型"class aa.Adkeys"指定的id类"class aa.AssetType"没有公共的无参数构造函数.

org.apache.openjpa.persistence.ArgumentException: The id class "class aa.AssetType" specified by type "class aa.Adkeys" does not have a public no-args constructor.

所以我的问题是:

  • 我们应该能够在JPA上将枚举用作ID的实体吗? (即OpenJPA中存在一个错误)
  • 还是我在某个地方犯了错误?
  • 有没有解决此问题的方法?

推荐答案

JPA规范没有说这是可能的:

The JPA spec doesn't say this is possible:

2.1.4主键和实体标识

2.1.4 Primary Keys and Entity Identity

主键(或复合主键的字段或属性)应为以下类型之一:任何Java原语类型;任何原始包装器类型; java.lang.String; java.util.Date; java.sql.Date.但是,一般而言,绝不能在主键中使用近似数字类型(例如,浮点类型).主键使用其他类型的实体将不可移植.

The primary key (or field or property of a composite primary key) should be one of the following types: any Java primitive type; any primitive wrapper type; java.lang.String; java.util.Date; java.sql.Date. In general, however, approximate numeric types (e.g., floating point types) should never be used in primary keys. Entities whose primary keys use types other than these will not be portable.

如果您确实想为给定实体提供编译时固定数量的记录,则可以使用Stringint主键并为其分配AssetType.FOO.name()AssetType.FOO.ordinal()

If you really want to have a compile-time fixed number of records for a given entity, you can use a String or int primary key and assign it AssetType.FOO.name() or AssetType.FOO.ordinal()

此处不可移植意味着某些持久性提供程序可能支持其他功能,但可能不适用于其他提供程序.与枚举一样-如果持久性提供程序对此有特殊支持,则它不会尝试实例化它,而是在检查class.isEnum()之后专门对其进行处理,然后它可能会起作用.但是似乎您的持久性提供程序没有执行此操作.

And non-portable here means that some persistence provider may support other things, but it might not work for another provider. As with the enum - if the persistence provider has special support for it, that does not try to instantiate it, but rather processes it specially after checking if class.isEnum(), then it might work. But it seems your persistence provider doesn't do this.

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

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