Hibernate.orgCommunity Documentation
Table of Contents
This tutorial is located within the download bundle under envers
.
Objectives
Configure Envers.
Use the Envers APIs to view and analyze historical data.
This file was discussed in the JPA
tutorial in Section 4.1, “persistence.xml
”, and is essentially the same here.
Again, the entity is largely the same as in Section 4.2, “The annotated entity Java class”. The major
difference is the addition of the @org.hibernate.envers.Audited
annotation, which
tells Envers to automatically track changes to this entity.
Again, this tutorial makes use of the JPA
APIs. However, the code also makes a change to one
of the entities, then uses the Envers API to pull back the initial revision as well as the updated
revision. A revision refers to a version of an entity.
Example 5.1. Using the org.hibernate.envers.AuditReader
public void testBasicUsage() { ... AuditReader reader = AuditReaderFactory.get( entityManager ); Event firstRevision = reader.find( Event.class, 2L, 1 ); ... Event secondRevision = reader.find( Event.class, 2L, 2 ); ... }
Procedure 5.1. Description of Example
An org.hibernate.envers.AuditReader
is obtained from the
org.hibernate.envers.AuditReaderFactory
which wraps the
javax.persistence.EntityManager
.
Next, the find
method retrieves specific revisions of the entity. The first call
reads find revision number 1 of Event with id 2
. The second call reads find
revision number 2 of Event with id 2
.
Practice Exercises
Provide a custom revision entity to additionally capture who made the changes.
Write a query to retrieve only historical data which meets some criteria. Use the Envers User Guide to see how Envers queries are constructed.
Experiment with auditing entities which have many-to-one, many-to-many relations as well as collections. Try retrieving historical versions (revisions) of such entities and navigating the object tree.