How to write custom DataType and Converter

Hi Nurmuhammad,

Thank you for the test project.

Your converter is incorrect, the DB type should not be String.
Try the following implementation, it works for me:

@Converter(autoApply = true)
public class JsonAttributeConverter implements AttributeConverter<JsonPojo, PGobject> {

    private Gson gson = new GsonBuilder().setPrettyPrinting().create();

    @Override
    public PGobject convertToDatabaseColumn(JsonPojo object) {
        if (object == null) return null;
        try {
            PGobject out = new PGobject();
            out.setType("json");
            out.setValue(gson.toJson(object));
            return out;
        } catch (SQLException ex) {
            throw new IllegalArgumentException("Cannot convert " + object + " to JSON", ex);
        }
    }

    @Override
    public JsonPojo convertToEntityAttribute(PGobject value) {
        if (value == null) return null;

        return gson.fromJson(value.getValue(), JsonPojo.class);
    }
}
1 Like