Java 类org.hibernate.envers.AuditReaderFactory 实例源码

项目:VersioningWithEnvers    文件:CustomerHistoryRepository.java   
@Transactional(readOnly = true)
public List<CustomerHistory> listCustomerRevisions(Long customerId) {

    // Create the Audit Reader. It uses the EntityManager, which will be opened when
    // starting the new Transation and closed when the Transaction finishes.
    AuditReader auditReader = AuditReaderFactory.get(entityManager);

    // Create the Query:
    AuditQuery auditQuery = auditReader.createQuery()
            .forRevisionsOfEntity(Customer.class, false, true)
            .add(AuditEntity.id().eq(customerId));

    // We don't operate on the untyped Results, but cast them into a List of AuditQueryResult:
    return AuditQueryUtils.getAuditQueryResults(auditQuery, Customer.class).stream()
            // Turn into the CustomerHistory Domain Object:
            .map(x -> getCustomerHistory(x))
            // And collect the Results:
            .collect(Collectors.toList());
}
项目:cibet    文件:EnversActuatorIntegrationTest.java   
@Test
public void persist2() throws Exception {
   if (!JBOSS.equals(APPSERVER)) {
      return;
   }
   log.info("start persist2()");
   AuditedTComplexEntity ce = createAuditedTComplexEntity();
   applEman.persist(ce);
   applEman.getTransaction().commit();
   applEman.getTransaction().begin();

   List<Archive> archList = ArchiveLoader.loadArchivesByPrimaryKeyId(AuditedTComplexEntity.class.getName(),
         String.valueOf(ce.getId()));
   Assert.assertEquals(0, archList.size());

   AuditReader ar = AuditReaderFactory.get(applEman);
   AuditQuery query = ar.createQuery().forRevisionsOfEntity(AuditedTComplexEntity.class, true, true);
   List<AuditedTComplexEntity> resList = query.getResultList();
   Assert.assertEquals(0, resList.size());
}
项目:cibet    文件:EnversActuatorIntegrationTest.java   
@Test
public void delete1() throws Exception {
   if (!JBOSS.equals(APPSERVER)) {
      return;
   }
   log.info("start delete1()");
   AuditedTComplexEntity ce = createAuditedTComplexEntity();
   applEman.persist(ce);
   applEman.getTransaction().commit();
   applEman.getTransaction().begin();

   applEman.remove(ce);
   applEman.getTransaction().commit();
   applEman.getTransaction().begin();

   AuditReader ar = AuditReaderFactory.get(applEman);
   AuditQuery query = ar.createQuery().forRevisionsOfEntity(AuditedTComplexEntity.class, true, true);
   List<AuditedTComplexEntity> resList = query.getResultList();
   Assert.assertEquals(1, resList.size());
   AuditedTComplexEntity ce2 = resList.get(0);
   log.debug(ce2);
   Assert.assertEquals(2, ce2.getEagerList().size());
}
项目:cibet    文件:EnversActuatorIntegrationTest.java   
@Test
public void update1() throws Exception {
   if (!JBOSS.equals(APPSERVER)) {
      return;
   }
   log.info("start update1()");
   AuditedTComplexEntity ce = createAuditedTComplexEntity();
   applEman.persist(ce);
   applEman.getTransaction().commit();
   applEman.getTransaction().begin();

   ce.setOwner("new owner");
   ce = applEman.merge(ce);
   applEman.getTransaction().commit();
   applEman.getTransaction().begin();

   AuditReader ar = AuditReaderFactory.get(applEman);
   AuditQuery query = ar.createQuery().forRevisionsOfEntity(AuditedTComplexEntity.class, true, true);
   List<AuditedTComplexEntity> resList = query.getResultList();
   Assert.assertEquals(1, resList.size());

   AuditedTComplexEntity ce2 = resList.get(0);
   Assert.assertEquals("new owner", ce2.getOwner());
}
项目:Tank    文件:JobNotificationDao.java   
/**
 * gets the entity at the specified revision
 * 
 * @param id
 *            the id of the entity to fetch
 * @param revisionNumber
 *            the revision number
 * @return the entity or null if no entity can be found
 */
@Nullable
@Override
public JobNotification findRevision(int id, int revisionNumber) {
    JobNotification result = null;
    try {
        begin();
        AuditReader reader = AuditReaderFactory.get(getEntityManager());
        result = reader.find(JobNotification.class, id, revisionNumber);
        Hibernate.initialize(result.getLifecycleEvents());
        result.getLifecycleEvents().contains(JobLifecycleEvent.QUEUE_ADD);
        commit();
    } catch (NoResultException e) {
        LOG.warn("No result for revision " + revisionNumber + " with id of " + id);
    } finally {
        cleanup();
    }
    return result;
}
项目:Tank    文件:BaseDao.java   
/**
 * 
 * @param id
 * @return
 */
public int getHeadRevisionNumber(int id) {
    int result = 0;
    try {
        begin();
        AuditReader reader = AuditReaderFactory.get(getEntityManager());
        List<Number> revisions = reader.getRevisions(entityClass, id);
        if (!revisions.isEmpty()) {
            result = revisions.get(revisions.size() - 1).intValue();
        }
        commit();
    } catch (NoResultException e) {
        rollback();
        LOG.warn("No result for revision with id of " + id);
    } finally {
        cleanup();
    }
    return result;
}
项目:Tank    文件:BaseDao.java   
/**
 * gets the entity at the specified revision
 * 
 * @param id
 *            the id of the entity to fetch
 * @param revisionNumber
 *            the revision number
 * @return the entity or null if no entity can be found
 */
@Nullable
public T_ENTITY findRevision(int id, int revisionNumber) {
    T_ENTITY result = null;
    try {
        begin();
        AuditReader reader = AuditReaderFactory.get(getEntityManager());
        result = reader.find(entityClass, id, revisionNumber);
        commit();
    } catch (NoResultException e) {
        rollback();
        LOG.warn("No result for revision " + revisionNumber + " with id of " + id);
    } finally {
        cleanup();

    }
    return result;
}
项目:ds4p    文件:AuditServiceImpl.java   
public List<HistoryDto> findAllHistory(String username) {

        Patient patientA = patientRepository.findByUsername(username);
        Long patientId = patientA.getId();

        EntityManager em = entityManagerFactory.createEntityManager();
        AuditReader reader = AuditReaderFactory.get(em);
        List<Number> revisions = reader.getRevisions(Patient.class, patientId);
        List<HistoryDto> historyList = findHistoryDetails(revisions);
        List<HistoryDto> legalHistoryList = findLegalHistoryByPatient(patientId);
        historyList.addAll(legalHistoryList);
        Collections.sort(historyList);

        List<HistoryDto> historyListReverse = getReversed(historyList);
        em.close();
        return historyListReverse;
    }
项目:karaku    文件:EnversReplicationProvider.java   
/**
 * @param clazz
 * @param lastId
 * @return
 */
@SuppressWarnings("unchecked")
private <T extends Shareable> Bundle<T> getDelta(Class<T> clazz,
        String lastId) {

    AuditReader ar = AuditReaderFactory.get(getSession());
    Number number = getLastId(clazz, lastId);
    List<Object[]> entities = ar.createQuery()
            .forRevisionsOfEntity(clazz, false, false)
            .add(AuditEntity.revisionNumber().gt(number)).getResultList();

    Bundle<T> bundle = new Bundle<T>(lastId);
    for (Object[] o : entities) {
        if (o == null) {
            continue;
        }
        bundle.add((T) notNull(o[0]), notNull(getId(o[1])));
    }
    return bundle;
}
项目:karaku    文件:EnversReplicationProvider.java   
/**
 * @param clazz
 * @param reader
 * @param lastId
 * @return
 */
