Home > Software design >  How do I map a List<String> from JSON to JPA
How do I map a List<String> from JSON to JPA

Time:11-05

I have a List that I want to store in the DB as a JSON string array. I've tried various ways of doing it but just can't get it working.

The column is currently defined as:

@Column(columnDefinition = "NVARCHAR(4000)")
@ElementCollection(targetClass = String.class)
@Convert(converter = StringListConverter.class)
protected List<String> tagsT = new ArrayList<>();

When I try build this I get a mapping exception of "Could not determine type for: java.util.List".

Alternatively I've also tried defining the column as:

@Convert(converter = StringListConverter.class)
protected ArrayList<String> tagsT = new ArrayList<>();

This builds successfully, however it generates a varbinary column which is not what I'm looking for. If I manually change the column to a NVARCHAR(4000) or a VARCHAR(255) then the data written still doesn't make sense.

I've also tried:

@Column(columnDefinition = "NVARCHAR(4000)")
@ElementCollection(targetClass = String.class)
@Convert(converter = StringListConverter.class)
protected ArrayList<String> tagsT = new ArrayList<>();

But got the same results as previously.

Any help would be appreciated as to what I'm doing wrong/missing.

Thanks.

CodePudding user response:

how is your StringListConverter looks like?

here is working example for Map, but you can adjust it for your case if you change type reference to List

  @Column(columnDefinition = "text")
  @Convert(converter = JsonConverter.class)
  private Map<String, String> connectParameters;
@Converter
public class JsonConverter implements AttributeConverter<Map<String, String>, String> {

  private final static ObjectMapper objectMapper = new ObjectMapper();
  private final TypeReference<Map<String, String>> mapTypeRef = new TypeReference<Map<String, String>>() {
  };

  @Override
  public String convertToDatabaseColumn(Map<String, String> data) {

    if (null == data) {
      return null;
    }

    try {
      return objectMapper.writeValueAsString(data);
    } catch (JsonProcessingException ex) {
      log.error("Couldn't convert data-map to JSON String.", ex);
      return null;
    }
  }

  @Override
  public Map<String, String> convertToEntityAttribute(String dbData) {

    if (null == dbData || dbData.isEmpty()) {
      return Collections.emptyMap();
    }

    try {
      return objectMapper.readValue(dbData, mapTypeRef);
    } catch (IOException ex) {
      log.error("Couldn't convert JSON String to data-map.", ex);
      return null;
    }
  }
}

  • Related