Using enumeration as id

Using JPA, can we define an enumeration as an id of an object?

I tried the following:

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;
   }

}

Using OpenJPA, he complains:

org.apache.openjpa.persistence.ArgumentException: class id "class aa.AssetType", specified by type "class aa.Adkeys", has no public constructor no-args.

So my questions are:

  • Should we use enum as id for an object in JPA? (i.e. there is an error in OpenJPA)
  • or am I mistaken somewhere?
  • and are there any ways to solve this problem?
+5
source share
4 answers

The JPA specification does not say that this is possible:

2.1.4 Primary keys and entity identifier

( ) : Java; ; java.lang.String; java.util.Date; java.sql.Date. , , (, ) . , , .

, String int AssetType.FOO.name() AssetType.FOO.ordinal()

, , . - , , , class.isEnum(), . , , .

+7

, ID, JPA ID ( int long -, JPA new).

- ( : ). - ​​ , , .

, .

+4

OpenJPA - JPA, . . Enum

+2

Do you really want to do this? This design does not allow changing the database enumeration keys without updating the enumeration in the code (load failure), and vice versa (restriction failure). Why don't you just create an AssetType table with the name int pk and name and make the Adkeys keys a foreign key for AssetType.id as pk?

You can load AssetTypes from db at startup if you need to list them in your application.

0
source

All Articles