在Enum数据类型中保存特殊字符

时间:2015-04-14 13:54:10

标签: java jpa

我想在DB表中存储和检索特殊字符(/*等)。这是我的尝试:

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;
...

但是在DB表中它只存储枚举字段名称,如 Hack Gk ,而不是 H / K G * M

1 个答案:

答案 0 :(得分:1)

使用@Enumerated注释,您只能存储枚举的名称或序号。使用JPA 2.1,您可以使用@Converter注释。

specification的第11.1.10节。

示例:

枚举:

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
public class SomeEntity {

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

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

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