John Manak
John Manak

Reputation: 13558

Read ENUM and its fields from a database (JPA)

I have a model object that's in fact an enum with fields and getters:

@Entity
public enum Type {
   TYPE1, TYPE2, TYPE3, TYPE4;

   @Column
   private Long id;
   @Column
   private String name;
   ...

   public String getName() {
      return this.name;
   }
   ...
}

It compiles and runs fine. However, if I call a getter method, it returns null (it doesn't load any values stored in the database). Is this the standard behavior? Is there a way to make JPA load them?

Upvotes: 2

Views: 3212

Answers (3)

Thomas
Thomas

Reputation: 88707

I'd say there is some misconception in this aproach:

  1. Entities represent objects that can be stored in the database. In this case, the database (or any other persistent store) defines which instances are available.

  2. Enums represent a fixed set of constants that are defined in source code. Thus the class itself defines which constants are available. In addition, it's generally bad practice to change the values of an enum, i.e. the name or id in your case.

You see that they are two quite different concepts which should be treated differently.

To store enums in entities (where the enum is a field of that entity), you could either use @Enumerated and store the name or ordinal of the enum, or (what we do more often) store one of the fields (we mostly use the id) and provide conversion methods.

If you want to store configurable "constants" in the database you might try and use plain entities for that, make the constructor private (Hibernate and other JPA providers should be able to deal with that) and provide an alternative implementation of the Enum class (you can't use the enum keyword though).

Upvotes: 3

Jberg
Jberg

Reputation: 945

Have you looked into the @Enumerated annotation? I haven't ever tried to use it within an enum itself, however it works quit well binding a class property to an enum.

enum Type{TYPE1, TYPE2}

@Column(name="type")
@Enumerated(EnumType.STRING)
public Type getType(){return type;}
public void setType(Type t){type = t;}

Upvotes: 1

rsp
rsp

Reputation: 23373

If JPA cannot be made to handle this, you could add a public Type valueOf(long id) method to your enum class which you use as a factory to instantiate enum instances representing the values in your legacy table.

Upvotes: 0

Related Questions