If you want to wipe out a revision by ID, you can access the envers table directly using a native query. There are 2 tables that contain references to the revision. Assuming your audit table uses the conventional _AUD suffix, you can find the entity table name programmatically.
Here are some snippets written in Kotlin:
fun getAuditTableName(em: EntityManager, aClass: Class<*>): String {
return getAuditTableName(em, aClass.name) + "_AUD"
}
fun getEntityTableName(em: EntityManager, aClass: Class<*>): String {
val session = em.unwrap(Session::class.java) as Session
val sessionFactory = session.sessionFactory
val hibernateMetadata = sessionFactory.getClassMetadata(className)
val persister = hibernateMetadata as AbstractEntityPersister
return persister.tableName
}
Now that we have the table name, we can remove the rows in the tables. (Put this in your JPA transaction block, replace the content as needed, and adjust the SQL for your provider). So given MyEntityClass and myRevisionId, we can do something like this:
val em:EntityManager = getEntityManager()
val auditTableName = getAuditTableName(MyEntityClass::class.java)
em.createNativeQuery("delete from `$auditTableName` where REV=${myRevisionId}").executeUpdate()
em.createNativeQuery("delete from REVINFO where REV=${myRevisionId}").executeUpdate()
If you want to delete by a parameter other than the revisionID, simply query for the the revisionIds in the entity_AUD table, and then delete the found rows in the mentioned way.
Keep in mind that a revisionId may be associated with more than 1 entity, and all of the entries will be removed in the previous method. To delete the revision for a single entity, you will need the entity's ID and entity's key field name(s).
Here is code for dynamically getting the field name:
fun getEntityKeyNames(em: EntityManager, entityClass: Class<*>): List<String> {
val session = em.unwrap(Session::class.java) as Session
val sessionFactory = session.sessionFactory
val hibernateMetadata = sessionFactory.getClassMetadata(entityClass.name)
val persister = hibernateMetadata as AbstractEntityPersister
return persister.keyColumnNames.toList()
}
" order by.*"
from the select query, then this is working for me too. The order by was probably added in a later version of Envers. – Edition