@SuppressWarnings("unchecked")
private <T extends Shareable> boolean isUnknown(Class<T> clazz,
        String lastId) {

    if (Bundle.FIRST_CHANGE.equals(lastId)) {
        return false;
    }

    AuditReader reader = AuditReaderFactory.get(getSession());
    List<T> entitiesAtRevision = reader.createQuery()
            .forRevisionsOfEntity(clazz, false, false)
            .add(AuditEntity.revisionNumber().eq(getLastId(clazz, lastId)))
            .getResultList();
    return (entitiesAtRevision == null) || entitiesAtRevision.isEmpty();
}
项目:karaku    文件:EnversReplicationProvider.java   
@Nonnull
private <T extends Shareable> Bundle<T> getAll(@Nonnull Class<T> clazz) {

    AuditReader reader = AuditReaderFactory.get(getSession());
    Number prior = (Number) reader.createQuery()
            .forRevisionsOfEntity(clazz, false, true)
            .addProjection(AuditEntity.revisionNumber().max())
            .getSingleResult();

    String lastId;
    // previous revision, la actual no será persistida.
    if (prior == null) {
        lastId = Bundle.FIRST_CHANGE;
    } else {
        lastId = String.valueOf(prior);
    }
    return firstChangeProviderHandler.getAll(clazz, notNull(lastId));

}
项目:spring-envers-audit    文件:DefaultRevisionAwareJpaRepository.java   
@Override
@SuppressWarnings("unchecked")
public Revision<N, T> findLastChangeRevision(ID id) {
    Class<T> type = entityInformation.getJavaType();
    AuditReader reader = AuditReaderFactory.get(entityManager);

    List<Number> revisions = reader.getRevisions(type, id);

    if (revisions.isEmpty()) {
        return null;
    }

    N latestRevision = (N) revisions.get(revisions.size() - 1);

    Class<?> revisionEntityClass = revisionEntityInformation.getRevisionEntityClass();

    Object revisionEntity = reader.findRevision(revisionEntityClass, latestRevision);
    RevisionMetadata<N> metadata = (RevisionMetadata<N>) getRevisionMetadata(revisionEntity);
    return new Revision<N, T>(metadata, reader.find(type, id, latestRevision));
}
项目:spring-envers-audit    文件:DefaultRevisionAwareJpaRepository.java   
@Override
@SuppressWarnings("unchecked")
public Page<Revision<N, T>> findRevisions(ID id, Pageable pageable) {
    Class<T> type = entityInformation.getJavaType();
    AuditReader reader = AuditReaderFactory.get(entityManager);
    List<Number> revisionNumbers = reader.getRevisions(type, id);

    if (pageable.getOffset() > revisionNumbers.size()) {
        return new PageImpl<Revision<N, T>>(Collections.<Revision<N, T>> emptyList(), pageable, 0);
    }

    int upperBound = pageable.getOffset() + pageable.getPageSize();
    upperBound = upperBound > revisionNumbers.size() ? revisionNumbers.size() : upperBound;

    List<? extends Number> subList = revisionNumbers.subList(pageable.getOffset(), upperBound);
    Revisions<N, T> revisions = getEntitiesForRevisions((List<N>) subList, id, reader);

    return new PageImpl<Revision<N, T>>(revisions.getContent(), pageable, revisionNumbers.size());
}
项目:Tanaguru    文件:ProcessResultDAOImpl.java   
@Override
public List<DefiniteResult> getHistoryChanges(ProcessResult processResultImpl) {

    List<DefiniteResult> history = new ArrayList<>();
    AuditReader auditReader = AuditReaderFactory.get(this.entityManager);
    Long id = processResultImpl.getId();
    if (id == null) {
        return new ArrayList<>();
    }
    List<Number> revisions = auditReader.getRevisions(processResultImpl.getClass(), id);
    DefiniteResult find = null;
    for (int i = 0; i < revisions.size(); i++) {
        Number revision = revisions.get(i);
        find = auditReader.find(DefiniteResultImpl.class, id, revision);
        history.add(find);
    }

    return history;

}
项目:mojito    文件:CurrentVariantRollbackService.java   
/**
 * Builds the query to insert new {@link com.box.l10n.mojito.entity.TMTextUnitCurrentVariant}s
 * as they were at the rollback date.
 *
 * @param rollbackDateTime Date at which the {@link TMTextUnitCurrentVariant}s will be rollbacked to
 * @param tmId             ID of the TM the {@link TMTextUnitCurrentVariant}s to be rolled back should belong to
 * @param extraParameters  Extra parameters to filter what to rollback
 * @return The insert audit query
 */
