Java – use hibernate envers to find recently deleted entities
So my problem is that I need to find all recently deleted entities of a specific class, that is, entities deleted since a specific timestamp Specifically, I want to find entities deleted in the past hour
All my entities have a created and updated timestamp, which I correctly maintain through the listener:
@NotNull @Column(name = "updated") @Type(type="org.joda.time.contrib.hibernate.PersistentDateTime") private DateTime updated;
I also use envers and annotate my entities
So guess, my query should start like this:
// Query for deleted bookings AuditReader reader = AuditReaderFactory.get(entityManager); AuditQuery query = reader.createQuery() .forRevisionsOfEntity(Booking.class,false,true)
But I don't know where to find the reservations deleted since datetime
Solution
First, get the timestamp of one hour ago (in milliseconds):
long timestamp = (System.getCurrentTimeMillis()) - (60*60*1000);
You can then query relative to the timestamp:
AuditReader reader = AuditReaderFactory.get(entityManager); AuditQuery query = reader.createQuery() .forRevisionsOfEntity(Booking.class,true) .add(AuditEntity.revisionProperty("timestamp").gt(timestamp) .add(AuditEntity.revisionType().eq(RevisionType.DEL)); List<Object[]> results = query.getResultList();
Get revision data Each object [] has
>Revision metadata (defaultrevisionentity or your own class annotated with @ revisionentity (customrevisionlistener. Class)) > entity instance (subscription in this case) > revisiontype, in which case we know it is always del