Example usage for org.hibernate.criterion Projections min

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

Introduction

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

Prototype

public static AggregateProjection min(String propertyName) 

Source Link

Document

A property minimum value projection

Usage

From source file:es.sm2.openppm.core.dao.ProcurementpaymentsDAO.java

License:Open Source License

/**
 * Find min and max actual dates of projects
 * //ww  w.  ja  v  a  2s . c  om
 * @param projects
 * @return
 */
public RangeDateWrap findMinAndMaxActualDatesByProjects(List<Project> projects) {

    RangeDateWrap range = null;

    if (ValidateUtil.isNotNull(projects)) {

        Criteria crit = getSession().createCriteria(getPersistentClass())
                .add(Restrictions.in(Procurementpayments.PROJECT, projects))
                .setProjection(Projections.projectionList()
                        .add(Projections.min(Procurementpayments.ACTUALDATE),
                                RangeDateWrap.Fields.MINDATE.toString())
                        .add(Projections.max(Procurementpayments.ACTUALDATE),
                                RangeDateWrap.Fields.MAXDATE.toString()))
                .setResultTransformer(Transformers.aliasToBean(RangeDateWrap.class));

        range = (RangeDateWrap) crit.uniqueResult();
    }

    return range;
}

From source file:es.sm2.openppm.core.dao.ProjectActivityDAO.java

License:Open Source License

/**
 * Update Planned Dates of root activity
 * // ww  w  . j  av a  2  s .co m
 * @param project
 * @param rootActivity
 */
public void updatePlannedDates(Project project, Projectactivity rootActivity) {

    // Num of activities of project
    int numActivities = rowCountEq(Projectactivity.PROJECT, project);

    // Get max and min project activity dates
    Criteria crit = getSession().createCriteria(getPersistentClass())
            .setProjection(Projections.projectionList().add(Projections.min(Projectactivity.PLANINITDATE))
                    .add(Projections.max(Projectactivity.PLANENDDATE)))
            .add(Restrictions.eq(Projectactivity.PROJECT, project));

    // Exclude root activities
    if (numActivities > 1) {
        crit.add(Restrictions.ne(Projectactivity.IDACTIVITY, rootActivity.getIdActivity()));
    }

    Object[] row = (Object[]) crit.uniqueResult();

    // Init calculated plan dates
    Date calculatedPlanStartDate = null;
    Date calculatedPlanFinishDate = null;

    // If there is result set root activity
    if (row != null && row.length > 0) {

        Date planInitDate = (Date) row[0];
        Date planEndDate = (Date) row[1];

        rootActivity.setPlanInitDate(planInitDate);
        rootActivity.setPlanEndDate(planEndDate);
        rootActivity = makePersistent(rootActivity);

        // Set calculated plan dates 
        calculatedPlanStartDate = planInitDate == null ? project.getPlannedInitDate() : planInitDate;
        calculatedPlanFinishDate = planEndDate == null ? project.getPlannedFinishDate() : planEndDate;
    } else {

        // Set calculated plan dates 
        calculatedPlanStartDate = project.getPlannedInitDate();
        calculatedPlanFinishDate = project.getPlannedFinishDate();
    }

    // Update calculated planning dates
    Query query = getSession().createQuery("update Project p "
            + " set p.calculatedPlanStartDate = :calculatedPlanStartDate,"
            + " p.calculatedPlanFinishDate = :calculatedPlanFinishDate" + " where p.idProject = :idProject");
    query.setInteger("idProject", project.getIdProject());
    query.setDate("calculatedPlanStartDate", calculatedPlanStartDate);
    query.setDate("calculatedPlanFinishDate", calculatedPlanFinishDate);
    query.executeUpdate();
}

From source file:fsl.ta.toms.roms.dao.impl.RoadCompliancyDAOImpl.java

