Video in progress

Strong Middle 🌱 Spring

How do you map a PostgreSQL jsonb column in a Hibernate 6 entity, and what are the pitfalls?

Hibernate 6 needs no external library: you put @JdbcTypeCode(SqlTypes.JSON) on the field, it is written to jsonb, and Jackson does the JSON conversion. Watch out for the cost of dirty checking, queries on fields inside the JSON, and the lack of a schema.

📖 Answer

In Hibernate 5 you needed an external library such as hibernate-types for this. Hibernate 6 has it built in:

@Entity
class Product {
    @Id Long id;
    String name;

    @JdbcTypeCode(SqlTypes.JSON)
    @Column(columnDefinition = "jsonb")
    private Map<String, Object> attributes = new HashMap<>();

    @JdbcTypeCode(SqlTypes.JSON)
    private Dimensions dimensions;   // a plain record or class
}

If Jackson is on the classpath, Hibernate uses it for JSON.

When jsonb fits: products whose attributes differ by category, storing a response from an external API, user settings. The core business fields (price, status, owner) should stay in regular columns, because they need FKs, NOT NULL and ordinary indexes.

Pitfalls:

  • Dirty checking. Hibernate finds changes by comparing the old and current values. Mutating the inside of a Map works, but the JSON is compared on every flush. With lots of large documents this eats CPU.
  • Queries. In standard JPQL you can't write attributes ->> 'color', you need native SQL:
    select * from product where attributes @> '{"color":"red"}'
    
    To speed it up, use create index ... using gin (attributes).
  • No schema. The database validates nothing, so within a year you end up with both "colour" and "color". Validate in code, and add a version field inside the JSON if needed.
  • Tests. H2 doesn't know the jsonb operators, so you need a real PostgreSQL via Testcontainers.

My rule: if you are filtering on a field inside the JSON all the time, it probably should have been its own column.