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:com.dalamar.model.LateTrainDaoImpl.java

public LateTrainDao max(String field) {
    Projection max = Projections.max(field);
    projections.add(max);
    return this;
}

From source file:com.eucalyptus.cloudwatch.common.internal.domain.metricdata.MetricManager.java

License:Open Source License

public static List<Collection<MetricStatistics>> getManyMetricStatistics(
        List<GetMetricStatisticsParams> getMetricStatisticsParamses) {
    if (getMetricStatisticsParamses == null)
        throw new IllegalArgumentException("getMetricStatisticsParamses can not be null");
    Date now = new Date();
    Map<GetMetricStatisticsParams, Collection<MetricStatistics>> resultMap = Maps.newHashMap();
    Multimap<Class, GetMetricStatisticsParams> hashGroupMap = LinkedListMultimap.create();
    for (GetMetricStatisticsParams getMetricStatisticsParams : getMetricStatisticsParamses) {
        if (getMetricStatisticsParams == null)
            throw new IllegalArgumentException("getMetricStatisticsParams can not be null");
        getMetricStatisticsParams.validate(now);
        Class metricEntityClass = MetricEntityFactory.getClassForEntitiesGet(
                getMetricStatisticsParams.getMetricType(), getMetricStatisticsParams.getDimensionHash());
        hashGroupMap.put(metricEntityClass, getMetricStatisticsParams);
    }/*from ww w.j  av a2  s  .  c o m*/
    for (Class metricEntityClass : hashGroupMap.keySet()) {
        try (final TransactionResource db = Entities.transactionFor(metricEntityClass)) {
            // set some global criteria to start (for narrowing?)
            Date minDate = null;
            Date maxDate = null;
            Junction disjunction = Restrictions.disjunction();
            Map<GetMetricStatisticsParams, TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>> multiAggregationMap = Maps
                    .newHashMap();
            for (GetMetricStatisticsParams getMetricStatisticsParams : hashGroupMap.get(metricEntityClass)) {
                multiAggregationMap.put(getMetricStatisticsParams,
                        new TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>(
                                GetMetricStatisticsAggregationKey.COMPARATOR_WITH_NULLS.INSTANCE));
                Junction conjunction = Restrictions.conjunction();
                conjunction = conjunction
                        .add(Restrictions.lt("timestamp", getMetricStatisticsParams.getEndTime()));
                conjunction = conjunction
                        .add(Restrictions.ge("timestamp", getMetricStatisticsParams.getStartTime()));
                conjunction = conjunction
                        .add(Restrictions.eq("accountId", getMetricStatisticsParams.getAccountId()));
                conjunction = conjunction
                        .add(Restrictions.eq("metricName", getMetricStatisticsParams.getMetricName()));
                conjunction = conjunction
                        .add(Restrictions.eq("namespace", getMetricStatisticsParams.getNamespace()));
                conjunction = conjunction.add(
                        Restrictions.eq("dimensionHash", hash(getMetricStatisticsParams.getDimensionMap())));
                if (getMetricStatisticsParams.getUnits() != null) {
                    conjunction = conjunction
                            .add(Restrictions.eq("units", getMetricStatisticsParams.getUnits()));
                }
                disjunction = disjunction.add(conjunction);
                if (minDate == null || getMetricStatisticsParams.getStartTime().before(minDate)) {
                    minDate = getMetricStatisticsParams.getStartTime();
                }
                if (maxDate == null || getMetricStatisticsParams.getEndTime().after(maxDate)) {
                    maxDate = getMetricStatisticsParams.getEndTime();
                }
            }
            Criteria criteria = Entities.createCriteria(metricEntityClass);
            criteria = criteria.add(Restrictions.lt("timestamp", maxDate));
            criteria = criteria.add(Restrictions.ge("timestamp", minDate));
            criteria = criteria.add(disjunction);

            ProjectionList projectionList = Projections.projectionList();
            projectionList.add(Projections.max("sampleMax"));
            projectionList.add(Projections.min("sampleMin"));
            projectionList.add(Projections.sum("sampleSize"));
            projectionList.add(Projections.sum("sampleSum"));
            projectionList.add(Projections.groupProperty("units"));
            projectionList.add(Projections.groupProperty("timestamp"));
            projectionList.add(Projections.groupProperty("accountId"));
            projectionList.add(Projections.groupProperty("metricName"));
            projectionList.add(Projections.groupProperty("metricType"));
            projectionList.add(Projections.groupProperty("namespace"));
            projectionList.add(Projections.groupProperty("dimensionHash"));
            criteria.setProjection(projectionList);
            criteria.addOrder(Order.asc("timestamp"));

            ScrollableResults results = criteria.setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY);
            while (results.next()) {
                MetricEntity me = getMetricEntity(results);
                for (GetMetricStatisticsParams getMetricStatisticsParams : hashGroupMap
                        .get(metricEntityClass)) {
                    if (metricDataMatches(getMetricStatisticsParams, me)) {
                        Map<GetMetricStatisticsAggregationKey, MetricStatistics> aggregationMap = multiAggregationMap
                                .get(getMetricStatisticsParams);
                        GetMetricStatisticsAggregationKey key = new GetMetricStatisticsAggregationKey(me,
                                getMetricStatisticsParams.getStartTime(), getMetricStatisticsParams.getPeriod(),
                                getMetricStatisticsParams.getDimensionHash());
                        MetricStatistics item = new MetricStatistics(me,
                                getMetricStatisticsParams.getStartTime(), getMetricStatisticsParams.getPeriod(),
                                getMetricStatisticsParams.getDimensions());
                        if (!aggregationMap.containsKey(key)) {
                            aggregationMap.put(key, item);
                        } else {
                            MetricStatistics totalSoFar = aggregationMap.get(key);
                            totalSoFar.setSampleMax(Math.max(item.getSampleMax(), totalSoFar.getSampleMax()));
                            totalSoFar.setSampleMin(Math.min(item.getSampleMin(), totalSoFar.getSampleMin()));
                            totalSoFar.setSampleSize(totalSoFar.getSampleSize() + item.getSampleSize());
                            totalSoFar.setSampleSum(totalSoFar.getSampleSum() + item.getSampleSum());
                        }
                    }
                }
            }
            for (GetMetricStatisticsParams getMetricStatisticsParams : multiAggregationMap.keySet()) {
                resultMap.put(getMetricStatisticsParams,
                        multiAggregationMap.get(getMetricStatisticsParams).values());
            }
        }
    }
    List<Collection<MetricStatistics>> resultList = Lists.newArrayList();
    for (GetMetricStatisticsParams getMetricStatisticsParams : getMetricStatisticsParamses) {
        if (resultMap.get(getMetricStatisticsParams) == null) {
            resultList.add(new ArrayList<MetricStatistics>());
        } else {
            resultList.add(resultMap.get(getMetricStatisticsParams));
        }
    }
    return resultList;
}

