Hibernate Envers audits persistent data and retains historical entity versions. It listens to Hibernate events, copies changes into dedicated audit tables, and groups modifications made in one transaction under a revision number. section 13.0 section 13.3
Configure auditing around the entities and properties whose history matters:
- Add the Envers JAR through Maven; no further configuration is required before enabling auditing. section 13.3.1
- Annotate an entity with @Audited to record all its properties, or use @NotAudited to exclude a property or association. section 13.3.1
- Expect separate audit tables, including ITEM_AUD and USERS_AUD, plus REVINFO for revision numbers and timestamps. section 13.3.1
- Treat revision data as durable history: Envers does not automatically remove it when an entity is deleted. section 13.3.1
Selective auditing for an Item
An Item can be annotated with @Audited while its bids association carries @NotAudited. Envers then records Item changes and the seller relationship while ignoring bids; User must also be annotated with @Audited when its history is required. On commit, modified audited instances receive a revision entry, copied state, and an INSERT, UPDATE, or DELETE marker in REVTYPE. section 13.3.1
Listing 13.4 Enabling audit logging for the Item entity
Path: Ch13/envers/src/main/java/com/manning/javapersistence/ch13 /filtering/envers/Item.java @Entity @org.hibernate.envers.Audited public class Item { @NotNull private String name; @OneToMany(mappedBy = "item") @org.hibernate.envers.NotAudited private Set<Bid> bids = new HashSet<>(); @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "SELLER_ID", nullable = false) private User seller; // . . . }
Inspect the annotated Item mapping to see entity-wide auditing combined with an excluded association. section 13.3.1
