views:

646

answers:

4

I have an entity loaded by Hibernate (via EntityManager)

User u = em.load(User.class, id)

This class is auditaded by Hibernate Envers. I want to load the previous version of this class. How can I do it?

Thanks

A: 

From the docs:

AuditReader reader = AuditReaderFactory.get(entityManager);
User user_rev1 = reader.find(User.class, user.getId(), 1);
Rich Kroll
I'm not sure this works for my, I want to get the previous version, your example get a mandatory version (in this case, the version number 1).
razenha
+2  A: 

maybe this then (from AuditReader docs)

AuditReader reader = AuditReaderFactory.get(entityManager);
User user_rev1 = reader.find(User.class, user.getId(), 1);

List<Number> revNumbers = reader.getRevisions(User.class, user_rev1);
User user_previous = reader.find(User.class, user_rev1.getId(),
  revNumbers.get(revNumbers.size()-1));

(I'm very new to this, not sure if I have all the syntax right, maybe the size()-1 should be size()-2?)

Jason S
A: 

I think it would be this:

final AuditReader reader = AuditReaderFactory.get( entityManagerOrSession );

// This could probably be declared as Long instead of Object
final Object pk = userCurrent.getId();

final List<Number> userRevisions = reader.getRevisions( User.class, pk );

final int revisionCount = userRevision.size();

final Number previousRevision = userRevisions.get( revisionCount - 2 );

final User userPrevious = reader.find( User.class, pk, previousRevision );
Jamie Bisotti
A: 

Just wanted to update everyone that the newest version of envers (1.2.1.GA) has a shortcut method for getting the current revision. See AuditReader.getCurrentRevision().

qbn