Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL throws "column is of type jsonb but expression is of type bytea" with JPA and Hibernate

This is my entity class that is mapped to a table in postgres (9.4) I am trying to store metadata as jsonb type in the database

@Entity
@Table(name = “room_categories”)
@TypeDef(name = “jsonb”, typeClass = JsonBinaryType.class)
public class RoomCategory extends AbstractEntity implements Serializable {
    private String name;
    private String code;
    @Type(type = "jsonb")
    @Column(columnDefinition = "json")
    private Metadata metadata;

}

This is the metadata class:

public class Metadata implements Serializable {
    private String field1;
    private String field2;

}

I have used following migration file to add jsonb column:

databaseChangeLog:
– changeSet:
id: addColumn_metadata-room_categories
author: arihant
changes:
– addColumn:
schemaName: public
tableName: room_categories
columns:
– column:
name: metadata
type: jsonb

I am getting this error while creating the record in postgres: ERROR: column “metadata” is of type jsonb but expression is of type bytea Hint: You will need to rewrite or cast the expression.

This is the request body i am trying to persist in db:

  {
    “name”: “Test102”,
    “code”: “Code102”,
    “metadata”: {
    “field1”: “field11”,
    “field2”: “field12”
    }
    }

Please help how to convert bytea type to jsonb in java spring boot app

like image 549
Arihant Jain Avatar asked Dec 19 '18 09:12

Arihant Jain


People also ask

Does hibernate support Jsonb?

Hibernate's PostgreSQL dialect does not support the JSONB datatype, and you need to register it.

What is Jsonb in Postgres?

JSONB stands for “JSON Binary” or “JSON better” depending on whom you ask. It is a decomposed binary format to store JSON. JSONB supports indexing the JSON data, and is very efficient at parsing and querying the JSON data. In most cases, when you work with JSON in PostgreSQL, you should be using JSONB.

What is Jsonb data type?

The JSONB data type stores JSON (JavaScript Object Notation) data as a binary representation of the JSONB value, which eliminates whitespace, duplicate keys, and key ordering. JSONB supports GIN indexes. Tip: For a hands-on demonstration of storing and querying JSON data from a third-party API, see the JSON tutorial.

Should I use Jsonb or JSON?

In general, most applications should prefer to store JSON data as jsonb , unless there are quite specialized needs, such as legacy assumptions about ordering of object keys. RFC 7159 specifies that JSON strings should be encoded in UTF8.


2 Answers

Simply convert your object by an ObjectMapper to a json string and then use (::jsonb) as cast to jsonb type:

INSERT INTO room_categories (name, code, metadata)
    VALUES (?, ?, ? ::jsonb ); 

(you will need to use native queries to query data stored as jsonb)

like image 103
Ali Faradjpour Avatar answered Sep 24 '22 11:09

Ali Faradjpour


The cause of the error

You could get this PostgreSQL:

ERROR: column “metadata” is of type jsonb but expression is of type bytea Hint: You will need to rewrite or cast the expression.

if you are executing a native SQL DML statement.

Native SQL DML statement

For instance, let's assume you want to do something like this:

int updateCount = entityManager.createNativeQuery("""
    UPDATE
        room_categories
    SET
        metadata = :metadata
    WHERE
        code = :code AND
        metadata ->> 'field1' is null            
    """)
.setParameter("code ", "123-ABC")
.setParameter(
    "metadata",
    new Metadata()
        .setField1("ABC")
        .setField2("123")
)
.executeUpdate();

The bytea type stands for byte array, and, since the Metadata type implements the Serializable interface, Hibernate falls back to using the SerializableType when no other type is more appropriate.

But, since you cannot bind a byte array to a jsonb column, PostgreSQL throws the aforementioned error.

The fix

To fix it, we have to set the JsonBinaryType explicitly using the Hibernate-specific setParameter Query method:

int updateCount = entityManager.createNativeQuery("""
    UPDATE
        room_categories
    SET
        metadata = :metadata
    WHERE
        code = :code AND
        metadata ->> 'field1' is null            
    """)
.setParameter("code ", "123-ABC")
.unwrap(org.hibernate.query.Query.class)
.setParameter(
    "metadata",
    new Metadata()
        .setField1("ABC")
        .setField2("123"),
    JsonBinaryType.INSTANCE
)
.executeUpdate();

First, we had to unwrap the JPA Query to a Hibernate org.hibernate.query.Query and call the setParameter method that takes a Hibernate Type instance.

Now, Hibernate will know that the metadata parameter needs to be handled by the JsonBinaryType, and not by the SerializableType.

like image 43
Vlad Mihalcea Avatar answered Sep 21 '22 11:09

Vlad Mihalcea