Video in progress

Senior 🌱 Spring

Every change to entities like contracts and tariffs has to be stored as "who, when, what it was, what it became". How do you choose between Envers, triggers and CDC?

Hibernate Envers writes a copy of the entity and a revision to an _aud table on every change, which is the fastest route for data that changes through JPA. If the database is also changed in other ways, triggers or CDC (Debezium) are more reliable; if the business meaning matters, you write explicit audit events.

📖 Answer

Envers is easy to hook up:

@Entity
@Audited
class Contract {
    @Id Long id;
    BigDecimal monthlyFee;
    @NotAudited String internalNote;
}

On every commit Hibernate writes a full copy of the row to the contract_aud table, and the revision number and time to revinfo. For "who", you add a username field to your own RevisionEntity and a RevisionListener (it reads from the SecurityContext). You read the history with AuditReader or Spring Data Envers' RevisionRepository.

Envers' limits:

  • only changes that go through Hibernate are recorded. A @Modifying bulk UPDATE, native SQL, another service, a manual fix: none of them appear in the history;
  • extra INSERTs on every write, which is noticeable on write-heavy tables;
  • audit tables grow faster than the main table, so you need a partitioning and archiving plan.
Approach Coverage Cost
Envers JPA path only easy, inside the app
DB trigger any write to the database hard to pass "who" (via session variable), logic lives in SQL
CDC (Debezium → Kafka) everything in the WAL needs infrastructure, no load on the main path
Domain audit event only the actions you write carries meaning: "tariff changed, reason: ..."

If there is a regulatory requirement (banking, insurance), I pick a mechanism close to the database: you need to be able to say "the database can't be bypassed". For a "change history" screen inside a product, Envers or domain events are enough. Often both live together: technical history and business meaning kept separately.

If the data is personal, remember that the history stores it too: deletion requirements apply to the audit tables as well.