Search code examples
spring-boothibernate-enversspring-data-envers

Find newest Revisions of Entities where timestamp is less than x


I have a max timestamp that I pass to my backend and I want to return the newest versions of the Entities that have a timestamp that is less than the passed one.
The passed timestamp in my example is 180. I've kept the numbers low so that it is easier to visualize.

This is a combination of a horizontal and a vertical Query and I'm not sure how I can achieve that.

The desired result:

painting of the result


Solution

  • It can be achieved with the following:

    public List<Book> getBooksByMaxTimestamp(Date date) {
        String formattedDate = simpleDateFormat.format(date);
        System.out.println("Less than " + formattedDate);
    
        AuditQuery maxRevisionNumberQuery = auditReader.createQuery().forRevisionsOfEntity(Book.class, true, false);
         
        maxRevisionNumberQuery.add(AuditEntity.revisionProperty("timestamp").le(date.getTime()));
        maxRevisionNumberQuery.addProjection(AuditEntity.revisionNumber().max());
        int maxRevisionNumber = (int) maxRevisionNumberQuery.getSingleResult();
    
        AuditQuery auditQuery = auditReader.createQuery().forEntitiesAtRevision(Book.class, maxRevisionNumber);
        return auditQuery.getResultList();
    }
    

    First we get the max revision number that is in that range and after that we use that number to get the entities that we want.