Hibernate envers doesnt save deleted data in aud table
I am using hibernate envers on spring boot have have these configs in application.properties file
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.org.hibernate.envers.store_data_at_delete=true
spring.jpa.properties.org.hibernate.envers.audit_table_suffix=_AUDIT
I am deleting some records from base table, audit tables are created in db but deleted records doesnt show up in audit table or rev table.
How i am deleting records is by using this method :
Query(value = "delete from basetable as a where a.first <= :first and a.sev = :sev and a.id not in (select larm_id from roots as rca where larm_id = a.id)", nativeQuery = true)
void delete(@Param("first") Long firstOccurrence, @Param("sev") int sev);
repo.delete(1639835200L, 0);
What am i doing wrong?
Solution 1:
The problem you face is the fact you're performing a bulk delete.
The query that executes the delete could theoretically delete 0, 1, or multiple rows from the database and such a query does not cause Hibernate to load the entity state. In short, you're effectively performing a JPA CriteriaDelete
query which isn't supported.
If you want to capture deleted state, you need to load the specific entity and delete that single instance of the entity, like:
MyEntity entity = entityManager.find( MyEntity.class, 123L );
entityManager.remove( entity );
Otherwise since Hibernate never loads the entity state, no event listeners get fired that provide the entity state to Envers so that it can be audited.