StringMapAttributeConverter.java

package com.tradecloud.converter;

import com.fasterxml.jackson.core.type.TypeReference;
import com.tradecloud.domain.dto.DocumentTypeDTO;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.io.IOException;
import java.io.Serializable;
import java.io.UncheckedIOException;
import java.util.HashSet;
import java.util.Set;

@Converter
public class StringMapAttributeConverter implements AttributeConverter<Set<DocumentTypeDTO>, String>, Serializable {
    private static final long serialVersionUID = 1L;

    private static final TypeReference<Set<DocumentTypeDTO>> TypeRef = new TypeReference<Set<DocumentTypeDTO>>() {
    };

    @Override
    public String convertToDatabaseColumn(Set<DocumentTypeDTO> attribute) {
        if (attribute == null || attribute.isEmpty()) {
            return null;
        }
        try {
            return Jackson2ObjectMapperBuilder.json().build().writeValueAsString(attribute);
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    }

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