I updated Chris's code to utilize the Jackson JSON library for lists and maps:
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;
}
This allows storing just about any types in a human-readable way in a string column, and makes it so you don't need a separate class for every type of list or hashmap. It also automatically escapes the strings.