2

I have many tables with data which are used as properties in my application. These data change very infrequently, they are like constants. In my application I have some classes enum which represent those tables, this is one of them:

public enum MyEnum {
  ENUM_ONE {
    public String getCode() {
      return "1";
    }
  },
  ENUM_TWO {
    public String getCode() {
      return "2";
    }
  };

  private static final String tableName = "MYENUMTABLE";

  public abstract String getCode();

  public String getTableName() {
    return tableName;
  }
}

The thing is that, as you can see in the code above, this is hardcode (isn't it?), so I wonder if it possible to create some code to load these properties when the application starts-up.

The application is built with Java, Hibernate, Spring framework, Oracle 11.2.0.3 ... maybe it exists something with any of these tools.

Thanks in advance.

Alavaros
  • 1,665
  • 7
  • 32
  • 52
  • Possible [duplicate](http://stackoverflow.com/questions/352586/how-to-use-enums-with-jpa)? – Buhake Sindi Jan 28 '15 at 11:23
  • @BuhakeSindi Sorry, I don't see the possible duplicate, in that post the enum is hard-coded too, isn't it? I would like it to be loaded from databse, and these enums could have a lots of entries and can be used in many different classes. Is it possible? – Alavaros Jan 28 '15 at 11:33
  • Enums are constants so and should be treated as a constant. If you want those entries to be loaded in memory and be reused by various classes, you can have them cached in a cache and call the values from the cache. – Buhake Sindi Jan 28 '15 at 12:08

1 Answers1

-1

Firstly, I would have created the enum as follows (see my answer here):

public enum MyEnum {
    ENUM_ONE("1"),
    ENUM_TWO("2")
    ;
    private final String code;

    private MyEnum(final String code) {
        this.code = code;
    }

    //Not nearly necessary since the toString() method returns the same value.
    public String getCode() {
      return code;
    }

    public String toString() {
        return code;
    }
 };

Then, supposing you're using MySQL database & JPA as your question doesn't specify what RDBMS you're using and ORM API per say, the @Column annotation contains the columnDefinition property where you can define your ENUM DDL definition,

E.g.,

@Column(name="CODE_ENUM", table="MYENUMTABLE", columnDefinition="ENUM(2) NOT NULL") //table is OPTIONAL
private MyEnum codeEnum;

//Generate getters and setters.

This is an example that uses JPA so your Hibernate must support JPA.


For Oracle, you can use @Enumerated(EnumType.ORDINAL) instead of using columnDefinition for your requirement.

I hope this helps.

Community
  • 1
  • 1
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228