How to write custom DataType and Converter

Hi there,
I want to use jsonb column in postgresql to storing json data.

I’ve write my own datatype and converter, but getting error.

Can you guys help me?
I’m attaching my sample project.

Thanks,
Nurmuhammad.

custom-datatype-converter.zip (420.3 KB)

@krivopustov @albudarov
Hi Konstantin, Alexander sorry for disterrubing.
Do you have any advices, ideas?
I’m searching this solution, but can’t find. Can you give any help or some direction to solve this?
Thanks,
Nurmuhammad.

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

Thanks @krivopustov, its working now. thank you for your advice!