protected AuditQuery buildInsertAuditQuery(DateTime rollbackDateTime, Long tmId, CurrentVariantRollbackParameters extraParameters) {

    logger.trace("Building the insert tmTextUnitCurrentVariants audit query");

    AuditReader auditReader = AuditReaderFactory.get(entityManager);
    Number revNumberAtDate = auditReader.getRevisionNumberForDate(rollbackDateTime.toDate());

    AuditQuery auditQuery = auditReader.createQuery()
            .forEntitiesAtRevision(TMTextUnitCurrentVariant.class, TMTextUnitCurrentVariant.class.getName(), revNumberAtDate, true)
            .add(AuditEntity.property("tm_id").eq(tmId));

    List<Long> localeIdsToRollback = extraParameters.getLocaleIds();
    if (localeIdsToRollback != null && !localeIdsToRollback.isEmpty()) {
        // Using "in" does not work with relatedId() nor property() so using loop instead
        for (Long localeIdToRollback : localeIdsToRollback) {
            auditQuery.add(AuditEntity.relatedId("locale").eq(localeIdToRollback));
        }
    }

    List<Long> tmTextUnitIdsToRollback = extraParameters.getTmTextUnitIds();
    if (tmTextUnitIdsToRollback != null && !tmTextUnitIdsToRollback.isEmpty()) {
        // Using "in" does not work with relatedId() nor property() so using loop instead
        for (Long tmTextUnitIdToRollback : tmTextUnitIdsToRollback) {
            auditQuery.add(AuditEntity.relatedId("tmTextUnit").eq(tmTextUnitIdToRollback));
        }
    }

    return auditQuery;
}
项目:cibet    文件:EnversActuatorIntegrationTest.java   
@Test
public void persist1() throws Exception {
   if (!JBOSS.equals(APPSERVER)) {
      return;
   }
   log.info("start persist1()");

   AuditedTComplexEntity ce = createAuditedTComplexEntity();
   applEman.persist(ce);
   applEman.getTransaction().commit();
   applEman.getTransaction().begin();

   List<Archive> archList = ArchiveLoader.loadArchivesByPrimaryKeyId(AuditedTComplexEntity.class.getName(),
         String.valueOf(ce.getId()));
   Assert.assertEquals(1, archList.size());
   Resource res0 = archList.get(0).getResource();
   Assert.assertEquals(2, res0.getParameters().size());
   ResourceParameter rp1 = res0.getParameters().iterator().next();
   ResourceParameter rp2 = res0.getParameters().iterator().next();
   Assert.assertTrue("compValue".equals(rp1.getName()) || "owner".equals(rp1.getName()));
   Assert.assertTrue("compValue".equals(rp2.getName()) || "owner".equals(rp2.getName()));

   AuditReader ar = AuditReaderFactory.get(applEman);
   AuditQuery query = ar.createQuery().forRevisionsOfEntity(AuditedTComplexEntity.class, true, true);
   List<AuditedTComplexEntity> resList = query.getResultList();
   Assert.assertEquals(1, resList.size());
   AuditedTComplexEntity ce2 = resList.get(0);
   Assert.assertEquals(2, ce2.getEagerList().size());
}
项目:HibernateDemos    文件:EnversDemo.java   
public List getProjectRevisions() {
    final Session s = openSession();
    final AuditReader ar = AuditReaderFactory.get( s );
    return ar.createQuery()
            .forRevisionsOfEntity(Project.class, false, true)
            .getResultList();
}
项目:HibernateDemos    文件:EnversDemo.java   
public List getProjectRevisions(String property) {
    final Session s = openSession();
    final AuditReader ar = AuditReaderFactory.get( s );
    return ar.createQuery()
            .forRevisionsOfEntity(Project.class, false, true)
            .add(AuditEntity.property(property).hasChanged())
            .getResultList();
}
项目:HibernateDemos    文件:EnversDemo.java   
public List getRevisionProjects(int revisionNumber) {
    final Session s = openSession();
    final AuditReader ar = AuditReaderFactory.get( s );
    return ar.createQuery()
            .forEntitiesAtRevision(Project.class, revisionNumber)
            .getResultList();
}
项目:spring-envers-audit    文件:DefaultRevisionAwareJpaRepository.java   
@Override
@SuppressWarnings("unchecked")
public Revisions<N, T> findRevisions(ID id) {
    Class<T> type = entityInformation.getJavaType();
    AuditReader reader = AuditReaderFactory.get(entityManager);
    List<? extends Number> revisionNumbers = reader.getRevisions(type, id);

    return revisionNumbers.isEmpty() ? new Revisions<N, T>(Collections.EMPTY_LIST) : getEntitiesForRevisions((List<N>) revisionNumbers, id, reader);
}
项目:hibernate-demos    文件:EnversDemo.java   
public List getProjectRevisions() {
    final Session s = openSession();
    final AuditReader ar = AuditReaderFactory.get( s );
    return ar.createQuery()
            .forRevisionsOfEntity(Project.class, false, true)
            .getResultList();
}
项目:hibernate-demos    文件:EnversDemo.java   
public List getProjectRevisions(String property) {
    final Session s = openSession();
    final AuditReader ar = AuditReaderFactory.get( s );
    return ar.createQuery()
            .forRevisionsOfEntity(Project.class, false, true)
            .add(AuditEntity.property(property).hasChanged())
            .getResultList();
}
项目:hibernate-demos    文件:EnversDemo.java   
public List getRevisionProjects(int revisionNumber) {
    final Session s = openSession();
    final AuditReader ar = AuditReaderFactory.get( s );
    return ar.createQuery()
            .forEntitiesAtRevision(Project.class, revisionNumber)
            .getResultList();
}
项目:oregami-server    文件:GenericDAOUUIDImpl.java   
public List<RevisionInfo> findRevisions(String id) {
    List<RevisionInfo> list = new ArrayList<>();
    AuditReader reader = AuditReaderFactory.get(getEntityManager());
    List<Number> revisions = reader.getRevisions(getEntityClass(), id);
    for (Number n : revisions) {
        CustomRevisionEntity revEntity = reader.findRevision(CustomRevisionEntity.class, n);
        list.add(new RevisionInfo(n, revEntity));
    }
    return list;
}
项目:oregami-server    文件:GenericDAOUUIDImpl.java   
public E findRevision(String id, Number revision) {
    AuditReader reader = AuditReaderFactory.get(getEntityManager());
    List<Number> revisions = reader.getRevisions(getEntityClass(), id);
    if (!revisions.contains(revision)) {
        return null;
    }
    E entity = reader.find(getEntityClass(), id, revision);
    return entity;
}
项目:ARCLib    文件:HistoricStore.java   
private AuditReader getAuditReader() {
    return AuditReaderFactory.get(entityManager);
}
项目:WechatTicketSystem    文件:SQLCore.java   
public static AuditReader getAuditReader(Session session) {
    return AuditReaderFactory.get(session);
}
项目:persistence    文件:AbstractRevisionedDaoEnvers.java   
/**
 * @return the auditReader
 */
