I have a column in a MySQL table, which have an enum variable: "questionTypes"
How will I make entity for this?
For String I do this:
@Column(name = "explanation")
private String explanation
public String getExplanation() {
return explanation;
}
public void setExplanation(String explanation) {
this.explanation = explanation;
}
What should I do for enums?
1 Answer 1
Add JPA's Enumerated annotation (getters/setters omitted):
@Entity
class Answer {
@Column(name = "explanation")
private String explanation
@Column(name = "questionType")
@Enumerated(EnumType.STRING)
private QuestionType type
}
where QuestionType is a regular Java enum.
answered Jul 10, 2012 at 19:57
Reimeus
160k16 gold badges224 silver badges282 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Dave Richardson
Use EnumType.ORDINAL to persist a numeric value for your enum, use EnumType.STRING to persist a string value of your enum. I prefer the latter, it's easier to read in the database.
Matt
I would avoid EnumType.ORDINAL, as it would allow someone to put another value in the enum somewhere other than the end of the enum list. If you use EnumType.STRING, the ordering in the source doesn't matter. You'll only have issues if someone flat out removes a value.
lang-java