Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get previous version of entity in Hibernate Envers

I have an entity loaded by Hibernate (via EntityManager):

User u = em.load(User.class, id)

This class is audited by Hibernate Envers. How can I load the previous version of a User entity?

like image 877
razenha Avatar asked Apr 27 '09 14:04

razenha


1 Answers

Building off of the excellent approach of @brad-mace, I have made the following changes:

  • You should pass in your EntityClass and Id instead of hardcoding and assuming the Model.
  • Don't hardcode your EntityManager.
  • There is no point setting selectDeleted, because a deleted record can never be returned as the previous revision.
  • Calling get single result with throw and exception if no results or more than 1 result is found, so either call resultlist or catch the exception (this solution calls getResultList with maxResults = 1)
  • Get the revision, type, and entity in one transaction (remove the projection, use orderBy and maxResults, and query for the Object[3] )

So here's another solution:

public static <T> T getPreviousRevision(EntityManager entityManager, Class<T> entityClass, Object entityId, int currentRev) {
    AuditReader reader = AuditReaderFactory.get(entityManager);
    List<Object[]> priorRevisions = (List<Object[]>) reader.createQuery()
            .forRevisionsOfEntity(entityClass, false, false)
            .add(AuditEntity.id().eq(entityId))
            .add(AuditEntity.revisionNumber().lt(currentRev))
            .addOrder(AuditEntity.revisionNumber().desc())
            .setMaxResults(1)
            .getResultList();

    if (priorRevisions.size() == 0) {
        return null;
    }
    // The list contains a single Object[] with entity, revinfo, and type 
    return (T) priorRevision.get(0)[0];
}
like image 86
Steven Spungin Avatar answered Sep 24 '22 01:09

Steven Spungin