Search code examples
springhibernatespring-datahibernate-envers

View change history entity for any date with hibernate


There is a problem - I have to watch the state of the table with entities for any date.

Please tell me how to implement this task via envers, or another solution is better and easier than envers

I use in my project spring-boot, spring-data and hibernate. For this I tried to use Hibernate-envers. My code looks like this, but it does not solved the problem:

List list = auditReader.createQuery()
            .forRevisionsOfEntity(Entity.class, false, true)
            .addOrder(AuditEntity.revisionNumber().desc())
            .addProjection(AuditEntity.property("id").distinct())
            .add(AuditEntity.revisionNumber().le(auditReader.getRevisionNumberForDate(new Date())))
            .getResultList();

Solution

  • I found solution in question.

    list = auditReader.createQuery()
                    .forRevisionsOfEntity(Entity.class, true, true)
                    .add(AuditEntity.revisionNumber().le(auditReader.getRevisionNumberForDate(date)))
                    .add(AuditEntity.revisionNumber().maximize().computeAggregationInInstanceContext())
                    .add(AuditEntity.revisionType().ne(RevisionType.DEL))
                    .getResultList();
    

    This query returns a ready list of entities. Function 'computeAggregationInInstanceContext()' works according to the documentation and would like a GROUP BY statement:

    Compute aggregated expression in the context of each entity instance separately.

    Dont forget catch 'RevisionDoesNotExistException', in case you return empty list