Sarvar Nishonboyev
Sarvar Nishonboyev

Reputation: 13090

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.

Upvotes: 1

Views: 1270

Answers (2)

Nowhere Man
Nowhere Man

Reputation: 19545

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
}

Upvotes: 1

Igor Rumiha
Igor Rumiha

Reputation: 407

If you don't wish to get into some hacks and workarounds you can do something like:

class EventData {
    Invoice invoice;
    Payment payment;
    // ... etc for all types of data you wish to store in an event.     
}

Then your Event entity looks like:

@TypeDefs({
    @TypeDef(name = "json", typeClass = JsonStringType.class)
})
@Entity
class Event {
    private Long id;
    private String eventName;

    @Type(type = "json")
    private EventData eventData;
}

Just populate the right EventData property, and let hibernate-types-52 do the conversion as they advertise.

Upvotes: 1

Related Questions