If you use EnumType.String then renaming one of your enum types will cause your enum value to be out of sync with the values saved in the database. If you use EnumType.ORDINAL then deleting or reordering the types within your enum will cause the values saved in the database to map to the wrong enums types.
Both of these options are fragile. If the enum is modified without performing a database migration, you could jeopodise the integrity of your data.
A possible solution is to use the JPA lifecycle call back annotations, @PrePersist and @PostLoad. This feels quite ugly as you will now have two variables in your entity. One mapping the value stored in the database, and the other, the actual enum.
The preferred solution is to map your enum to a fixed value, or ID, defined within the enum. Mapping to predefined, fixed value makes your code more robust. Any modification to the order of the enums types, or the refactoring of the names, will not cause any adverse effects.
If you are using JPA 2.1 you have the option to use the new @Convert annotation. This requires the creation of a converter class, annotated with @Converter, inside which you would define what values are saved into the database for each enum type. Within your entity you would then annotate your enum with @Convert.
The reason why I prefer to define my ID's within the enum as oppose to using a converter, is good encapsulation. Only the enum type should know of its ID, and only the entity should know about how it maps the enum to the database.
Here is an example:
public class Player {
@Id
@Column(name="player_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
//...
private Integer position;
public Position getPosition() {
return Position.getType(this.position);
}
public void setPosition(Position position) {
if (position == null) {
this.position = null;
} else {
this.position = position.getId();
}
}
}
public enum Position {
FORWARD(1),
DEFENCE(2),
MIDFIELD(3),
GOALKEEPER(4);
private int id;
private Position(int id) {
this.id = id;
}
public static Position getType(Integer id) {
if (id == null) {
return null;
}
for (Position position : Position.values()) {
if (id.equals(position.getId())) {
return position;
}
}
throw new IllegalArgumentException("No matching type for id " + id);
}
public int getId() {
return id;
}
}
Note: by using an integer data type rather than a String data type, will mean quicker database queries when using the value in where clause. While this may not matter in smaller datasets of say 10,000 records, much larger datasets may notice a reduction in performance.