VOOZH about

URL: https://www.geeksforgeeks.org/advance-java/auditing-with-hibernate-envers-in-spring-boot/

⇱ Auditing with Hibernate Envers in Spring Boot - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Auditing with Hibernate Envers in Spring Boot

Last Updated : 30 Apr, 2026

Auditing with Hibernate Envers in Spring Boot allows automatic tracking of entity changes such as insert, update, and delete operations. It maintains historical data without requiring manual audit logic or separate tracking code.

  • Automatically creates audit tables to store entity history
  • Uses annotations like @Audited for easy configuration
  • Helps track who changed data and when (with timestamps)

Key Components of Auditing

  • Change Tracking: Monitoring what changes are made to the data.
  • Versioning: Maintaining different versions of the data over time.
  • Metadata Recording: Capturing who made the changes and when they were made.
  • Historical Data Access: Providing mechanisms to retrieve past states of the data.

Why Auditing is Required?

Auditing serves multiple critical purposes in applications:

  • Compliance and Regulatory Requirements: Many industries, such as finance, healthcare, and government, are subject to strict regulations that mandate data auditing. Ensuring compliance helps avoid legal penalties and maintains trust with stakeholders.
  • Data Integrity and Security: Auditing helps detect unauthorized or malicious access by providing a trail of who accessed or modified data, ensuring that data remains accurate and reliable over time.
  • Troubleshooting and Debugging: When issues arise, audit logs can provide valuable insights into the sequence of events leading to the problem, facilitating efficient troubleshooting and debugging.
  • Historical Analysis and Reporting: Auditing data allows for historical analysis, trend identification, and comprehensive reporting, which can inform business decisions and strategies.
  • Accountability and Transparency: Auditing fosters accountability by attributing data changes to specific users or processes, promoting transparency within the organization.

Unique Facts About Auditing Using Hibernate Envers

Hibernate Envers simplifies the auditing process by automatically tracking entity changes and maintaining audit tables. Here’s what makes Hibernate Envers unique:

  • Seamless Integration with Hibernate ORM: Envers integrates tightly with Hibernate ORM, leveraging its mapping and session management capabilities. This ensures efficient and consistent auditing without significant overhead.
  • Annotation-Based Configuration: Using annotations like @Audited, developers can easily specify which entities and fields should be audited, reducing configuration complexity.
  • Automatic Audit Table Creation: Envers automatically generates and manages the audit tables corresponding to audited entities. These tables store the historical records of entity changes without manual intervention.
  • Versioning Support: Envers maintains different versions of the entities, allowing retrieval of entity states at any revision. This facilitates comprehensive historical data access.
  • Flexible Querying: It provides APIs to query historical data, such as retrieving revisions, tracking changes over time, and comparing different versions of entities.
  • Minimal Boilerplate Code: It handles auditing logic internally, minimizing the need for boilerplate code and allowing developers to focus on business logic.
  • Customization Capabilities: While Envers offers sensible defaults, it allows customization of auditing behavior, such as defining custom revision entities or excluding specific fields from auditing.

Using the In-built Auditing Mechanism in Spring Boot

Spring Boot, combined with Hibernate Envers and Spring Data JPA, provides robust auditing capabilities. Below are the steps to implement auditing in a Spring Boot application using Hibernate Envers.

Step 1: Create a New Spring Boot Project

Create a new Spring Boot project using IntelliJ IDEA. Choose the following options:

  • Name: spring-boot-audit-example
  • Language: Java
  • Type: Maven
  • Packaging: Jar

Click on the Next button.

πŸ‘ Project Metadata

Step 2: Add the Dependencies

Add the following dependencies into the Spring Boot.

  • Spring Web
  • Spring Data JPA
  • MySQL Driver
  • Spring Boot DevTools

Click on the Create button.

πŸ‘ Add Dependencies

External Dependency:

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-envers -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>3.5.3-Final</version>
</dependency>

Project Structure

After the project creation done, the folder structure will look like the below image:

πŸ‘ Project Folder Structure

Step 3: Configure Application Properties

Open the application.properties file and add the following configuration for MySQL and Hibernate Envers properties:

spring.application.name=spring-boot-audit-example
spring.datasource.url=jdbc:mysql://localhost:3306/audit_example
spring.datasource.username=root
spring.datasource.password=mypassword
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.ejb.interceptor=org.hibernate.envers.event.EnversIntegrator

Step 4: Create the User Class

Create the User entity that will be audited in your Spring Boot project.

User.java:

Step 5: Create the UserRepository Interface

Step 6: Create the UserService Class

Create the UserService class to handle user-related operations in the Spring Boot application.

UserService.java:

Step 7: Create the UserController Class

Create the UserController class to expose the user API endpoints of the Spring Boot application.

UserController.java:

Step 8: Main Class

No changes are required in the main class.

pom.xml File:

Step 9: Run the Application

Once the project will be completed, it will run and start at port 8080. It will automatically create the necessary database tables, including the audit tables.

πŸ‘ Project Running


Console Logs:

πŸ‘ Console Logs

Step 10: Testing the Application

To test the auditing functionality, you can use tools like Postman or cURL to interact with the API endpoints:

1. Create a User

Make a POST request to /api/users with a JSON body.

POST http://localhost:8080/api/users

Output:

πŸ‘ Create User

2. Get All Users

Make a GET request to /api/users to retrieve all users.

GET http://localhost:8080/api/users

Output:

πŸ‘ Get All Users

3. Get a User by ID

Make a GET request to /api/users/{id} to retrieve a specific user.

GET http://localhost:8080/api/users/1

Output:

πŸ‘ Get a User by ID

4. Delete User

Make a DELETE request to /api/users/{id} to delete a user.

DELETE http://localhost:8080/api/users/1

Note: After deleting a user, the record is removed from the main table, but Hibernate Envers stores the last state in the audit table (e.g., user_AUD) with a delete revision (REVTYPE = DEL). This allows tracking deleted data.

Output:

πŸ‘ Delete User

User Table:

πŸ‘ User Table

Hibernate Envers automatically creates an audit table (e.g., user_AUD) that stores all changes including insert, update, and delete operations. Even if a user is deleted, its historical data remains available here.

Accessing Deleted Data from Audit Table

AuditReader reader = AuditReaderFactory.get(entityManager);
User user = reader.find(User.class, userId, revisionNumber);

This allows retrieving past versions of an entity, even after it has been deleted.


Comment

Explore