javaspringpostgresqlhibernatehibernate-types

Storing String value into the field of JSON type


There is an entity for Events:

@Entity
class Event {
    private Long id;
    private String eventName;
    private String eventData; // json value of object eg. Invoice, Payment.
}

When I tried to insert a new record, PostgreSSQL is giving an error because type of eventData field is json. I cannot use a specific type for eventData to convert to Json object because it can be any event (Invoice, Payment etc). Is there any way to convert to Generic type.

I've used Hibernate-types-52 library.


Solution

  • The following implementation should work (for PostgreSQL JsonBinaryType.class should be used for both "json" and "jsonb" columns types according to Vlad Minalcea's statement):

    @TypeDef(name = "json", typeClass = JsonBinaryType.class)
    @Entity
    public class Event {
        @Id
        private Long id;
        private String eventName;
    
        @Type(type = "json")
        @Column(columnDefinition = "json")
        private String eventData;
    // getters/setters
    }