Get previous version of entity in Hibernate Envers

后端 未结 5 1742
孤街浪徒
孤街浪徒 2021-01-31 22:36

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

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

This class is audited by Hibernate Enve

5条回答
  •  抹茶落季
    2021-01-31 23:40

    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 getPreviousRevision(EntityManager entityManager, Class entityClass, Object entityId, int currentRev) {
        AuditReader reader = AuditReaderFactory.get(entityManager);
        List priorRevisions = (List) 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];
    }
    

提交回复
热议问题