As usual Java enum types have corresponding codes and name description. And Java classes that contain such fields, contain them as Enum:
public enum MyEnum{
SOMEINSTANCE(1, "test1"),
SOMEINSTANCE(2, "test2");
private final int code;
private final String name;
private MyEnum(int code, String name){
this.code = code;
this.name = name;
}
... helper getter for code and name
}
@Entity
puclic class EnumHolder{
private MyEnum myEnum;
}
I'm a newbie to JPA, but I wish to have the 'myEnums' table, looked like:
code int not null, name varchar(50) not null)
And in my enumHolder table I want to have the myEnumCode field that points to the myEnums table.
Using currenlty supported both EnumType.ORDINAL and EnumType.STRING I suppose not a good idea.
And another question. How can I fill in the myEnums table using Java MyEnum class data? How would you do it? The best approach please.
PS: here are solutions I can offer:
Let's suppose there is table myEnum with code and name fields. Java MyEnum enum, that is described in the question. enumHolder table need to have myEnumCode reference to myEnum.code field. Please comment the solution if you disagree.
@Entity
@Access(AccessType.FIELD)
public class EnumHolder {
@Id private int id;
@Transient private MyEnum myEnum;
…
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public MyEnum getMyEnum() { return MyEnum; }
public void setMyEnum(MyEnum myEnum) { this.myEnum = myEnum; }
@Access(AccessType.PROPERTY) @Column(name="myEnumCode")
protected int getMyEnumForDb() {
return myEnum.getCode();
}
protected void setMyEnumForDb(int enumCode) {
myEnum = MyEnum.getByCode( enumCode);
}
…
}
Of course there are drawbacks here. But at the moment I cannot see the better approach. Alternatives with EnumType.ORDINAL and EnumType.STRING please don't offer. I don't want to write here all problems that can exist with its usage (in Effective Java it is described concerning ordinals usage). Using EnumType.STRING I don't like either cause it does not allow to have discription in database and request it from db.
Concerning fillind database. I think it's not difficult to write a script, that clears the myEnum table and then for each Java enum istance makes insert into the table. And always do it during a deployment phase.