protected AuditReader getAuditReader() {

  return AuditReaderFactory.get(getEntityManager());
}
项目:ds4p    文件:AuditServiceImpl.java   
public List<HistoryDto> findLegalHistoryByPatient(long patientId) {

        EntityManager em2 = entityManagerFactory.createEntityManager();
        AuditReader reader2 = AuditReaderFactory.get(em2);

        Set<Number> legalList = new HashSet<Number>();

        List<ModifiedEntityTypeEntity> metes = modifiedEntityTypeEntityRepository
                .findAll();
        for (ModifiedEntityTypeEntity m : metes) {
            String entityname = m.getEntityClassName()
                    .substring(m.getEntityClassName().lastIndexOf('.') + 1)
                    .trim();
            if (entityname.equals("PatientLegalRepresentativeAssociation")) {
                long revisionId = m.getRevision().getId();
                Byte bt = m.getRevisionType();

                if (bt != 2) {
                    AuditQuery query = reader2
                            .createQuery()
                            .forEntitiesAtRevision(
                                    PatientLegalRepresentativeAssociation.class,
                                    revisionId);

                    List<PatientLegalRepresentativeAssociation> psList = (List<PatientLegalRepresentativeAssociation>) query.getResultList();
                    for (PatientLegalRepresentativeAssociation ps : psList) {
                        PatientLegalRepresentativeAssociationPk pks=ps.getPatientLegalRepresentativeAssociationPk();
                        Patient pl=pks.getPatient();
                        if(pl!=null)
                        {
                        if (patientId == pl.getId()) {

                            Long LegalId = ps.getId();
                            List<Number> revisionListLegal = reader2
                                    .getRevisions(
                                            PatientLegalRepresentativeAssociation.class,
                                            LegalId);
                            legalList.addAll(revisionListLegal);

                            Long LegalRepId = ps
                                    .getPatientLegalRepresentativeAssociationPk()
                                    .getLegalRepresentative().getId();
                            List<Number> revisionListLegal2 = reader2
                                    .getRevisions(Patient.class, LegalRepId);

                            legalList.addAll(revisionListLegal2);

                        }
                        }
                    }

                }

            }

        }
        Set<Number> removeLegalList = new HashSet<Number>();
        for (Number a : legalList) {
            RevisionInfoEntity patientRevisionEntity = patientRevisionEntityRepository
                    .findOneById(a);
            List<ModifiedEntityTypeEntity> meteLegalLists = modifiedEntityTypeEntityRepository
                    .findAllByRevision(patientRevisionEntity);
            for (ModifiedEntityTypeEntity meteLegal : meteLegalLists) {
                if (meteLegal.getRevisionType() == 0) {
                    String en = new String(meteLegal.getEntityClassName());
                    if (en.substring(en.lastIndexOf('.') + 1).trim()
                            .equals("Patient")) {
                        removeLegalList.add(a);
                    }
                }

            }
        }
        legalList.removeAll(removeLegalList);
        em2.close();
        List<Number> legalList2 = new ArrayList<Number>(legalList);
        List<HistoryDto> historyLegals = (List<HistoryDto>) findLegalHistoryDetails(legalList2);
        return historyLegals;
    }
