I. Introduction

In today’s data-centric world, maintaining a comprehensive record of changes and ensuring data integrity is critical for both developers and administrators. Auditing allows you to track and review modifications made to your data, providing a valuable history of who changed what and when. This guide delves into the auditing capabilities provided by Spring Data JPA and Hibernate Envers, exploring their features, benefits, and detailed configuration steps. Whether you’re building a new application or enhancing an existing one, understanding and implementing auditing can greatly improve data governance and traceability.

The importance of Auditing is crucial for a variety of reasons:

  • Data Integrity: Ensures that data changes are recorded, providing a clear history that can be audited or restored if needed.
  • Accountability: Tracks who made changes and when which is essential for compliance and accountability in applications.
  • Debugging: Helps in troubleshooting by allowing you to trace back to the exact point when data was altered.

Spring Data JPA and Hibernate Envers offer robust solutions for implementing auditing, each with its own strengths and use cases.

II. Understanding Auditing in Spring Data JPA

Spring Data JPA is a robust framework that simplifies data access in Java applications. It integrates seamlessly with the Java Persistence API (JPA) to handle CRUD operations and provide features such as pagination and sorting. However, Spring Data JPA does not include built-in auditing features out of the box.

Auditing involves tracking detailed information about changes to data, including:

  • Who made the change
  • When the change was made
  • What changes were made

Important notes for auditing in Spring Data JPA are as follows:

  • @CreatedDate: captures the moment the entity was brought into existence.
  • @LastModifiedDate: records the time of the entity’s most recent update.
  • @CreatedBy: documents the entity’s creator.
  • @LastModifiedBy: keeps track of the person who made the most recent changes to the entity.

1. Enabling JPA Auditing:

Set up a Spring Data JPA application with annotations to activate auditing features. Incorporating @EnableJpaAuditing into the main class is part of this process.

enabling JPA Auditing

2. Adding Spring’s Entity Callback Listener:

Spring Data JPA uses @EntityListeners to specify callback listeners. The `AuditingEntityListener` provided by Spring is used to capture auditing information during entity lifecycle events:

adding spring’s entity callback listener

3. Tracking Created and Last Modified Dates:

You can track creation and modification timestamps by adding `@CreatedDate` and `@LastModifiedDate` annotations to your entity fields. Spring Data JPA automatically updates these fields.

tracking created and last modified dates

4. Author of Changes with Spring Security:

If the application uses Spring Security, it can track who changed the data by using `@CreatedBy` and `@LastModifiedBy`. Implement the `AuditorAware<T>` interface to provide the current user information:

author of changes with spring security

The information comes from SecurityContext’s Authentication instance. To alter values assigned to the annotated fields, we can utilize the `AuditorAware` interface.

AuditorAware

III. Introduction to Hibernate Envers

Hibernate Envers is a module of Hibernate, the object-relational mapping (ORM) tool,  that provides a robust solution for auditing. Envers automatically tracks changes to entities, storing the history of revisions in separate tables. This makes it easy to query historical data and understand how it has evolved.

1. Setting up Hibernate Envers:

To set up Envers, add the `hibernate-envers` JAR into the classpath:

setting up hibernate envers

Then add the `@Audited` annotation, either on an `@Entity` (to audit the whole entity) or on a specific `@Column` (if we need to audit specific properties only).

setting up hibernate envers 2

2. Creating Audit Log Tables:

Set `hibernate.hbm2ddl.auto` to create, create-drop, or update, and then Envers can create them automatically. Consider using auto create table in the database in a business project.

creating audit log tables

3. Configuring Envers:

Set up Envers properties in the same way as you would any other Hibernate property.

configuring envers

4. Accessing Entity History:

Data from the past can be retrieved in a similar way to how data is retrieved using the Hibernate Criteria API. Using an active `EntityManager` or `Session`, the `AuditReader` interface can be used to access the audit history of an entity via the `AuditReaderFactory`.

accessing entity history

IV. Custom Revision

