I've never really made use of Java enum classes before for constant values, I've typically used the "public final" approach in the past. I've started using an enum now and I'm overriding the toString() method to return a different value than the enum name.
I have some JPA code in which I'm creating a TypedQuery with named parameters, one of which is a String representation of the enum value. If I merely set the parameter using Status.ACTIVE, I get the proper "A" value, but an exception is thrown because it's type is actually Status rather than String. It only works if I explicitly call the toString() method. I thought that simply overriding the toString() method would result in a String type being returned, no matter what the class type was.
This is the enum:
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 the 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());