Video in progress
In Hibernate 6, when is using JSON columns the right call, and when is a normalized table better?
JSON is convenient for data whose schema changes fast, that is read as a whole and rarely filtered: settings, integration payloads, type-specific attributes. If you need joins, constraints, aggregation or frequent UPDATEs on it, use separate columns and tables.
📖 Answer
In Hibernate 6 you don't need an external library for JSON:
@Entity
class Product {
@JdbcTypeCode(SqlTypes.JSON)
private ProductAttributes attributes; // a record or a Map
}
record ProductAttributes(String color, Integer weightGrams, List<String> tags) {}
It maps to jsonb on PostgreSQL and to a suitable type on other databases. Serialization goes through Jackson (if it is on the classpath).
Cases where JSON is a good choice:
- many product types, each with its own attributes, instead of 200 nullable columns;
- storing a response from an external system, to process later if needed;
- user settings, UI state.
The downsides show up quickly:
Dirty checking. Hibernate compares the JSON object as a whole. A change inside a mutable Map is sometimes missed or, the other way around, an unnecessary UPDATE goes out on every flush. If you use an immutable record, you set a new object for each change, which is more reliable.
Write cost. Changing a single attribute rewrites the whole document. Big JSON + frequent UPDATEs = WAL and TOAST load.
No constraints. "weightGrams must be positive", FKs: all of it lives in application code.
Queries. JSON functions are not standard in JPQL; you often need native SQL and a GIN index.
My rule: if I need a WHERE or ORDER BY on a field for the second time, I pull it out into its own column (or a PostgreSQL generated column). JSON is for the edges, not for the core.
Sign up to mark studied questions and save your progress.