Example usage for org.hibernate.criterion Projections max

List of usage examples for org.hibernate.criterion Projections max

Introduction

In this page you can find the example usage for org.hibernate.criterion Projections max.

Prototype

public static AggregateProjection max(String propertyName) 

Source Link

Document

A property maximum value projection

Usage

From source file:org.balisunrise.daa.hibernate.HQuery.java

License:Open Source License

@Override
public <V> V max(String property) {
    return (V) hcrit.setProjection(Projections.max(property)).uniqueResult();
}

From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java

License:Open Source License

/**
 * Retrieves an iterator over the compliance snapshots on the target date.
 *
 * @param targetDate//  w  ww .  ja va 2  s .c om
 *  The date for which to retrieve compliance snapshots. If null, the current date will be used
 *  instead.
 *
 * @param consumerUuids
 *  A list of consumer UUIDs to use to filter the results. If provided, only compliances for
 *  consumers in the list will be retrieved.
 *
 * @param ownerFilters
 *  A list of owners to use to filter the results. If provided, only compliances for consumers
 *  belonging to the specified owners (orgs) will be retrieved.
 *
 * @param statusFilters
 *  A list of statuses to use to filter the results. If provided, only compliances with a status
 *  matching the list will be retrieved.
 *
 * @param productNameFilters
 *  A list of product names to use to filter compliances. If provided, only compliances for
 *  consumers having installed the specified products will be retrieved.
 *
 * @param subscriptionSkuFilters
 *  A list of subscription skus to use to filter compliances. If provided, only compliances for
 *  the specified subscription skus will be retrieved.
 *
 * @param subscriptionNameFilters
 *  A list of subscription names to use to filter compliances. If provided, only compliances for
 *  the specified subscription names will be retrieved.
 *
 * @param attributeFilters
 *  A map of entitlement attributes to use to filter compliances. If provided, only compliances
 *  for entitlements having the specified values for the given attributes will be retrieved.
 *
 * @param pageRequest
 *  A PageRequest instance containing paging information from the request. If null, no paging
 *  will be performed.
 *
 * @return
 *  A Page instance containing an iterator over the compliance snapshots for the target date and
 *  the paging information for the query.
 */