From source file:com.eucalyptus.cloudwatch.common.internal.domain.metricdata.MetricManager.java

License:Open Source License

public static Collection<MetricStatistics> getMetricStatistics(
        GetMetricStatisticsParams getMetricStatisticsParams) {
    if (getMetricStatisticsParams == null)
        throw new IllegalArgumentException("getMetricStatisticsParams can not be null");
    Date now = new Date();
    getMetricStatisticsParams.validate(now);
    Class metricEntityClass = MetricEntityFactory.getClassForEntitiesGet(
            getMetricStatisticsParams.getMetricType(), getMetricStatisticsParams.getDimensionHash());
    Map<GetMetricStatisticsAggregationKey, MetricStatistics> aggregationMap = new TreeMap<GetMetricStatisticsAggregationKey, MetricStatistics>(
            GetMetricStatisticsAggregationKey.COMPARATOR_WITH_NULLS.INSTANCE);
    try (final TransactionResource db = Entities.transactionFor(metricEntityClass)) {
        Criteria criteria = Entities.createCriteria(metricEntityClass);
        criteria = criteria.add(Restrictions.eq("accountId", getMetricStatisticsParams.getAccountId()));
        criteria = criteria.add(Restrictions.eq("metricName", getMetricStatisticsParams.getMetricName()));
        criteria = criteria.add(Restrictions.eq("namespace", getMetricStatisticsParams.getNamespace()));
        criteria = criteria.add(Restrictions.lt("timestamp", getMetricStatisticsParams.getEndTime()));
        criteria = criteria.add(Restrictions.ge("timestamp", getMetricStatisticsParams.getStartTime()));
        criteria = criteria.add(Restrictions.eq("dimensionHash", getMetricStatisticsParams.getDimensionHash()));
        if (getMetricStatisticsParams.getUnits() != null) {
            criteria = criteria.add(Restrictions.eq("units", getMetricStatisticsParams.getUnits()));
        }/*from w  w w .  ja  va  2s.  c  o  m*/

        ProjectionList projectionList = Projections.projectionList();
        projectionList.add(Projections.max("sampleMax"));
        projectionList.add(Projections.min("sampleMin"));
        projectionList.add(Projections.sum("sampleSize"));
        projectionList.add(Projections.sum("sampleSum"));
        projectionList.add(Projections.groupProperty("units"));
        projectionList.add(Projections.groupProperty("timestamp"));
        criteria.setProjection(projectionList);
        criteria.addOrder(Order.asc("timestamp"));
        ScrollableResults results = criteria.setCacheMode(CacheMode.IGNORE).scroll(ScrollMode.FORWARD_ONLY);
        while (results.next()) {
            MetricEntity me = getMetricEntity(getMetricStatisticsParams.getAccountId(),
                    getMetricStatisticsParams.getMetricName(), getMetricStatisticsParams.getNamespace(),
                    getMetricStatisticsParams.getMetricType(), getMetricStatisticsParams.getDimensionHash(),
                    results);
            GetMetricStatisticsAggregationKey key = new GetMetricStatisticsAggregationKey(me,
                    getMetricStatisticsParams.getStartTime(), getMetricStatisticsParams.getPeriod(),
                    getMetricStatisticsParams.getDimensionHash());
            MetricStatistics item = new MetricStatistics(me, getMetricStatisticsParams.getStartTime(),
                    getMetricStatisticsParams.getPeriod(), getMetricStatisticsParams.getDimensions());
            if (!aggregationMap.containsKey(key)) {
                aggregationMap.put(key, item);
            } else {
                MetricStatistics totalSoFar = aggregationMap.get(key);
                totalSoFar.setSampleMax(Math.max(item.getSampleMax(), totalSoFar.getSampleMax()));
                totalSoFar.setSampleMin(Math.min(item.getSampleMin(), totalSoFar.getSampleMin()));
                totalSoFar.setSampleSize(totalSoFar.getSampleSize() + item.getSampleSize());
                totalSoFar.setSampleSum(totalSoFar.getSampleSum() + item.getSampleSum());
            }
        }
    }
    return Lists.newArrayList(aggregationMap.values());
}

