The @Enumerated annotation is used to specify that an entity attribute represents an enumerated type.
An enum type is mapped to a database via the @javax.persistence.Enumerated annotation.
There are two strategies to store enum values in the database -
- @Enumerated(EnumType.ORDINAL) → Store the enum values according the ordinal position (i.e. 0 , 1, 2 … ) of enum value.
- @Enumerated(EnumType.STRING) → Store the enum values according to the name of the enum value. The default is EnumType.ORDINAL.
@Enumerated - JPA Annotation Example
@Enumerated(String) Example
Let's look at how to map enum types using @javax.persistence.Enumerated annotation with the below snippets.
Consider the following enum types -
package net.javaguides.hibernate.entity;
public enum ProjectStatus {
OPEN,
INPROGESS,
RESUME,
COMPLETED,
CLOSED;
}
Let's use and map this enum in Project entity class -
@Entity
@Table(name = "project")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "project_name")
private String projectName;
@Enumerated(EnumType.STRING)
@Column(name = "project_status")
private ProjectStatus projectStatus;
// getter and setters
}
@Enumerated(ORDINAL) Example
Consider the following enum types -
package net.javaguides.hibernate.entity;
public enum ProjectStatus {
OPEN,
INPROGESS,
RESUME,
COMPLETED,
CLOSED;
}
Let's use and map this enum in Project entity class -
@Entity
@Table(name = "project")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "project_name")
private String projectName;
@Enumerated(EnumType.ORDINAL)
@Column(name = "project_status")
private ProjectStatus projectStatus;
// getter and setters
}
Check out the complete tutorial at https://www.javaguides.net/2018/11/hibernate-5-enum-type-mapping-example.html.
Comments
Post a Comment