项目:ankush    文件:ConfigurationManager.java   
/**
 * Gets the configuration.
 * 
 * @param clusterId
 *            the cluster id
 * @return the configuration
 */
public List getConfiguration(Long clusterId) {
    try {
        AuditReader reader = AuditReaderFactory.get(HibernateUtils
                .getEntityManager());
        AuditQuery query = reader.createQuery().forRevisionsOfEntity(
                Configuration.class, false, true);

        // filter results besed on cluster id.
        query.add(AuditEntity.property(
                com.impetus.ankush2.constant.Constant.Keys.CLUSTERID).eq(
                clusterId));
        query.addOrder(AuditEntity.revisionProperty(
                com.impetus.ankush2.constant.Constant.Keys.TIMESTAMP)
                .desc());

        // Getting Result list.
        List list = query.getResultList();

        // Creating List Object.
        List result = new ArrayList();
        for (Object object : list) {
            Object[] obj = (Object[]) object;
            Map map = new HashMap();
            // Mapping Revision Entity.
            DefaultRevisionEntity ri = (DefaultRevisionEntity) obj[1];
            map.putAll(JsonMapperUtil.mapFromObject(obj[0]));
            map.put(com.impetus.ankush2.constant.Constant.Keys.DATE,
                    ri.getRevisionDate());
            map.put(com.impetus.ankush2.constant.Constant.Keys.REVISIONID,
                    ri.getId());
            map.put(com.impetus.ankush2.constant.Constant.Keys.TYPE, obj[2]);
            result.add(map);
        }
        return result;
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }
    return null;

}
项目:hibernate-demos    文件:DataPointServiceImpl.java   
public Map<Number, DefaultRevisionEntity> getRevisions(long id) {
    Session s = hibernateUtil.getSession();
    AuditReader reader = AuditReaderFactory.get(s);
    List<Number> revisionNums = reader.getRevisions( DataPoint.class, id );
    return reader.findRevisions( DefaultRevisionEntity.class, new HashSet<Number>(revisionNums) );
}
项目:hibernate-tutorials    文件:EnversIllustrationTest.java   
public void testBasicUsage() {
    // create a couple of events
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();
    entityManager.persist( new Event( "Our very first event!", new Date() ) );
    entityManager.persist( new Event( "A follow up event", new Date() ) );
    entityManager.getTransaction().commit();
    entityManager.close();

    // now lets pull events from the database and list them
    entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();
       List<Event> result = entityManager.createQuery( "from Event", Event.class ).getResultList();
    for ( Event event : result ) {
        System.out.println( "Event (" + event.getDate() + ") : " + event.getTitle() );
    }
       entityManager.getTransaction().commit();
       entityManager.close();

    // so far the code is the same as we have seen in previous tutorials.  Now lets leverage Envers...

    // first lets create some revisions
    entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();
    Event myEvent = entityManager.find( Event.class, 2L ); // we are using the increment generator, so we know 2 is a valid id
    myEvent.setDate( new Date() );
    myEvent.setTitle( myEvent.getTitle() + " (rescheduled)" );
       entityManager.getTransaction().commit();
       entityManager.close();

    // and then use an AuditReader to look back through history
    entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();
    myEvent = entityManager.find( Event.class, 2L );
    assertEquals( "A follow up event (rescheduled)", myEvent.getTitle() );
    AuditReader reader = AuditReaderFactory.get( entityManager );
    Event firstRevision = reader.find( Event.class, 2L, 1 );
    assertFalse( firstRevision.getTitle().equals( myEvent.getTitle() ) );
    assertFalse( firstRevision.getDate().equals( myEvent.getDate() ) );
    Event secondRevision = reader.find( Event.class, 2L, 2 );
    assertTrue( secondRevision.getTitle().equals( myEvent.getTitle() ) );
    assertTrue( secondRevision.getDate().equals( myEvent.getDate() ) );
    entityManager.getTransaction().commit();
       entityManager.close();
}
项目:oregami-server    文件:RegionRevisionTest.java   
@Test
    public void testRegion() {

        entityManager.getTransaction().begin();

        RegionDao regionDao = injector.getInstance(RegionDao.class);

        Region germany = new Region(Region.GERMANY);
        String id1 = regionDao.save(germany);
        Assert.assertNotNull("ID expected", id1);

        List<Region> all = regionDao.findAll();
        Assert.assertTrue("1 Region expected", all.size()==1);

        Region europe = new Region(Region.EUROPE);
        String id2 = regionDao.save(europe);

        all = regionDao.findAll();
        Assert.assertTrue("2 Regions expected", all.size()==2);

        entityManager.getTransaction().commit();



        entityManager.getTransaction().begin();
        Region loadedGermany = regionDao.findByExactName(Region.GERMANY);
        Assert.assertNotNull(loadedGermany);
        Assert.assertEquals(loadedGermany.getId(), id1);
        Assert.assertEquals(loadedGermany, germany);

        Region loadedEurope = regionDao.findByExactName(Region.EUROPE);
        Assert.assertNotNull(loadedEurope);
        Assert.assertEquals(loadedEurope.getId(), id2);
        Assert.assertEquals(loadedEurope, europe);

        loadedEurope.setDescription("this is changed europe");
        regionDao.save(loadedEurope);

        all = regionDao.findAll();
        Assert.assertTrue("2 Regions expected", all.size()==2);
        entityManager.getTransaction().commit();


        entityManager.getTransaction().begin();
        Region loadedEurope2 = regionDao.findByExactName(Region.EUROPE);
        loadedEurope2.setDescription("this is twice changed europe");
        regionDao.save(loadedEurope);
        entityManager.getTransaction().commit();


        entityManager.getTransaction().begin();
        AuditReader auditReader = AuditReaderFactory.get(entityManager);
        List<Number> revisionNumbers = auditReader.getRevisions(Region.class, loadedEurope.getId());
//      System.out.println(revisionNumbers + " revisions found.");
        for (Number number : revisionNumbers) {
//          System.out.println("RevisionNumber: " + number);
            Region regionWithRevision = auditReader.find(Region.class, loadedEurope.getId(), number);
//          try {
//              System.out.println("Region with revision " + number + "\n"
//                      + new ObjectMapper().writeValueAsString(regionWithRevision));
//          } catch (JsonProcessingException e) {
//              Assert.fail(e.getMessage());
//          }
            Assert.assertNotNull(regionWithRevision);
        }
        entityManager.getTransaction().commit();



        entityManager.getTransaction().begin();
        regionDao.delete(loadedEurope);
        regionDao.delete(loadedGermany);
        List<Region> regionList = regionDao.findAll();
        Assert.assertEquals(0, regionList.size());
        entityManager.getTransaction().commit();



    }
项目:hibernate-envers-demo    文件:CommonDAO.java   
/**
 * Get an {@link AuditReader} from the {@link EntityManager} through the
 * {@link AuditReaderFactory}
 * 
 * @return an {@link AuditReader}
 */
protected AuditReader getAuditReader() {
    return AuditReaderFactory.get(this.entityManager);
}