Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 421
Leo Avatar asked Jan 04 '23 19:01

Leo


1 Answers

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.

like image 195
Naros Avatar answered May 13 '23 19:05

Naros