@Override
public Date getMinCourtAppearnceDateForCompliancy(Integer complianceId) {
    Criteria criteria = this.hibernateTemplate.getSessionFactory().getCurrentSession()
            .createCriteria(CourtAppearanceDO.class, "courtAp");

    //create aliases
    criteria.createAlias("courtAp.courtCase", "courtCase");
    criteria.createAlias("courtCase.summons", "summons");
    criteria.createAlias("summons.roadCheckOffenceOutcome", "roadCkOffOut");
    criteria.createAlias("roadCkOffOut.outcomeType", "outcome");
    criteria.createAlias("roadCkOffOut.roadCheckOffence", "roadChkOff");
    criteria.createAlias("roadChkOff.roadCheck", "roadCheck");
    criteria.createAlias("roadCheck.compliance", "compliance");

    criteria.add(Restrictions.eq("compliance.complianceId", complianceId));
    criteria.add(Restrictions.eq("outcome.outcomeTypeId", Constants.OutcomeType.ISSUE_SUMMONS));

    criteria.setProjection(Projections.min("courtDTime"));

    return (Date) criteria.uniqueResult();

}

From source file:grails.orm.HibernateCriteriaBuilder.java

License:Apache License

/**
 * Adds a projection that allows the criteria to retrieve a  minimum property value
 *
 * @param alias The alias to use// w w  w  .j a v a2  s  .  c  om
 */
public org.grails.datastore.mapping.query.api.Projections min(String propertyName, String alias) {
    final AggregateProjection aggregateProjection = Projections.min(calculatePropertyName(propertyName));
    addProjectionToList(aggregateProjection, alias);
    return this;
}

From source file:io.milton.cloud.server.apps.admin.WebsiteAccessReport.java

License:Open Source License

@Override
public GraphData runReport(Organisation org, Website website, Date start, Date finish, JsonResult jsonResult) {
    Session session = SessionManager.session();
    Criteria crit = session.createCriteria(AccessLog.class)
            .setProjection(Projections.projectionList().add(Projections.min("reqDate"))
                    .add(Projections.rowCount()).add(Projections.groupProperty("reqYear"))
                    .add(Projections.groupProperty("reqMonth")).add(Projections.groupProperty("reqDay"))
                    .add(Projections.groupProperty("reqHour")));
    if (start != null) {
        crit.add(Restrictions.ge("reqDate", start));
    }/*from  w  ww.j  ava 2  s  .  com*/
    if (finish != null) {
        crit.add(Restrictions.le("reqDate", finish));
    }
    if (website != null) {
        crit.add(Restrictions.le("website", website));
    }
    if (org != null) {
        crit.add(Restrictions.le("organisation", org));
    }
    List list = crit.list();
    List<TimeDataPointBean> dataPoints = new ArrayList<>();
    for (Object oRow : list) {
        Object[] arr = (Object[]) oRow;
        Date date = (Date) arr[0];
        Integer count = (Integer) arr[1];
        TimeDataPointBean b = new TimeDataPointBean();
        b.setDate(date.getTime());
        b.setValue(count);
        dataPoints.add(b);
    }
    GraphData graphData = new GraphData();
    graphData.setData(dataPoints);
    String[] labels = { "Hits" };
    graphData.setLabels(labels);
    graphData.setXkey("date");
    String[] ykeys = { "value" };
    graphData.setYkeys(ykeys);
    return graphData;
}

From source file:io.milton.cloud.server.apps.reporting.SiteActivityReportPage.java

License:Open Source License

private void searchDaily(Map<String, String> params, OutputStream out) throws IOException {
    Date start;/*from ww  w. ja  va 2s .co  m*/
    Date finish;
    try {
        String sStart = params.get("startDate");
        start = parseDate(sStart);
        System.out.println("start: " + start);
        String sFinish = params.get("finishDate");
        finish = parseDate(sFinish);
        System.out.println("finish: " + finish);
    } catch (ParseException parseException) {
        JsonResult jsonResult = new JsonResult(false, "Invalid date: " + parseException.getMessage());
        jsonResult.write(out);
        return;
    }
    Session session = SessionManager.session();
    Criteria crit = session.createCriteria(AccessLog.class)
            .setProjection(Projections.projectionList().add(Projections.min("reqDate"))
                    .add(Projections.rowCount()).add(Projections.groupProperty("reqYear"))
                    .add(Projections.groupProperty("reqMonth")).add(Projections.groupProperty("reqDay"))
                    .add(Projections.groupProperty("reqHour")));
    if (start != null) {
        crit.add(Restrictions.ge("reqDate", start));
    }
    if (finish != null) {
        crit.add(Restrictions.le("reqDate", finish));
    }
    List list = crit.list();
    List<TimeDataPointBean> dataPoints = new ArrayList<>();
    for (Object oRow : list) {
        Object[] arr = (Object[]) oRow;
        Date date = (Date) arr[0];
        Integer count = (Integer) arr[1];
        TimeDataPointBean b = new TimeDataPointBean();
        b.setDate(date.getTime());
        b.setValue(count);
        dataPoints.add(b);
    }
    JsonResult jsonResult = new JsonResult(true);
    jsonResult.setData(dataPoints);
    jsonResult.write(out);
}

