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.