Java Reference
In-Depth Information
manually managing their status), @Enumarated(EnumType.STRING) and @Enu-
marated(EnumType.ORDINAL) ; both had their flaws. The first one is sensitive to-
wards enum renaming; the entities in the database will have the full name of the enum
stored (which sometimes is also a waste of the storage space). The second one could cre-
ate problems when the order of enums would be changed (because it stored the index of
the enum value). From JPA 2.1, we can create a converter, which will automatically con-
vert our enum attributes to specific entries in the database. We only need to create an an-
notated class, which implements the AttributeConverter interface:
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public class SeatPositionConverter implements
AttributeConverter<SeatPosition, String> {
public String convertToDatabaseColumn(SeatPosition
attribute) {
return attribute.getDatabaseRepresentation();
public SeatPosition convertToEntityAttribute(String
dbData) {
for (SeatPosition seatPosition :
SeatPosition.values()) {
(dbData.equals(seatPosition.getDatabaseRepresentation())) {
return seatPosition;
throw new IllegalArgumentException("Unknown
attribute value " + dbData);
That's all, no additional configuration is required. The autoApply attribute set to true
signals JPA to take care of all of our SeatPosition enums in entities.
Search WWH ::

Custom Search