From source file:io.milton.cloud.server.apps.signup.GroupSignupsReport.java

License:Open Source License

@Override
public GraphData runReport(Organisation org, Website website, Date start, Date finish, JsonResult jsonResult) {
    log.info("runReport: " + start + " - " + finish);
    Session session = SessionManager.session();
    Criteria crit = session.createCriteria(SignupLog.class)
            .setProjection(Projections.projectionList().add(Projections.min("reqDate"))
                    .add(Projections.rowCount()).add(Projections.groupProperty("groupEntity"))
                    .add(Projections.groupProperty("reqYear")).add(Projections.groupProperty("reqMonth"))
                    .add(Projections.groupProperty("reqDay")).add(Projections.groupProperty("reqHour")));
    //        if (start != null) {
    //            crit.add(Restrictions.ge("reqDate", start));
    //        }//from w w  w  .jav  a 2  s  .  c om
    //        if (finish != null) {
    //            crit.add(Restrictions.le("reqDate", finish));
    //        }
    //        if( website != null ) {
    //            crit.add(Restrictions.le("website", website));
    //        }
    //        if( org != null ) {
    //            crit.add(Restrictions.le("organisation", org));
    //        }
    List list = crit.list();
    Set<String> groupsInSeries = new HashSet<>();
    List<Map<String, Object>> dataPoints = new ArrayList<>();
    Map<Long, Map<String, Object>> mapOfDataPointsByTime = new HashMap<>();
    log.info("results: " + list.size());
    for (Object oRow : list) {
        Object[] arr = (Object[]) oRow;
        log.info("got row: " + arr);
        Date date = (Date) arr[0];
        Long time = date.getTime();
        Integer count = (Integer) arr[1];
        Group group = (Group) arr[2];

        groupsInSeries.add(group.getName()); // keep a set of group names for labels

        Map<String, Object> dataPoint = mapOfDataPointsByTime.get(time);
        if (dataPoint == null) {
            dataPoint = new HashMap<>();
            dataPoint.put("date", time);
            mapOfDataPointsByTime.put(time, dataPoint);
            dataPoints.add(dataPoint);
        }
        dataPoint.put(group.getName(), count);

    }
    GraphData graphData = new GraphData();
    graphData.setData(dataPoints);
    String[] labels = { "Signups" };
    graphData.setLabels(labels);
    graphData.setXkey("date");
    String[] ykeys = new String[groupsInSeries.size()];
    groupsInSeries.toArray(ykeys);
    graphData.setYkeys(ykeys);
    log.info("data points: " + dataPoints.size());
    return graphData;
}

From source file:mitm.common.security.ca.hibernate.CertificateRequestDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
public CertificateRequestEntity getNextRequest(Date notAfter) {
    DetachedCriteria minDateCriteria = createDetachedCriteria(CertificateRequestEntity.ENTITY_NAME);

    /*/*from   w  w  w  .  ja  va 2s  . c o m*/
     * Create a criteria to get the oldest nextUpdate
     */
    minDateCriteria.setProjection(Projections.min(CertificateRequestEntity.NEXT_UPDATE_COLUMN_NAME));

    Criteria criteria = createCriteria(CertificateRequestEntity.ENTITY_NAME);

    criteria.add(Restrictions.or(
            Property.forName(CertificateRequestEntity.NEXT_UPDATE_COLUMN_NAME).eq(minDateCriteria),
            Restrictions.isNull(CertificateRequestEntity.NEXT_UPDATE_COLUMN_NAME)));

    /*
     * We only want entries that are older than notAfter or have no nextUpdate yet. The reason for notAfter is
     * that we do not want to try too fast in succession. By setting notAfter to the current date we will only 
     * get entries for which the update is long overdue.
     */
    criteria.add(Restrictions.or(Restrictions.le(CertificateRequestEntity.NEXT_UPDATE_COLUMN_NAME, notAfter),
            Restrictions.isNull(CertificateRequestEntity.NEXT_UPDATE_COLUMN_NAME)));

    addSortOnCreationDate(criteria);

    CertificateRequestEntity next = null;

    List<CertificateRequestEntity> found = criteria.list();

    if (found != null && found.size() > 0) {
        next = found.get(0);
    }

    return next;
}

