JPA: Saving List of values as comma separated values
The @ElementCollection requires a table to store multiples rows of values,
So you could define as a String column and join/explode in getters and setters, like this
private String services;
public setServices(String services[]) //Can be Array or List
{
// this.services = Iterate services[] and create a comma separated string or Use ArrayUtils
}
public String[] getServices() //Can be Array or List
{
// services.split(",") to get a list of Strings, then typecast/parse them to Strings before returning or use Arrays.asList(arguments.split(","));
}
As mentioned by others in the comments an AttributeConverter
works pretty well. This one uses Jackson to serialize as a JSON array. I recommend JSON since it cleanly handles delimiter escaping, nulls, quotes, etc.:
@Converter
public class StringListAttributeConverter implements AttributeConverter<List<String>, String> {
private static final TypeReference<List<String>> TypeRef = new TypeReference<List<String>>(){};
@Override
public String convertToDatabaseColumn (List<String> attribute) {
if (attribute == null) {
return null;
}
try {
return ObjectMapperFactory.getInstance().writeValueAsString(attribute);
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
@Override
public List<String> convertToEntityAttribute (String dbData) {
if (dbData == null) {
return null;
}
try {
return ObjectMapperFactory.getInstance().readValue(dbData, TypeRef);
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
}
I've used this class and it works well in most cases. One caveat I've found is that using this converter can confuse some JPA criteria queries, because it expects a type List on the entity, but finds a String in the db.