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

项目:WechatTicketSystem    文件:TicketLog.java   
@Override
protected Object process(HttpServletRequest req, WxSession session) throws Exception {
    int first;
    int limit;
    Date start;
    Date end;
    first = req.getParameter("first") == null ? 0 : Integer.parseInt(req.getParameter("first"));
    limit = req.getParameter("limit") == null ? 20 : Integer.parseInt(req.getParameter("limit"));
    start = req.getParameter("start") == null ? getToday() : dateFormat.parse(req.getParameter("start"));
    end = req.getParameter("end") == null ? getToday() : dateFormat.parse(req.getParameter("end"));
    end = DateUtils.addDays(end, 1);
    try (Session s = SQLCore.sf.openSession()) {
        AuditReader reader = TableTicket.getAuditReader(s);
        return reader.createQuery()
                .forRevisionsOfEntity(Ticket.class, false, true)
                .addOrder(AuditEntity.revisionNumber().desc())
                .add(AuditEntity.revisionProperty("timestamp").between(start.getTime(), end.getTime()))
                .setFirstResult(first)
                .setMaxResults(limit)
                .getResultList();
    }
}
项目: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());
}
项目: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;

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

}
项目: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;
}
项目:WechatTicketSystem    文件:TableTicket.java   
@SuppressWarnings("unchecked")
public static List<Object[]> track(int tid) {
    try (Session s = SQLCore.sf.openSession()) {
        AuditReader reader = getAuditReader(s);
        return reader.createQuery()
                .forRevisionsOfEntity(Ticket.class, false, true)
                .addOrder(AuditEntity.revisionNumber().desc())
                .add(AuditEntity.id().eq(tid))
                .getResultList()
                ;
    }
}
项目: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;
}
项目: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();
}
项目: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-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;
}
项目: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;

}
项目:apple-orm    文件:DataAccessUtility.java   
/**
 * looking for initial revision of entity(for first database insert).
 * 
 * @param auditReader
 *            envers reader implementation
 * @param persistentClass
 *            something that extends {@link AbstractPersistentEntity}
 * @param uniqueIdentifier
 *            primary key of entity
 * @return revision number
 */
public static Number initialRevision(AuditReader auditReader, Class<? extends IBO> persistentClass, long uniqueIdentifier) {
    return (Number) auditReader.createQuery()
            .forRevisionsOfEntity(persistentClass, true, true)
            .add(AuditEntity.id().eq(uniqueIdentifier))
            .add(AuditEntity.revisionType().eq(RevisionType.ADD))
            .addProjection(AuditEntity.revisionNumber().min())
            .getSingleResult();
}
项目:apple-orm    文件:DataAccessUtility.java   
/**
 * looking for latest modify revision of entity(for latest database
 * update/delete).
 * 
 * @param auditReader
 *            envers reader implementation
 * @param persistentClass
 *            something that extends {@link AbstractPersistentEntity}
 * @param uniqueIdentifier
 *            primary key of entity
 * @return revision number
 */
public static Number latestModifyRevision(AuditReader auditReader, Class<? extends IBO> persistentClass, long uniqueIdentifier) {
    return (Number) auditReader
            .createQuery()
            .forRevisionsOfEntity(persistentClass, true, true)
            .add(AuditEntity.id().eq(uniqueIdentifier))
            .add(AuditEntity.revisionType()
            .in(new RevisionType[] { RevisionType.MOD, RevisionType.DEL }))
            .addProjection(AuditEntity.revisionNumber().max())
            .getSingleResult();
}