From source file:mitm.common.sms.hibernate.SMSGatewayDAO.java

License:Open Source License

/**
 * Returns the entry that has the oldest try date and not after notAfter. If there is no such entry null
 * is returned.//w  w w  . jav a  2s. co  m
 */
@SuppressWarnings("unchecked")
public SMSGatewayEntity getNextAvailable(Date notAfter) {
    DetachedCriteria minDateCriteria = createDetachedCriteria(entityName);

    /*
     * Create a criteria to get the oldest dateLastTry
     */
    minDateCriteria.setProjection(Projections.min(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn()));

    Criteria criteria = createCriteria(entityName);

    criteria.add(Restrictions.or(
            Property.forName(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn()).eq(minDateCriteria),
            Restrictions.isNull(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn())));

    /*
     * We only want entries that are older than notAfter or have no dateLastTry yet. The reason for notAfter is
     * that we do not want to try too fast in succession. By setting notAfter in the past we can make sure that
     * we only get entries that are not recently been updated.
     */
    criteria.add(Restrictions.or(Restrictions.le(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn(), notAfter),
            Restrictions.isNull(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn())));

    SMSGatewayEntity next = null;

    List<SMSGatewayEntity> found = criteria.list();

    if (found != null && found.size() > 0) {
        next = found.get(0);
    }

    return next;
}

From source file:net.firejack.platform.core.store.statistics.LogTransactionStore.java

License:Apache License

@Override
@Transactional(readOnly = true)//from w w  w  .  jav  a 2 s . c  o m
public List<LogTransactionModel> findAggregatedByTermAndDates(Integer offset, Integer limit, String term,
        String lookup, Date startDate, Date endDate, String sortColumn, String sortDirection,
        MetricGroupLevel level) {
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.min("hourPeriod"), "startTime").add(Projections.max("hourPeriod"), "endTime")
            .add(Projections.groupProperty("packageLookup"), "packageLookup")
            .add(Projections.sum("transactions"), "transactions")
            .add(Projections.sum("entitiesLoaded"), "entitiesLoaded")
            .add(Projections.sum("entitiesUpdated"), "entitiesUpdated")
            .add(Projections.sum("entitiesInserted"), "entitiesInserted")
            .add(Projections.sum("entitiesDeleted"), "entitiesDeleted")
            .add(Projections.sum("entitiesFetched"), "entitiesFetched")
            .add(Projections.sum("collectionsLoaded"), "collectionsLoaded")
            .add(Projections.sum("collectionsUpdated"), "collectionsUpdated")
            .add(Projections.sum("collectionsRecreated"), "collectionsRecreated")
            .add(Projections.sum("collectionsRemoved"), "collectionsRemoved")
            .add(Projections.sum("collectionsFetched"), "collectionsFetched")
            .add(Projections.max("maxQueryTime"), "maxQueryTime");

    switch (level) {
    case HOUR:
        projectionList.add(Projections.groupProperty("hourPeriod").as("hourPeriod"));
        break;
    case DAY:
        projectionList.add(Projections.groupProperty("dayPeriod").as("dayPeriod"));
        break;
    case WEEK:
        projectionList.add(Projections.groupProperty("weekPeriod").as("weekPeriod"));
        break;
    case MONTH:
        projectionList.add(Projections.groupProperty("monthPeriod").as("monthPeriod"));
        break;
    }

    return findAllByProjection(offset, limit, term, lookup, startDate, endDate, sortColumn, sortDirection,
            projectionList);
}