@SuppressWarnings("checkstyle:indentation")
public Page<Iterator<Compliance>> getSnapshotIterator(Date targetDate, List<String> consumerUuids,
        List<String> ownerFilters, List<String> statusFilters, List<String> productNameFilters,
        List<String> subscriptionSkuFilters, List<String> subscriptionNameFilters,
        Map<String, String> attributeFilters, PageRequest pageRequest) {

    Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>();
    page.setPageRequest(pageRequest);

    DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class);
    subquery.createAlias("consumer", "c");
    subquery.createAlias("c.consumerState", "state");

    // https://hibernate.atlassian.net/browse/HHH-2776
    if (consumerUuids != null && !consumerUuids.isEmpty()) {
        subquery.add(Restrictions.in("c.uuid", consumerUuids));
    }

    Date toCheck = targetDate == null ? new Date() : targetDate;
    subquery.add(
            Restrictions.or(Restrictions.isNull("state.deleted"), Restrictions.gt("state.deleted", toCheck)));
    subquery.add(Restrictions.le("state.created", toCheck));

    if (ownerFilters != null && !ownerFilters.isEmpty()) {
        subquery.createAlias("c.owner", "o");
        subquery.add(Restrictions.in("o.key", ownerFilters));
    }

    subquery.add(Restrictions.le("date", toCheck));

    subquery.setProjection(
            Projections.projectionList().add(Projections.max("date")).add(Projections.groupProperty("c.uuid")));

    Session session = this.currentSession();
    Criteria query = session.createCriteria(Compliance.class, "comp").createAlias("comp.consumer", "cs")
            .add(Subqueries.propertiesIn(new String[] { "comp.date", "cs.uuid" }, subquery))
            .setCacheMode(CacheMode.IGNORE).setReadOnly(true);

    if ((statusFilters != null && !statusFilters.isEmpty())
            || (attributeFilters != null && attributeFilters.containsKey("management_enabled"))
            || (productNameFilters != null && !productNameFilters.isEmpty())) {

        query.createAlias("comp.status", "stat");

        if (statusFilters != null && !statusFilters.isEmpty()) {
            query.add(Restrictions.in("stat.status", statusFilters));
        }

        if (attributeFilters != null && attributeFilters.containsKey("management_enabled")) {
            boolean managementEnabledFilter = PropertyConverter
                    .toBoolean(attributeFilters.get("management_enabled"));
            query.add(Restrictions.eq("stat.managementEnabled", managementEnabledFilter));
        }

        if (productNameFilters != null && !productNameFilters.isEmpty()) {
            query.createAlias("stat.compliantProducts", "cprod", JoinType.LEFT_OUTER_JOIN)
                    .createAlias("stat.partiallyCompliantProducts", "pcprod", JoinType.LEFT_OUTER_JOIN)
                    .createAlias("stat.nonCompliantProducts", "ncprod", JoinType.LEFT_OUTER_JOIN);

            DetachedCriteria prodQuery = DetachedCriteria.forClass(Compliance.class, "comp2");
            prodQuery.createAlias("comp2.consumer", "cons2");
            prodQuery.createAlias("cons2.installedProducts", "installed");
            prodQuery.add(Restrictions.and(Restrictions.in("installed.productName", productNameFilters),
                    Restrictions.eqProperty("comp2.id", "comp.id")));
            prodQuery.setProjection(Projections.property("installed.productId"));

            query.add(Restrictions.or(Property.forName("cprod.productId").in(prodQuery),
                    Property.forName("pcprod.productId").in(prodQuery),
                    Property.forName("ncprod.productId").in(prodQuery)));
        }
    }

    // Add subscription filters, if necessary
    if ((subscriptionSkuFilters != null && !subscriptionSkuFilters.isEmpty())
            || (subscriptionNameFilters != null && !subscriptionNameFilters.isEmpty())) {

        // Impl note: We have to be very careful with alias names, as Hibernate has a tendancy
        // to errorneously truncate "long" ones. Actual property/field names are safe, though.
        query.createAlias("comp.entitlements", "entsnap");

        if (subscriptionSkuFilters != null && !subscriptionSkuFilters.isEmpty()) {
            query.add(Restrictions.in("entsnap.productId", subscriptionSkuFilters));
        }

        if (subscriptionNameFilters != null && !subscriptionNameFilters.isEmpty()) {
            query.add(Restrictions.in("entsnap.productName", subscriptionNameFilters));
        }
    }

    if (pageRequest != null && pageRequest.isPaging()) {
        page.setMaxRecords(this.getRowCount(query));

        query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage());
        query.setMaxResults(pageRequest.getPerPage());

        if (pageRequest.getSortBy() != null) {
            query.addOrder(
                    pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy())
                            : Order.desc(pageRequest.getSortBy()));
        }
    }

    page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0));

    return page;
}

From source file:org.candlepin.gutterball.curator.ComplianceSnapshotCurator.java

License:Open Source License

/**
 * Retrieves an iterator over the compliance snapshots for the specified consumer.
 *
 * @param consumerUUID/*from  www.  ja v a 2s .c om*/
 *  The UUID for the consumer for which to retrieve compliance snapshots.
 *
 * @param startDate
 *  The start date to use to filter snapshots retrieved. If specified, only snapshots occurring
 *  after the start date, and the snapshot immediately preceding it, will be retrieved.
 *
 * @param endDate
 *  The end date to use to filter snapshots retrieved. If specified, only snapshots occurring
 *  before the end date will be retrieved.
 *
 * @param pageRequest
 *  A PageRequest instance containing paging information from the request. If null, no paging
 *  will be performed.
 *
 * @return
 *  A Page instance containing an iterator over the snapshots for the specified consumer, and
 *  the paging information for the query.
 */
