我想在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
答案 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;
}
}