Java 类org.hibernate.envers.query.AuditQuery 实例源码

项目: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());
}
项目:VersioningWithEnvers    文件:AuditQueryUtils.java   
public static <TTargetType> List<AuditQueryResult<TTargetType>> getAuditQueryResults(AuditQuery query, Class<TTargetType> targetType) {

        List<?> results = query.getResultList();

        if (results == null) {
            return new ArrayList<>();
        }

        // The AuditReader returns a List of Object[], where the indices are:
        //
        // 0 - The queried entity
        // 1 - The revision entity
        // 2 - The Revision Type
        //
        // We cast it into something useful for a safe access:
        return results.stream()
                // Only use Object[] results:
                .filter(x -> x instanceof Object[])
                // Then convert to Object[]:
                .map(x -> (Object[]) x)
                // Transform into the AuditQueryResult:
                .map(x -> AuditQueryResultUtils.getAuditQueryResult(x, targetType))
                // And collect the Results into a List:
                .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());
}
项目:hibernate-envers-demo    文件:CommonDAO.java   
@Transactional
public Object[] getLatestChangeForItemWithID(final Long id,
                                             final Class<?> itemClass) {
    final AuditQuery query = this.getAuditReader()
                                 .createQuery()
                                 .forRevisionsOfEntity(itemClass,
                                                       false,
                                                       true)
                                 .addOrder(AuditEntity.property("modified")
                                                      .desc())
                                 .add(AuditEntity.id().eq(id))
                                 .setMaxResults(1);

    final List<Object[]> resultList = query.getResultList();

    if (resultList != null && resultList.size() > 0) {
        return resultList.get(0);
    }
    return null;
}
项目:hibernate-envers-demo    文件:ProductDAO.java   
/**
 * Retrieve the previous state of a given {@link ProductEntity} which was
 * modified earlier than the given modified date.
 * 
 * @param prodId
 *            the id of the {@link ProductEntity}
 * @param revNumber
 *            the revision number when the productDetails was modified
 * @return a {@link ProductEntity} object
 */
@Transactional
public ProductEntity getPreviousStateForProduct(final Long prodId,
                                                final int revNumber) {
    /**
     * Get only the most recent {@link ProductEntity} information from the
     * audit tables where the wasChecked property is true and the
     * modifiedDate is less than the one given as parameter for the given
     * product details object
     */
    final AuditQuery query = this.getAuditReader()
                                 .createQuery()
                                 .forRevisionsOfEntity(ProductEntity.class,
                                                       true,
                                                       true)
                                 .addOrder(AuditEntity.property("modified")
                                                      .desc())
                                 .add(AuditEntity.id().eq(prodId))
                                 .add(AuditEntity.property("wasChecked")
                                                 .eq(Boolean.TRUE))
                                 .add(AuditEntity.revisionNumber()
                                                 .lt(Integer.valueOf(revNumber)))
                                 .setMaxResults(1);

    final List<ProductEntity> resultList = query.getResultList();

    if (resultList != null && resultList.size() > 0) {
        return resultList.get(0);
    }

    return null;

}
项目:mojito    文件:CurrentVariantRollbackService.java   
/**
 * Deletes the {@link com.box.l10n.mojito.entity.TMTextUnitCurrentVariant}s based on the given parameters.
 * These variants will be recreated later in the same state as 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
 */
protected void addCurrentVariantsAsOfRollbackDate(DateTime rollbackDateTime, Long tmId, CurrentVariantRollbackParameters extraParameters) {

    logger.debug("Adding back TMTextUnitCurrentVariants as of {}", rollbackDateTime);

    AuditQuery auditQuery = buildInsertAuditQuery(rollbackDateTime, tmId, extraParameters);
    List<TMTextUnitCurrentVariant> tmTextUnitCurrentVariantsToAdd = (List<TMTextUnitCurrentVariant>) auditQuery.getResultList();
    tmTextUnitCurrentVariantRepository.save(tmTextUnitCurrentVariantsToAdd);
}
项目: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());
}
项目:hibernate-envers-demo    文件:ProductDetailsDAO.java   
/**
 * Retrieve the previous state of a given {@link ProductDetailsEntity} which
 * was modified earlier than the given modified date.
 * 
 * @param prodDetailsId
 *            the id of the {@link ProductDetailsEntity}
 * @param modifiedDate
 *            the date when the productDetails was modified
 * @return a {@link ProductDetailsEntity} object
 */
