我更新了 Chris 的代码以将 Jackson JSON 库用于列表和地图:
import java.util.List;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Converter
public class ListToJsonConverter<T> implements AttributeConverter<List<T>, String> {
private static ObjectMapper mapper = new ObjectMapper();
@Override
public String convertToDatabaseColumn(List<T> attribute) {
if (attribute == null) {
return null;
}
try {
return mapper.writeValueAsString(attribute);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public List<T> convertToEntityAttribute(String dbData) {
if (dbData == null || dbData.isEmpty()) {
return null;
}
try {
return mapper.readValue(dbData, List.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
import java.util.Map;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Converter
public class MapToJsonConverter<T, K> implements AttributeConverter<Map<T, K>, String> {
private static ObjectMapper mapper = new ObjectMapper();
@Override
public String convertToDatabaseColumn(Map<T, K> attribute) {
if (attribute == null) {
return null;
}
try {
return mapper.writeValueAsString(attribute);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public Map<T, K> convertToEntityAttribute(String dbData) {
if (dbData == null || dbData.isEmpty()) {
return null;
}
try {
return mapper.readValue(dbData, Map.class);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@Column(name = "example_list")
@Convert(converter = ListToJsonConverter.class)
public List<String> getExampleList() {
return exampleList;
}
@Column(name = "example_map")
@Convert(converter = MapToJsonConverter.class)
public Map<String, String> getExampleMap() {
return exampleMap;
}
这允许以人类可读的方式在字符串列中存储几乎任何类型,并使得您不需要为每种类型的列表或哈希图创建一个单独的类。它还会自动转义字符串。