Reputation: 241
I'm trying to map a string stored in the database (ex. ABC1, BCD2) to an enum (ABC_1, BCD_2).
With hibernate I was able to do this with the following hibernate mapping
<typedef name="LinkEnum" class="GenericEnumUserType">
<param name="enumClass">types.LinkEnum</param>
<param name="identifierMethod">value</param>
<param name="valueOfMethod">fromValue</param>
</typedef>
and in the LinkEnum
@XmlType(name = "LinkEnum")
@XmlEnum
public enum LinkEnum {
@XmlEnumValue("ABC1")
ABC_1("ABC1"),
@XmlEnumValue("BCD2")
BCD_2("BCD2");
private final String value;
LinkEnum(String v) {
value = v;
}
public String value() {
return value;
}
public static LinkEnum fromValue(String v) {
for (LinkeEnum c: LinkEnum.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
In the JPA class, I'm trying to do the same kind of mapping, however it's having a problem mapping the enum still. Is there an equivalent way to do this with JPA?
private LinkEnum link;
@Enumerated(EnumType.STRING)
@Column(name = "LINK", nullable = false, length = 8)
public LinkEnum getLink() {
return this.link;
}
Upvotes: 0
Views: 1640
Reputation: 245
You could also use a javax.persistence.AttributeConverter (gives your more freedom than the above solution).
For this, implement a class that implements AttributeConverter and annotate your member in the class as follows:
@Convert(converter = NameOfYourConverter.class)
Upvotes: 1
Reputation: 441
Define your Enum like this :
public enum LinkEnum {ABC_1("ABC1"), BCD_2("BCD2")}
And your entity, you can annotated like this :
@Enumerated(EnumType.STRING)
public LinkEnum getLinkEnum() {...}
Upvotes: 0
Reputation:
There's a good explanation on the documentation of @Enumerated
public enum EmployeeStatus {FULL_TIME, PART_TIME, CONTRACT}
public enum SalaryRate {JUNIOR, SENIOR, MANAGER, EXECUTIVE}
@Entity public class Employee {
//@Enumerated is not mandatory. If it's not specified, It assumes to be an ORDINAL (by default)
public EmployeeStatus getStatus() {...}
...
@Enumerated(EnumType.STRING)
public SalaryRate getPayScale() {...}
...
}
https://docs.oracle.com/javaee/7/api/javax/persistence/Enumerated.html
Upvotes: 0