StringArrayAttributeConverter.java

package com.tradecloud.converter;

import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.io.IOException;
import java.io.UncheckedIOException;

@Converter
public class StringArrayAttributeConverter implements AttributeConverter<String[], String> {

    private static final TypeReference<String[]> TypeRef = new TypeReference<String[]>() {
    };

    @Override
    public String convertToDatabaseColumn(String[] attribute) {
        if (attribute == null) {
            return null;
        }
        try {
            return Jackson2ObjectMapperBuilder.json().build().writeValueAsString(attribute);
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    }

    @Override
    public String[] convertToEntityAttribute(String dbData) {
        if (dbData == null) {
            return null;
        }
        try {
            return Jackson2ObjectMapperBuilder.json().build().readValue(dbData, TypeRef);
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    }
}