How to add audit row to audit table using spring data jpa

Viewed 2186

I am having a "user" table at any time if a row inserted or updated or deleted then I need to insert a row in the "user_audit" table with all user data and action columns to note the action performed.

I am using spring batch, spring data JPA to insert data into the user table

How I can implement this in spring batch using spring data JPA or is there any implementation provided by JPA/hibernate?

1 Answers

If you use Hibernate you can use Envers which offers:

  • Auditing of all mappings defined by the JPA specification

  • Auditing some Hibernate mappings that extend JPA, e.g. custom types and collections/maps of "simple" types like Strings, Integers.

  • Logging data for each revision using a "revision entity"

  • Querying historical snapshots of an entity and its associations

However Envers will only audit changes which originated from Hibernate.

If for example you are using JPA native queries or JDBC API these changes won't be audited. That's why it's often safer to define database triggers that will perform the audit. Here and here is PostgreSQL example.

Related