Let\'s say I have the following situation:
Object Car has an ArrayList of prices, which are all numbers. Is it possible in Hibernate to save all the prices in a sin
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 implements AttributeConverter, String> {
private static ObjectMapper mapper = new ObjectMapper();
@Override
public String convertToDatabaseColumn(List attribute) {
if (attribute == null) {
return null;
}
try {
return mapper.writeValueAsString(attribute);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
@Override
public List 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 implements AttributeConverter
@Column(name = "example_list")
@Convert(converter = ListToJsonConverter.class)
public List getExampleList() {
return exampleList;
}
@Column(name = "example_map")
@Convert(converter = MapToJsonConverter.class)
public Map 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.