@Transactional
public ProductDetailsEntity
        getPreviousStateForProductDetails(final Long prodDetailsId,
                                          final int revNumber) {
    /**
     * Get only the most recent {@link ProductDetailsEntity} information
     * from the audit tables where the wasChecked property is true and the
     * modifiedDate is less than the one given as parameter for the given
     * product details object
     */
    final AuditQuery query = this.getAuditReader()
                                 .createQuery()
                                 .forRevisionsOfEntity(ProductDetailsEntity.class,
                                                       true,
                                                       true)
                                 .addOrder(AuditEntity.property("modified")
                                                      .desc())
                                 .add(AuditEntity.id().eq(prodDetailsId))
                                 .add(AuditEntity.property("wasChecked")
                                                 .eq(Boolean.TRUE))
                                 .add(AuditEntity.revisionNumber()
                                                 .lt(Integer.valueOf(revNumber)))
                                 .setMaxResults(1);

    final List<ProductDetailsEntity> resultList = query.getResultList();

    if (resultList != null && resultList.size() > 0) {
        return resultList.get(0);
    }

    return null;
}
项目:hibernate-envers-demo    文件:ProductDAO.java   
/**
 * Get all products that need to be shown to the checker for approval.
 * 
 * @return a list of Object[]. Each element will be an Object[3] array with
 *         the following items: Object[0] - the {@link ProductEntity} at a
 *         revision ( greater or equal than the one given as parameter)
 *         Object[1] a {@link DefaultRevisionEntity} Object[2] a
 *         {@link RevisionType} object containing information about the
 *         revision
 */
@Transactional
public List<Object[]> getAllProductsWaitingForApproval() {
    /**
     * Get all distinct {@link ProductEntity} objects where the wasChecked
     * property is false order by modified descending
     */
    final AuditQuery query = this.getAuditReader()
                                 .createQuery()
                                 .forRevisionsOfEntity(ProductEntity.class,
                                                       false,
                                                       true)
                                 .addOrder(AuditEntity.property("modified")
                                                      .desc())
                                 .add(AuditEntity.revisionNumber()
                                                 .maximize()
                                                 .computeAggregationInInstanceContext())
                                 .add(AuditEntity.property("wasChecked")
                                                 .eq(Boolean.FALSE))
                                 .add(AuditEntity.revisionType()
                                                 .ne(RevisionType.DEL));

    final List<Object[]> resultList = query.getResultList();

    final List<Object[]> result = new ArrayList<>();

    /**
     * for each "changed" object found in the db we need to check if there
     * is a newer revision of it in which the {@link ProductEntity} was
     * approved (wasChecked = true) because we do not need to retrieve
     * already checked objects to the checker.
     */
    for (final Object[] change : resultList) {
        final ProductEntity pe = (ProductEntity) change[0];
        final AuditQuery queryForWasCheckedTrue = this.getAuditReader()
                                                      .createQuery()
                                                      .forRevisionsOfEntity(ProductEntity.class,
                                                                            false,
                                                                            true)
                                                      .addOrder(AuditEntity.property("modified")
                                                                           .desc())
                                                      .add(AuditEntity.id()
                                                                      .eq(pe.getId()))
                                                      .add(AuditEntity.property("wasChecked")
                                                                      .eq(Boolean.TRUE));

        if (pe.getModified() != null) {
            queryForWasCheckedTrue.add(AuditEntity.property("modified")
                                                  .gt(pe.getModified()));
        }

        try {
            final Object[] trueWasChecked = (Object[]) queryForWasCheckedTrue.getSingleResult();
        }
        catch (final NoResultException ex) {
            // there is no newer revision where the current product has
            // wasChecked property == true
            result.add(change);
        }

    }

    return result;
}
项目: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;

}