3
votes

I would like to store and retrieve special characters (/, * etc) into/from DB table. This is my attempt:

public enum SpecialCharacters {
    Hack("H/K"), Gk("G*M");

    private String value;

    private SpecialCharacters(String value) {
        this.value = value;
    }

    public String toString() {
        return this.value; // This will return , # or +
    }
}

@Column(name = "Special_Char")
@Enumerated(EnumType.STRING)
private SpecialCharacters specialCharacters;
...

But in DB table it stores only enum field Names like Hack and Gk, not H/K and G*M

1
Why do you think storing the enum names is wrong?Seelenvirtuose
Cant you just use the value returned by toString from the retrieved enum?Reimeus

1 Answers

1
votes

With the @Enumerated Annotation you are only able to store the name or ordinal of your enum. With JPA 2.1 you can use the @Converter Annotation.

See Chapter 11.1.10 of the specification.

Example:

Enum:

public enum SpecialCharacter {
    Hack("H/K"),
    Gk("G*M");

    private String value;

    private SpecialCharacter(String value) {
        this.value = value;
    }

    public String toString() {
        return this.value; // This will return , # or +
    }

    public static SpecialCharacter valueOfKey(String key) {
        for (SpecialCharacter specialCharacter : values()) {
            if (specialCharacter.toString().equals(key)) {
                return specialCharacter;
            }
        }
        throw new IllegalArgumentException("Illegal key");
    }
}

ConverterClass:

@Converter(autoApply = true)
public class SpecialCharacterConverter implements AttributeConverter<SpecialCharacter, String> {

    /**
     * Converts a {@link SpecialCharacter} to the correspondig String that is used in the database
     */
    @Override
    public String convertToDatabaseColumn(SpecialCharacter specialCharacter) {
        return specialCharacter.toString();
    }

    /**
     * Converts a String from the database to the corresponding {@link SpecialCharacter}.
     */
    @Override
    public SpecialCharacter convertToEntityAttribute(String dbValue) {
        return SpecialCharacter.valueOfKey(dbValue);
    }

}

Entity-Object:

@Entity
public class SomeEntity {

    @Column(name = "Special_Char")
    private SpecialCharacter specialCharacter;

    public SpecialCharacter getSpecialCharacter() {
        return this.specialCharacter;
    }

    public void setSpecialCharacter(SpecialCharacter specialCharacter) {
        this.specialCharacter = specialCharacter;
    }
}