Java Programming
Undo & Redo with Hibernate, JPA and Spring Data
How many times have you found yourself wanting to go back when editing a field in a CRUD application? Undo & Redo is one of the most requested features yet most CRUD type applications are missing it! In this guide I will show you how to implement that feature in a Spring Boot app using Spring Data and JPA so your users can always go back if they want to.
Database schema and logic
Let's start with how we are going to store our data, so we can easily go back to previous revisions. The easiest way to do it is to maintain a separate database table for historic entries and when an entity gets updated we just copy the old values over to the table.
You could implement this manually using a separate Spring Repository for the historic entries table but it would also require us to write some application logic to always call the repository when something changes.
The good news is we can use a library which will hide this logic from us, so we don't have to care about storing old entries and can focus on writing the application code and the history is kept automatically.
For this purpose we are going to use the Hibernate Envers module.
The features of Hibernate Envers according to the project page are:
- 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
While the project mostly is used for auditing, the functionality is equally good for setting up a scheme for undoing and re-doing.