Search code examples
spring-bootliquibasehibernate-envers

How to run one-off script to manipulate jpa entities data and keep trace on envers?


I want to run a one-off script on spring to modify jpa entities and I would like those changes to appear on envers audit tables.

I have a spring-boot application using envers to keep track of changes of some JPA entities. It is using liquibase to run db migrations for DDL changes.

Ideally, I wanted the script to be java liquibase migration, however liquibase runs before the spring context is initialized so only jdbc statements could be run. On one hand, I understand the reasons behind, JPA should be initialized after the database is set-up; on the other hand, I would like to have a system similar to liquibase, that keeps track of scripts that have been run and will look for new ones once the spring context has been initialized.

Any suggestion or idea of what I could use or the best way to go in this case?


Solution

  • There are ultimately two things your script could be doing

    1. Schema Migration
    2. Data Migration

    For Schema Migration, there is nothing that stops that script from applying the necessary schema changes to the envers audit tables just like it does for the JPA entity mappings. It's likely the best approach as the table structures should be kept in sync and therefore migrated in the same physical way, so keeping that behavior centralized in the same place just makes for good long-term general housekeeping of these actions.

    For Data Migration, that's an entirely different ball-game.

    Envers heavily relies on the Hibernate Event Listener framework for changes to be captured in the envers audit schema, so anything that bypasses or does not generate such events are lost. So if you want these operations to be captured, you either need to do them through ORM or manually insert the events yourself.

    In Hibernate 6, there will be a new feature where you'll be able to control at a more granular level its own Schema Migration functionality. For example, you'll be able to say that the ORM tables are never updated, perhaps that's where you use Liquibase for those but you can explicitly mark Envers objects to always be updated. But remember, there are limitations to Hibernate's Schema Migration.

    I do have some long-term ideas on how to improve all this but nothing I can share concretely yet. What I describe above is what's presently available or the general how-to-do-it procedure for now.