Video in progress
Some column values are set by the database itself (triggers, DEFAULT, generated columns). How do you work with that in Hibernate, and where are the traps?
Hibernate doesn't know what happened in the database: after the INSERT the entity keeps an old or null value. If I mark the column with @Generated (Hibernate 6), Hibernate re-reads the value after the write. Every such column costs an extra SELECT or a RETURNING.
📖 Answer
An example: the created_at column has default now(), and search_vector is filled by a trigger. In the entity both are plain fields. What happens?
- On INSERT, Hibernate sends
nullforcreated_at: the DEFAULT doesn't apply, because the column is given explicitly. If it is NOT NULL, you get an error. - The trigger ran, but
searchVectorin the entity stayed null. The next UPDATE can write it back as null.
The correct mapping:
@Generated(event = EventType.INSERT)
@Column(insertable = false, updatable = false)
private Instant createdAt;
@Generated(event = { EventType.INSERT, EventType.UPDATE })
@Column(insertable = false, updatable = false)
private String searchVector;
In Hibernate 6.2+, @Generated works with the event attribute (the old GenerationTime is deprecated). Hibernate re-reads the values after the write: through RETURNING on databases that support it, otherwise with an extra SELECT.
For DEFAULT alone, the alternative is not Hibernate's @ColumnDefault (it only affects DDL generation) but @CreationTimestamp or setting the value in Java. Often that is the simplest: the application sets the time and it becomes the single source of truth.
At the architecture level I recommend keeping triggers to a minimum. When the database changes a value on its own, neither the Hibernate L2 cache nor the persistence context knows about it, and the copy in the cache goes stale. If you do need a trigger (audit, denormalization), the columns it writes should be updatable = false in the entity and not cached.
Sign up to mark studied questions and save your progress.