Skip to content

Instantly share code, notes, and snippets.

@framis
Created November 2, 2016 00:19
Show Gist options
  • Save framis/a20387c153d5a7ec72f368ebeffa1f3d to your computer and use it in GitHub Desktop.
Save framis/a20387c153d5a7ec72f368ebeffa1f3d to your computer and use it in GitHub Desktop.
JPA to Json Converter
@Entity
public class Entity {
@Id
@GeneratedValue
private Long id;
@Convert(converter = JpaJsonConverter.class)
private Map<String, String> customMap;
}
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.persistence.AttributeConverter;
import java.io.IOException;
public class JpaJsonConverter implements AttributeConverter<Object, String> {
private static final ObjectMapper om = new ObjectMapper();
@Override
public String convertToDatabaseColumn(Object attribute) {
try {
return om.writeValueAsString(attribute);
} catch (JsonProcessingException ex) {
//log.error("Error while transforming Object to a text datatable column as json string", ex);
return null;
}
}
@Override
public Object convertToEntityAttribute(String dbData) {
try {
return om.readValue(dbData, Object.class);
} catch (IOException ex) {
//log.error("IO exception while transforming json text column in Object property", ex);
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment