There are different ways of configuring enums inside JPA entity which yields different results.
Let's consider we have this enum
public enum EmpType {
FULL_TIME, PART_TIME;
}
And the entity
@Entity
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private String name;
@Enumerated
private EmpType empType;
..
}
To use enum we have to annotate field with @Enumerated
Employee e = new Employee();
e.setId(1L);
e.setName("na");
e.setEmpType(EmpType.FULL_TIME);
em.persist(e);
the above code will save entity as follows
ID EMPTYPE NAME
1 0 na
This is because all the enum's in EmpType are indexed starting from zero, so if we change order or introduce a new enum in middle we lose the context in Employee table.
Instead use this @Enumerated(EnumType.STRING) which save the above entity as
ID EMPTYPE NAME
1 FULL_TIME na
If you are looking for more advance mapping then consider this post
Advance Enums JPA 2.0
Let's consider we have this enum
public enum EmpType {
FULL_TIME, PART_TIME;
}
And the entity
@Entity
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private String name;
@Enumerated
private EmpType empType;
..
}
To use enum we have to annotate field with @Enumerated
Employee e = new Employee();
e.setId(1L);
e.setName("na");
e.setEmpType(EmpType.FULL_TIME);
em.persist(e);
the above code will save entity as follows
ID EMPTYPE NAME
1 0 na
This is because all the enum's in EmpType are indexed starting from zero, so if we change order or introduce a new enum in middle we lose the context in Employee table.
Instead use this @Enumerated(EnumType.STRING) which save the above entity as
ID EMPTYPE NAME
1 FULL_TIME na
If you are looking for more advance mapping then consider this post
Advance Enums JPA 2.0
Comments
Do you think that theese advantages balance the greater database space use? I actually never ran in a situation where the size of those field is really an issue - a few bytes more by a few thousands record sum up as a few kilobytes after all, but a case with a table with many enums may be different.
http://mdshannan1.blogspot.com/2010/09/jpa-20-enums-with-custom-values.html
Thanks