How to store enum type as lowercase string?

write a converter class, annotated with @Converter , which implements javax.persistence.AttributeConverter<YourEnum, String>. There are two methods:

public String convertToDatabaseColumn(YourEnum attribute){..}
public YourEnum convertToEntityAttribute(String dbData) {..}

there you can apply your upper/lower case logic.

Later you can annotated your field, for using the given converter.


Here's a quick and practical example of using AttributeConverter (introduced in JPA 2.1)

Update your enum class:

public enum Status {
    ACTIVE,
    INACTIVE;

    public String toDbValue() {
        return this.name().toLowerCase();
    }

    public static Status from(String status) {
        // Note: error if null, error if not "ACTIVE" nor "INACTIVE"
        return Status.valueOf(status.toUpperCase());
    }
}

Create attribute converter:

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

@Converter(autoApply = true)
public class StatusConverter implements AttributeConverter<Status, String> {
    @Override
    public String convertToDatabaseColumn(Status status) {
        return status.toDbValue();
    }

    @Override
    public Status convertToEntityAttribute(String dbData) {
        return Status.from(dbData);
    }
}

If autoApply is set to true, you don't need to add the javax.persistence.Convert annotation to all attributes that shall be converted. Otherwise, apply the converter:

import javax.persistence.Convert;
import javax.persistence.Entity;

@Entity
public class User {

    @Convert(converter = StatusConverter.class)
    @Enumerated(STRING)
    private Status status;

    // ... other fields, constructor(s), standard accessors
}

If you're using Jackson for the REST service let Jackson do the conversion at the REST boundary. Your question doesn't state a requirement for the DB to store lower case or for the application to process lower case.

public enum Status {
    STARTED,
    CONSUMING,
    GENERATING,
    FAILED,
    COMPLETED,
    DELETED;

    /**
     * Serialises to and from lower case for jackson.
     *
     * @return lower case Status name.
     */
    @JsonValue
    public String toLower() {
        return this.toString().toLowerCase(Locale.ENGLISH);
    }
}