Welcome back to our Hibernate series! In this post, we will explore Hibernate Envers, a powerful tool that allows you to track and audit changes to your entities over time. Auditing is crucial for applications that require a reliable history of data changes for accountability, compliance, or debugging purposes.
What is Hibernate Envers?
Hibernate Envers is a module that provides automatic auditing of entity states. When you make changes to your entities, Envers records the state of these entities in a separate audit table. This means you can track when an entity was created, modified, or deleted without manually implementing tracking features.
Setting Up Hibernate Envers
To get started with Envers, you need to include the Envers dependency in your project. If you are using Maven, add the following to your pom.xml
:
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-envers</artifactId>
<version>5.4.32.Final</version>
</dependency>
Annotating Entities for Auditing
Next, you need to annotate your entities to enable auditing. Let’s take our Product
entity and add auditing capabilities:
import org.hibernate.envers.Audited;
import javax.persistence.*;
@Audited
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false)
private String name;
@Column
private Double price;
// Getters and setters
}
In this example:
@Audited
indicates that this entity should be tracked for auditing purposes.
Working with Audit Tables
When you annotate an entity with @Audited
, Hibernate Envers automatically creates audit tables in your database. For the Product
entity, you would see a corresponding table named product_audit
where all changes are stored.
Retrieving Historical Data
Envers provides a straightforward API to access the historical versions of an audited entity. Here’s how you can retrieve all versions of a Product
by its ID:
import org.hibernate.envers.AuditReader;
import org.hibernate.envers.AuditReaderFactory;
public List<Product> getProductHistory(Long productId) {
Session session = sessionFactory.openSession();
AuditReader auditReader = AuditReaderFactory.get(session);
List<Product> productHistory = auditReader.createQuery()
.forRevisionsOf(Product.class, false, true)
.add(AuditEntity.id().eq(productId))
.getResultList();
session.close();
return productHistory;
}
In this method:
- We create an
AuditReader
instance to query the audit history of the specified product. - The
forRevisionsOf()
method retrieves the historical versions, returning a list ofProduct
instances along with their changes.
Versioning and Customizing Audit Data
Hibernate Envers allows you to customize the data stored in audit tables, such as including or excluding certain fields or implementing a custom revision entity. To change the default behavior:
### 1. Custom Revision Entity: You can create a custom revision entity to record additional metadata, such as who made the changes or timestamps:import org.hibernate.envers.RevisionEntity;
import javax.persistence.*;
@Entity
@RevisionEntity
public class CustomRevisionEntity extends DefaultRevisionEntity {
@Column(name = "modified_by")
private String modifiedBy;
// Getters and setters for modifiedBy
}
### 2. Specifying Fields to Audit:
You can control what fields are audited using annotations to exclude specific fields:
@Audited(exclude = { "price" })
private String description;
Conclusion
In this post, we explored Hibernate Envers and how it can aid in auditing your entity changes over time. By enabling auditing on your entities, you can easily track the history of modifications, providing better traceability for your application.
We learned how to configure Envers, retrieve audit information, customize audit data, and handle revisions. Envers is a powerful feature that can add significant value to your applications, especially in scenarios where data integrity and accountability are paramount.
Keep exploring the functionalities of Hibernate to unlock the full potential of your applications. Stay tuned for more in-depth discussions in our Hibernate series!
To learn more about ITER Academy, visit our website: ITER Academy.