Search code examples
hibernate-envers

Hibernate Envers-Get all entities, revision numbers, revision dates and revision types of an Entity by its ID


Using Hibernate Envers I want to get all entities, revision numbers, revision dates and revision types of an Entity by its ID.

Currently I am doing this to obtain the entity, revision number and revision date:

public List<Alumno> obtenerAuditoriaAlumno(Long idAlumno) {

   AuditReader auditReader = AuditReaderFactory.get(entityManager);
   List<Number> revisionNumbers = auditReader.getRevisions(Alumno.class, idAlumno);

   List<Alumno> auditoriaAlumno = new ArrayList<Alumno>();

   for (Number rev : revisionNumbers) {
      Alumno alumno = auditReader.find(Alumno.class, idAlumno, rev);
      Date revisionDate = auditReader.getRevisionDate(rev);

      alumno.setRevisionNumber(rev.intValue());
      //alumno.setRevisionType(revisionType); // GET THIS
      alumno.setRevisionDate(revisionDate);
      auditoriaAlumno.add(alumno);
  }
return auditoriaAlumno;
}

Is it possible to obtain it with one query?

Should I add these fields directly to the Entity?


Solution

  • I would suggest you take a look at using forRevisionsOfEntity. You access this method by using the AuditReader interface as follows:

    auditReader.createQuery().forRevisionsOfEntity( 
       YourAuditEntityClass.class,
       false,                       // false returns an array of entity and audit data
       true                         // selects the deleted audit rows
    );
    

    The important method argument here is the second argument as that influences the returned Object type. When its true, you'll be returned the actual audited entity instances for each revision; however, when its false you'll be returned an Object[] array of values of which are:

    1. The entity instance.
    2. The revision entity instance (where you can get the revision number and date)
    3. The revision type, e.g. ADD, MOD, DEL.

    HTH.