Question
How can I map an enum in JPA to use specific integer values for each enum entry while saving only these integer values?
@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {
public enum Right {
READ(100), WRITE(200), EDITOR (300);
private int value;
Right(int value) { this.value = value; }
public int getValue() { return value; }
};
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "AUTHORITY_ID")
private Long id;
private Right right;
}
Answer
Mapping enums in JPA to specific integer values requires custom handling, as JPA's default behavior is to use ordinal values (0, 1, 2). This guide outlines several solutions to achieve the desired mapping of enums with fixed integer values.
@Basic
private int intValueForAnEnum;
@PrePersist
void populateDBFields() {
intValueForAnEnum = right.getValue();
}
@PostLoad
void populateTransientFields() {
right = Right.valueOf(intValueForAnEnum);
}
Causes
- JPA by default maps enums using ordinal values, which do not correspond to the custom integers specified in the enum definition.
- Complexity increases with the need to maintain enum values in the database that do not reflect their ordinal indexes.
Solutions
- **Using @Enumerated with a custom int field**: One straightforward approach is to create an additional integer field to store the values derived from the `enum`. Then, utilize `@PrePersist` and `@PostLoad` lifecycle methods to convert between the enum and its integer representation.
- **Implementing a custom converter**: With the use of a custom converter, you can define how to convert between the enum and the desired int representation. This is more efficient and keeps your entity cleaner.
Common Mistakes
Mistake: Using `@Enumerated(EnumType.ORDINAL)` without understanding it maps to ordinal values.
Solution: Instead, use an integer field and manage conversions manually.
Mistake: Overcomplicating the enum mapping with too many conversions.
Solution: Utilize JPA lifecycle methods for simpler mapping between enum and persistence.
Helpers
- JPA enum mapping
- JPA fixed values enum
- JPA enum integer values
- Java persistence API enum
- Spring JPA enum conversion
- Hibernate enum mapping