Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store enum type as lowercase string?

My model class (piece):

public class User ... {

    @Enumerated(STRING)
    private Status status;

    ...

    public enum Status {

        ACTIVE,
        INACTIVE;

        @Override
        public String toString() {
            return this.name().toLowerCase();
        }
    }

    ...

    public String getStatus() {
        return status.name().toLowerCase();
    }

    public void setStatus(Status status) {
        this.status = status;
    }
}

As you see above I override toString method, but no effect. Enumeration store in database as ACTIVE or INACTIVE.

P.S. I use hibernate jpa

Thanks for help!

P.S.S. I ask because I write REST service that produces json (in json object better use lower case, if I'm not mistake)

like image 249
eugenes Avatar asked Oct 23 '13 16:10

eugenes


People also ask

Can enum values be lowercase?

Java conventions are that enum names are all uppercase, which immediately causes problems if you want to serialize the enum in another form. But when you serialize those enum values, you want to use lowercase values of "left", "top", "right", and "bottom". No problem—you can override Side.

How do I convert an enum to a string?

There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.

Should enum be uppercase or lowercase?

Because they are constants, the names of an enum type's fields are in uppercase letters. You should use enum types any time you need to represent a fixed set of constants.

Should Enums be case sensitive?

Implementation Details. Enum labels are case sensitive, so 'happy' is not the same as 'HAPPY' . White space in the labels is significant too. Although enum types are primarily intended for static sets of values, there is support for adding new values to an existing enum type, and for renaming values (see ALTER TYPE).


1 Answers

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.

like image 73
Kent Avatar answered Sep 22 '22 22:09

Kent