Created
November 2, 2016 00:19
-
-
Save framis/a20387c153d5a7ec72f368ebeffa1f3d to your computer and use it in GitHub Desktop.
JPA to Json Converter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity | |
public class Entity { | |
@Id | |
@GeneratedValue | |
private Long id; | |
@Convert(converter = JpaJsonConverter.class) | |
private Map<String, String> customMap; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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