Video in progress
How reasonable is it to add system-wide logic (audit fields, tenant, encryption) through a Hibernate Interceptor or event listener? What are the risks?
It is right for small, mechanical jobs: filling createdAt/updatedBy, setting the tenant ID. I don't put business logic there: it is invisible, does not run for bulk and native SQL, executes during flush and can cause extra queries or a recursive flush.
📖 Answer
Hibernate has several hooks: JPA callbacks (@PrePersist, @PreUpdate), Spring Data auditing (@CreatedBy, @LastModifiedDate), the Hibernate Interceptor, and listeners through the low-level EventListenerRegistry.
Where they work well:
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
abstract class Audited {
@CreatedDate Instant createdAt;
@LastModifiedBy String updatedBy;
}
Mechanical, predictable, the same for every entity.
Where the trouble starts.
Querying with the EntityManager inside a listener. If code called during flush sends a new query, an auto-flush can start again: unexpected errors and sometimes infinite recursion. The JPA specification forbids EntityManager operations in callbacks.
Invisibility. A new developer writes order.setStatus(PAID) and can't find where the payment message gets sent from. I write business events explicitly in code, as a domain event or in a service method.
Bypassing. Bulk JPQL, native SQL, StatelessSession (for plain listeners): none of them go through these hooks. If tenant ID or encryption relies only on a listener, the first bulk query opens a security hole.
For encryption I prefer an AttributeConverter: it works at the column level, is explicit and testable. For the tenant, a combination of Hibernate 6's @TenantId and database-level RLS.
Sign up to mark studied questions and save your progress.