Video in progress

Strong Middle 🐻 Hibernate and JPA

How do you map a JSON column in Hibernate 6, and what's better about it than an `AttributeConverter`?

In Hibernate 6, if you put @JdbcTypeCode(SqlTypes.JSON), the field (Map, record, POJO) is converted to JSON through Jackson and written to jsonb on PostgreSQL. Unlike a converter, Hibernate understands the type, dirty checking works correctly, and in 6.2+ if you map an @Embeddable type as JSON, you can reach its fields in HQL.

📖 Answer

public record Address(String city, String street, String zip) {}

@Entity
class Customer {
    @Id Long id;

    @JdbcTypeCode(SqlTypes.JSON)
    @Column(columnDefinition = "jsonb")
    Address address;

    @JdbcTypeCode(SqlTypes.JSON)
    Map<String, Object> attributes;
}

No extra library is needed: if Jackson is on the classpath, Hibernate uses it itself. In Hibernate 5 you needed a library like hypersistence-utils for this.

You can do it with an AttributeConverter<Address, String> too, but:

  • the converter's result is varchar/text; writing to jsonb needs an extra cast;
  • when the inside of a mutable object (a Map) changes, for dirty checking to notice it, equals has to work well. With a converter the change sometimes gets lost or a needless update goes out on every flush;
  • you can't reach inside the JSON in a query.

Things to know: jsonb doesn't preserve key order, so comparisons have to account for that. If you often search by a field inside the JSON, you need a GIN index or a generated column plus a plain index, otherwise a full scan.

When I choose JSON: data whose structure changes quickly or that comes from an external system and is only read as a whole. Fields that business logic searches and filters on should be ordinary columns.