Entity Auditing in Spring Boot with Hibernate Envers

Hakan Yılmaz
2 min readJun 10, 2023

--

Entity Auditing in Spring Boot with Hibernate Envers

What is Hibernate Envers ?

The Envers module is a core Hibernate model that works both with Hibernate and JPA. It aims to provide an easy auditing / versioning solution for entity classes.

Dependency

Add following dependency

Note: Spring boot 3+ needs hibernate 6+

implementation 'org.hibernate:hibernate-envers:6.2.4.Final'

Integration

First setup your entities. You need to add @Audited annotation to activate auditing for entity. Also you can use @AuditTable for specify audit table name.

Example Vehicle entity

@Data
@Entity
@Table(name = "VEHICLE")
@Audited
@AuditTable(value = "AU_VEHICLE")
public class Vehicle {

@Column(name = "PLATE", length = 25)
private String plate;

@Column(name = "DRIVER_NAME", length = 64)
private String driverName;

@Column(name = "DRIVER_PHONE_NUMBER", length = 25)
private String driverPhoneNumber;
}

Create your entity tables with using following property

spring.jpa.hibernate.ddl-auto = update

When you start application, tables are automatically created. You will see Vehicle table, AU_Vehicle table and revinfo table and hibernate_sequence at your database. Then you should change above property ‘update’ to ‘none’ or ‘validate’.

By Default Hibernate enver uses REVINFO table to log data for revision. This includes keeping track of the revision number and timestamp. revinfo table also usees hibernate_sequence for primary key.

There are 3 revision types.

  1. 0 means entity is created;
  2. 1 means entity is updated;
  3. 2 means entity is removed;

When you do any update at vehicle entity, you will see revision history at au_vehicle and revinfo table.

Extra Configurations

With following properties, you can design audit table suffix, prefix and column names. You can see full list in here.

spring.jpa.properties.org.hibernate.envers.audit_table_suffix=
spring.jpa.properties.org.hibernate.envers.audit_table_prefix=AU_
spring.jpa.properties.org.hibernate.envers.revision_field_name=REV_ID
spring.jpa.properties.org.hibernate.envers.revision_type_field_name=REV_TYPE
spring.jpa.properties.org.hibernate.envers.store_data_at_delete=true

store_data_at_delete =true means if you want to keep changes of the removed entity, you must set this property to true. It is false by default.

--

--