0

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;
}
asked Sep 21, 2016 at 15:29
1
  • Can we see the entire class definition ? Commented Sep 21, 2016 at 15:36

3 Answers 3

1

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)

answered Sep 21, 2016 at 16:01
Sign up to request clarification or add additional context in comments.

Comments

0

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

answered Sep 21, 2016 at 15:42

Comments

0

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() {...}
answered Sep 21, 2016 at 15:54

1 Comment

Any news ? Do you fix your problem ?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.