From source file:com.floreantpos.model.dao.UserDAO.java

License:Open Source License

public Integer findUserWithMaxId() {
    Session session = null;//from  ww w  .j a v  a  2s.  c o m

    try {
        session = getSession();
        Criteria criteria = session.createCriteria(getReferenceClass());
        criteria.setProjection(Projections.max(User.PROP_USER_ID));

        List list = criteria.list();
        if (list != null && list.size() > 0) {
            return (Integer) list.get(0);
        }

        return null;
    } finally {
        if (session != null) {
            closeSession(session);
        }
    }
}

From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java

License:Apache License

/**
 * Adds a new projection to the current projectionList stack.
 * Mandatory Attributes:<ul>/*www  . j  a va  2 s .co  m*/
 * <li><b>name</b>: The field to create a projection on.</li>
 * <li><b>type</b>: The projection type.</li>
 * <li><b>alias</b>: The name applied to the projection returned field.</li>
 * </ul>
 * @param attrs The attributes of the processed node.
 * @throws SAXException
 * TODO: Implement checks for mandatory attributes.
 */
public void addProjection(Attributes attrs) throws SAXException {
    ProjectionList projectionList = projectionStack.peek();
    if (projectionList == null) {
        throw new SAXException(
                "Attempted to add Projection and no ProjectionList Exists On The Stack. (Projection must be embedded inside a Projections)");
    }
    String type = attrs.getValue("type");
    String name = attrs.getValue("name");
    String alias = attrs.getValue("alias");
    if ("avg".equalsIgnoreCase(type)) {
        projectionList.add(Projections.avg(name), alias);
    } else if ("count".equalsIgnoreCase(type)) {
        projectionList.add(Projections.count(name), alias);
    } else if ("countDistinct".equalsIgnoreCase(type)) {
        projectionList.add(Projections.countDistinct(name), alias);
    } else if ("groupProperty".equalsIgnoreCase(type)) {
        projectionList.add(Projections.groupProperty(name), alias);
    } else if ("max".equalsIgnoreCase(type)) {
        projectionList.add(Projections.max(name), alias);
    } else if ("min".equalsIgnoreCase(type)) {
        projectionList.add(Projections.min(name), alias);
    } else if ("sum".equalsIgnoreCase(type)) {
        projectionList.add(Projections.sum(name), alias);
    } else if ("rowCount".equalsIgnoreCase(type)) {
        projectionList.add(Projections.rowCount(), alias);
    }

}

From source file:com.hibernate.dao.AsesinosDAO.java

