Dealing with JSONB data Type in Micronaut

If you are using micronaut with postgres, one of the issues you must facing is how to save and retrieve JSONB data in micronaut entity.

I have to write this blog because as per the official doc using

@TypeDef(type = DataType.JSON)

Doesn’t worked for me, I was getting errors like

Cannot encode parameter of type java.util.HashMap

Somehow I was able to save but was facing issue while retrieving the column.

@Introspected
@MappedEntity(value = "temp_jsonb")
data class TempJsonb(
    @field:Id @GeneratedValue var id: Long?,
    @TypeDef(type = DataType.JSON)
    var data: JSONTemp?,
)


data class JSONTemp(
    var id: Int?
)
// As per the doc

So if you are facing the same issue, I hope following solution solves your problem too.

The idea is to use MappedProperty Annotation.

@Introspected
@MappedEntity(value = "temp_jsonb")
data class TempJsonb(
    @field:Id @GeneratedValue var id: Long?,
    @MappedProperty(type = DataType.JSON)
    var data: JSONTemp?,
)

Using Mapped Property skips the issue of “Cannot encode parameter” and retrieving the data also works as expected. This also handles the null values if our data column is null.

Related Post

Leave a Reply

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