Categories
Java

Postgres JDBC and Hibernate Using JSONB Type

While working with Postgres JSONB type and Java, if we assign the value of type UUID as a string then we will get the following exception.

org.postgresql.util.PSQLException: ERROR: column "column" is of type jsonb but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.

To assigning value incorrect way is given below, if you are using PreparedStatement.

First, in the query, you need to write input param par as given below for the PreparedStatement. You need to use to_json function of Postgres as given below and then assign partner as a JSON string value.

PreparedStatement stmt = this.connection.prepareStatement("INSERT INTO " + eventsTableName +
                " (aggregateId, revision, event, hasBeenPublished) values(?, ?, to_json(?::json) , ?)");

In the case of Hibernate you need to define entity as given below

    @Type(type = "jsonb")
    @Column(name = "jsonData", columnDefinition = "jsonb")
    private String jsonData;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.