By default, Envers tracks “what” changed but does not include details on “who” or “when” changes occurred. You can customize the revision table to include additional fields like username and revision date.

1. Implement a Custom Revision Entity:

implement a custom revision entity

2. Create a Revision Listener:

create a revision listener

V. Database Behavior with Auditing

1. Auto-Updating Entities with Auditing:

After configuring the Auditing with annotations, the client sends the request CRUD with only the necessary fields, and other fields that were config Auditing will auto-update data in the database.

auto-updating entities with auditing

auto-updating entities with auditing 2

2. History revision tables:

The system automatically creates two new tables, one named `revinfo` and the other `[entity_name]_aud`.

– In the revinfo table, it’s the tracking time of each revision, but it has the limitation that it shows the timestamp in `long` type, so it’s hard for developers to track ‘when’ the entity changes.

– In [entity_name]_aud table, in each transaction will create new records. With `id` column is represented for entity id. The `rev` is represented as a timestamp in the revision table. The `revtype` represents the action of each change: 0 – Create, 1 – Update, 2 – Delete.

* A noted that after each action (CRUD), it will create only 1 record even when you update 1 or more than 1 field in each request. 

history revision tables

3. Custom revision results:

The result after the config customization revision is that we can track the time and username of each transaction:

custom revision results

VI. Conclusion

Implementing auditing with Spring Data JPA and Hibernate Envers is essential for maintaining data integrity and tracking changes effectively. By following the steps outlined in this guide, you can configure comprehensive auditing mechanisms that provide valuable insights into your data’s history and evolution.

Auditing not only aids in maintaining data integrity and compliance but also supports debugging and operational transparency. Whether you’re developing a new application or upgrading an existing system, integrating auditing will significantly enhance your application’s robustness and reliability.

References

Content manager
Thanh (Bruce) Pham
CEO of Saigon Technology
A Member of Forbes Technology Council

Related articles

IT Support Outsourcing: Enhancing Efficiency & Reducing Costs
Methodology

IT Support Outsourcing: Enhancing Efficiency & Reducing Costs

We cover the benefits and types of IT support outsourcing in this blog. We also cover some factors to consider when selecting a capable outsourcing partner.
Deep dive into java.time: Instant
Methodology

Deep dive into java.time: Instant

Java's Instant class is immutable, thread-safe, and ideal for time-sensitive applications needing absolute time without time zones.
Finance App Development: The Complete Guide
Methodology

Finance App Development: The Complete Guide

Explore finance app development essentials from types to key features and discover how to develop secure, user-friendly financial solutions.
Telemedicine App Development: A Complete Guide
Methodology

Telemedicine App Development: A Complete Guide

Dive into our telemedicine app development guide. Learn about essential features, development costs, monetization strategies, and key steps.
Real Estate App Development: Your Step-by-Step Guide
Methodology

Real Estate App Development: Your Step-by-Step Guide

Dive into real estate app development and learn key features and strategies to create an app that buyers, sellers, and renters love.
How Software Testing Outsourcing Works: A Detailed Overview
Methodology

How Software Testing Outsourcing Works: A Detailed Overview

Discover how outsourcing software testing improves quality, cuts costs, and boosts efficiency. It also speeds up product delivery, keeping you competitive.
HIPAA-Compliant App Development: Everything You Need to Know
Methodology

HIPAA-Compliant App Development: Everything You Need to Know

Learn everything you need to know about HIPAA-compliant app development. Discover key requirements, best practices, and steps. Check it now!
Mobile Banking App Development: A Complete Guide
Methodology

Mobile Banking App Development: A Complete Guide

Mobile banking app development offers unmatched convenience. Learn how to develop powerful banking apps with Saigon Technology. Read now!
17 Mobile App Development Trends for 2025
Methodology

17 Mobile App Development Trends for 2025

Discover the top 17 mobile app development trends shaping 2025! From AI integration to 5G advancements and other emerging innovations.

Want to stay updated on industry trends for your project?

We're here to support you. Reach out to us now.
Contact Message Box
Back2Top