Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement history data changes with Spring Boot/Spring Data

The problem is how to implement tracking of data changes on e.g. master detail tables i.e. two entities in one to many relationship in Spring Boot/Spring Data.

After storing data, to be able to get the master entity with its details at specific version, and to have functionality to revert it to specific version.

like image 915
user5927256 Avatar asked Oct 18 '25 15:10

user5927256


2 Answers

You can use Hibernate Envers to audit and version your persistence entities changes.

The Envers project aims to enable easy auditing of persistent classes. All that you have to do is annotate your persistent class or some of its properties, that you want to audit, with @Audited. For each audited entity, a table will be created, which will hold the history of changes made to the entity. You can then retrieve and query historical data without much effort.

Similarly to Subversion, the library has a concept of revisions. Basically, one transaction is one revision (unless the transaction didn't modify any audited entities). As the revisions are global, having a revision number, you can query for various entities at that revision, retrieving a (partial) view of the database at that revision. You can find a revision number having a date, and the other way round, you can get the date at which a revision was commited.

The library works with Hibernate and requires Hibernate Annotations or Entity Manager. For the auditing to work properly, the entities must have immutable unique identifiers (primary keys). You can use Envers wherever Hibernate works: standalone, inside JBoss AS, with JBoss Seam or Spring. source

You can query for historic data in a way similar to querying data via the Hibernate criteria API. The audit history of an entity can be accessed using the AuditReader interface, which can be obtained with an open EntityManager or Session via the AuditReaderFactory. source

With Hibernate Envers the 80% of the task is done. You can record your data changes, then access it, either using your persistence context or SQL to apply your version changes using the provide revision id.

Furthermore, you may read the articles listed below:

  • Setting up Hibernate Envers with Spring Boot

  • Auditing with JPA, Hibernate, and Spring Data JPA

  • Hibernate Envers: Simple Implementations

like image 88
eHayik Avatar answered Oct 20 '25 05:10

eHayik


If you use JPA, object auditing frameworks like hibernate envers or javers might help

like image 29
Sudhir Avatar answered Oct 20 '25 06:10

Sudhir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!