Senior
What is the difference between JSON and JSONB in PostgreSQL? What are the issues with Hibernate and JSON fields?
sobes.tech AI
Answer from AI
In PostgreSQL, JSON and JSONB types both store data in JSON format but differ in internal representation:
- JSON — stores data as text, preserving the original format, including spaces and key order.
- JSONB — a binary format that is indexed and optimized for fast search and data operations.
JSONB is usually preferred for queries and indexing but takes up slightly more space when written.
The issue with Hibernate and JSON fields is that Hibernate does not have built-in support for PostgreSQL's JSON/JSONB types. To work with them, custom UserTypes or libraries like Hibernate Types are often used, which allow mapping JSON fields to Kotlin/Java objects.
Example of a custom UserType for JSONB:
@TypeDef(name = "jsonb", typeClass = JsonBinaryType::class)
@Entity
class MyEntity(
@Type(type = "jsonb")
@Column(columnDefinition = "jsonb")
val data: Map<String, Any>
)
Without such support, Hibernate may save JSON as a string, which reduces efficiency and ease of work.