Torshovdalen

enum

@Entity

@Enumerated(EnumType.ORDINAL) (default) will map enum values using Enum.ordinal() . Basically first enumerated value will be mapped to 0 in database column, second to 1 , etc. This is very compact and works great to the point when you want to modify your enum. Removing or adding value in the middle or rearranging them will totally break existing records. Ouch! To make matters worse, unit and integration tests often work on clean database, so they won’t catch discrepancy in old data.



@Enumerated(EnumType.STRING) is much safer because it stores string representation of enum . You can now safely add new values and move them around. However renaming enum in Java code will still break existing records in DB. Even more important, such representation is very verbose, unnecessarily consuming database resources.



You can also use raw representation (e.g. single char or int ) and map it manually back and forth in @PostLoad / @PrePersist / @PreUpdate events. Most flexible and safe from database perspective, but quite ugly.





Book

@Entity public class Book { @Id @GeneratedValue(strategy = IDENTITY) private Integer id; //... private Cover cover; //... }

Cover

enum

public enum Cover { PAPERBACK, HARDCOVER, DUST_JACKET }

ORDINAL

STRING

import javax.persistence.AttributeConverter; import javax.persistence.Converter; @Converter public class CoverConverter implements AttributeConverter<Cover, String> { @Override public String convertToDatabaseColumn(Cover attribute) { switch (attribute) { case DUST_JACKET: return "D"; case HARDCOVER: return "H"; case PAPERBACK: return "P"; default: throw new IllegalArgumentException("Unknown" + attribute); } } @Override public Cover convertToEntityAttribute(String dbData) { switch (dbData) { case "D": return DUST_JACKET; case "H": return HARDCOVER; case "P": return PAPERBACK; default: throw new IllegalArgumentException("Unknown" + dbData); } } }

@Converter(autoApply = true)

@Enumerated

@Entity

import javax.persistence.Convert; //... @Convert(converter = CoverConverter.class) private Cover cover;

Exception Description: The converter class [com.blogspot.nurkiewicz.CoverConverter] specified on the mapping attribute [cover] from the class [com.blogspot.nurkiewicz.Book] was not found. Please ensure the converter class name is correct and exists with the persistence unit definition.

orm.xml

<?xml version="1.0"?> <entity-mappings xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/orm" version="2.1"> <converter class="com.blogspot.nurkiewicz.CoverConverter"/> </entity-mappings>

Cover

enum

enum

IllegalArgumentException

enum

for (Cover cover : Cover.values()) { new CoverConverter().convertToDatabaseColumn(cover); }

@Converter

PhoneNumber

isInternational()

getCountryCode()

String

long