@Override
public List<Asesinos> getAsesinosListByProjection() {

    List<Asesinos> peliculas1 = session.createCriteria(Asesinos.class)//.list();
            .setProjection(Projections.projectionList().add(Projections.rowCount())
                    .add(Projections.avg("personasasesinadas")).add(Projections.max("personasasesinadas"))
                    .add(Projections.groupProperty("formato").as("ao"))

            ).list();// ww  w  .j  av  a2 s  .  c  om

    return peliculas1;
}

From source file:com.hms.util.IdGenerator.java

public String getPatientId() {
    Session session = new MySession().getSession();
    session.beginTransaction();//from   w ww . ja  v a  2 s . c o m
    Criteria criteria = session.createCriteria(Patient.class).setProjection(Projections.max("id"));

    Long max = (Long) criteria.uniqueResult();

    session.getTransaction().commit();
    session.close();

    return "BU-" + (max + 1);
}

From source file:com.hms.util.IdGenerator.java

public String getReceiptNumber() {
    Session session = new MySession().getSession();
    session.beginTransaction();/* w w  w. ja va  2 s.c  om*/

    Long max;

    Criteria criteria = session.createCriteria(LedgerAC.class).setProjection(Projections.max("id"));
    max = (Long) criteria.uniqueResult();
    //System.out.println(max);

    if (max == null) {
        max = 0L;
    }

    session.getTransaction().commit();
    session.close();

    DecimalFormat df = new DecimalFormat("0000");
    return df.format(max + 1);

}

From source file:com.hypersocket.repository.AbstractRepositoryImpl.java

License:Open Source License

@Override
@Transactional(readOnly = true)//w ww  . ja v a 2s .c  o m
public Long max(String column, Class<?> clz, CriteriaConfiguration... configs) {

    Criteria criteria = createCriteria(clz);

    for (CriteriaConfiguration c : configs) {
        c.configure(criteria);
    }

    criteria.setProjection(Projections.projectionList().add(Projections.max(column)));

    Integer result = (Integer) criteria.uniqueResult();
    if (result == null) {
        return 0L;
    } else {
        return new Long(result);
    }
}

From source file:com.inkubator.hrm.dao.impl.EmpCareerHistoryDaoImpl.java

@Override
public List<EmpCareerHistory> getByParamReport(ReportEmpMutationParameter searchParameter, int firstResult,
        int maxResults, Order order) {
    Criteria criteria = getCurrentSession().createCriteria(getEntityClass());
    criteria.createAlias("bioData", "bioData", JoinType.INNER_JOIN);
    criteria.createAlias("jabatan", "jabatan", JoinType.INNER_JOIN);
    doSearchEmpRotasiByParamReport(searchParameter, criteria);

    DetachedCriteria maxTglPengangkatanQuery = DetachedCriteria.forClass(getEntityClass());
    ProjectionList proj = Projections.projectionList();
    proj.add(Projections.max("tglPenganngkatan"));
    proj.add(Projections.groupProperty("nik"));
    maxTglPengangkatanQuery.setProjection(proj);

    criteria.add(Subqueries.propertiesIn(new String[] { "tglPenganngkatan", "nik" }, maxTglPengangkatanQuery));
    criteria.addOrder(order);/*from   w w w .j a  va  2  s . com*/
    criteria.setFirstResult(firstResult);
    criteria.setMaxResults(maxResults);

    List<EmpCareerHistory> listEmpCareerHistorys = criteria.list();

    //Set Jabatan Lama/sebelumnya dari masing - masing record
    for (EmpCareerHistory ech : listEmpCareerHistorys) {
        Criteria criteriaOldPosition = getCurrentSession().createCriteria(getEntityClass());
        criteriaOldPosition.setFetchMode("jabatan", FetchMode.JOIN);
        criteriaOldPosition.add(Restrictions.eq("nik", ech.getNik()));
        criteriaOldPosition.add(Restrictions.lt("tglPenganngkatan", ech.getTglPenganngkatan()));
        criteriaOldPosition.addOrder(Order.desc("tglPenganngkatan"));
        criteriaOldPosition.setMaxResults(1);
        EmpCareerHistory prevPosition = (EmpCareerHistory) criteriaOldPosition.uniqueResult();

        //jika sebelumnya dia sudah pernah menjabat di posisi lain maka set oldJabatan dengan posisi tersebut
        if (null != prevPosition) {
            ech.setJabatanOldCode(prevPosition.getJabatan().getCode());
            ech.setJabatanOldName(prevPosition.getJabatan().getName());
        } else {
            ech.setJabatanOldCode("-");
        }
    }

    return listEmpCareerHistorys;
}