I have never used the Java enum classes before for constant values, I usually used the "public final" approach in the past. I started using enum now, and I'm overriding the toString () method to return a different value than the enumeration name.
I have a JPA code in which I create a TypedQuery with named parameters, one of which is a string representation of the enum value. If I simply set the using Status.ACTIVE parameter, I get the correct value "A", but an exception is thrown because it is of type Status, not String. It only works if I explicitly call the toString () method. I thought that simply overriding the toString () method would return a String, regardless of the type of class.
This listing is:
public enum Status {
ACTIVE ("A"),
PENDING ("P"),
FINISHED ("F");
private final String value;
Status(String value) {
this.value = value;
}
public String toString() {
return value;
}
};
This is TypedQuery:
TypedQuery<MechanicTimeEvent> query = entityManager().createQuery("SELECT o FROM MechanicTimeEvent o WHERE o.id.mechanicNumber = :mechanicNumber AND o.id.status = :status", MechanicTimeEvent.class);
query.setParameter("mechanicNumber", mechanicNumber);
query.setParameter("status", Status.ACTIVE.toString());
source
share