@SuppressWarnings("checkstyle:indentation")
public Page<Iterator<Compliance>> getSnapshotIteratorForConsumer(String consumerUUID, Date startDate,
        Date endDate, PageRequest pageRequest) {

    Page<Iterator<Compliance>> page = new Page<Iterator<Compliance>>();
    page.setPageRequest(pageRequest);

    Session session = this.currentSession();
    Criteria query = session.createCriteria(Compliance.class, "comp1");
    query.createAlias("comp1.consumer", "cons1");

    query.add(Restrictions.eq("cons1.uuid", consumerUUID));

    if (startDate != null) {
        DetachedCriteria subquery = DetachedCriteria.forClass(Compliance.class, "comp2");
        subquery.createAlias("comp2.consumer", "cons2");
        subquery.createAlias("cons2.consumerState", "state2");

        subquery.add(Restrictions.or(Restrictions.isNull("state2.deleted"),
                Restrictions.gt("state2.deleted", startDate)));

        subquery.add(Restrictions.lt("state2.created", startDate));
        subquery.add(Restrictions.eqProperty("cons2.uuid", "cons1.uuid"));
        subquery.add(Restrictions.lt("comp2.date", startDate));

        subquery.setProjection(Projections.projectionList().add(Projections.max("comp2.date")));

        query.add(Restrictions.disjunction().add(Restrictions.ge("comp1.date", startDate))
                .add(Subqueries.propertyEq("comp1.date", subquery)));
    }

    if (endDate != null) {
        query.add(Restrictions.le("comp1.date", endDate));
    }

    query.setCacheMode(CacheMode.IGNORE);
    query.setReadOnly(true);

    if (pageRequest != null && pageRequest.isPaging()) {
        page.setMaxRecords(this.getRowCount(query));

        query.setFirstResult((pageRequest.getPage() - 1) * pageRequest.getPerPage());
        query.setMaxResults(pageRequest.getPerPage());

        if (pageRequest.getSortBy() != null) {
            query.addOrder(
                    pageRequest.getOrder() == PageRequest.Order.ASCENDING ? Order.asc(pageRequest.getSortBy())
                            : Order.desc(pageRequest.getSortBy()));
        }
    }

    page.setPageData(new AutoEvictingColumnarResultsIterator<Compliance>(session,
            query.scroll(ScrollMode.FORWARD_ONLY), 0));

    return page;
}

From source file:org.candlepin.model.RulesCurator.java

License:Open Source License

private Date getUpdatedFromDB() {
    return (Date) this.currentSession().createCriteria(Rules.class)
            .setProjection(Projections.projectionList().add(Projections.max("updated"))).uniqueResult();
}

From source file:org.cast.cwm.service.EventService.java

License:Open Source License

@Override
public Date getLastEventTime(LoginSession ls) {
    Session session = Databinder.getHibernateSession();
    Criteria criteria = session.createCriteria(Event.class);
    criteria.add(Restrictions.eq("loginSession", ls));
    criteria.setProjection(Projections.max("insertTime"));
    return (Date) criteria.uniqueResult();
}

From source file:org.cms.dao.FajlDao.java

@Transactional
public int vratiID() {
    Session session = this.sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Fajl.class).setProjection(Projections.max("fajlID"));
    try {/*from www  . j  av  a 2s  . c om*/
        int id = (int) criteria.uniqueResult();
        return id;
    } catch (Exception e) {
        return 0;
    }
}

From source file:org.cms.dao.KategorijaDao.java

@Transactional
public int vratiID() {
    Session session = this.sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Kategorija.class).setProjection(Projections.max("kategorijaID"));
    try {/*from ww  w  . ja va  2s  . c om*/
        int id = (int) criteria.uniqueResult();
        return id;
    } catch (Exception e) {
        return 0;
    }
}

From source file:org.cms.dao.KorisnikDao.java

@Transactional
public int vratiID() {
    Session session = this.sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Korisnik.class).setProjection(Projections.max("korisnikID"));
    int id = 0;// www  . j  a  va 2 s .c o m
    try {
        return (int) criteria.uniqueResult();
    } catch (Exception e) {
        return id;
    }

}

From source file:org.cms.dao.VestDao.java

@Transactional
public int vratiID() {
    Session session = this.sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Vest.class).setProjection(Projections.max("vestID"));
    int id = 0;//w w w .j  a va 2 s.c o m
    try {
        return (int) criteria.uniqueResult();
    } catch (Exception e) {
        return id;
    }
}

From source file:org.encuestame.persistence.dao.imp.HashTagDao.java

License:Apache License

public Date getMaxHashTagRankingDate() {
    DetachedCriteria criteria = DetachedCriteria.forClass(HashTagRanking.class);
    criteria.setProjection(Projections.max("rankingDate"));
    @SuppressWarnings("unchecked")
    List<HashTagRanking> results = (List<HashTagRanking>) getHibernateTemplate().findByCriteria(criteria);
    return (Date) (results.get(0) == null ? new Date() : results.get(0));
}