Example usage for org.hibernate.criterion Projections avg

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

Introduction

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

Prototype

public static AggregateProjection avg(String propertyName) 

Source Link

Document

A property average value projection

Usage

From source file:com.smartitengineering.dao.impl.hibernate.AbstractDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
private void processCriteria(Criteria criteria, String element, QueryParameter parameter) {
    switch (parameter.getParameterType()) {
    case PARAMETER_TYPE_PROPERTY: {
        criteria.add(getCriterion(element, parameter));
        return;/*w w w  . j  ava2s  .c  o  m*/
    }
    case PARAMETER_TYPE_ORDER_BY: {
        final Order order;
        SimpleNameValueQueryParameter<com.smartitengineering.dao.common.queryparam.Order> queryParameter = QueryParameterCastHelper.SIMPLE_PARAM_HELPER
                .cast(parameter);
        com.smartitengineering.dao.common.queryparam.Order requestedOrder = queryParameter.getValue();
        switch (requestedOrder) {
        case ASC: {
            order = Order.asc(element);
            break;
        }
        case DESC: {
            order = Order.desc(element);
            break;
        }
        default: {
            order = null;
            break;
        }
        }
        if (order != null) {
            criteria.addOrder(order);
        }
        return;
    }
    case PARAMETER_TYPE_MAX_RESULT: {
        ValueOnlyQueryParameter<Integer> queryParameter = QueryParameterCastHelper.VALUE_PARAM_HELPER
                .cast(parameter);
        criteria.setMaxResults(queryParameter.getValue());
        return;
    }
    case PARAMETER_TYPE_FIRST_RESULT: {
        ValueOnlyQueryParameter<Integer> queryParameter = QueryParameterCastHelper.VALUE_PARAM_HELPER
                .cast(parameter);
        criteria.setFirstResult(queryParameter.getValue());
        return;
    }
    case PARAMETER_TYPE_DISJUNCTION: {
        processDisjunction(criteria, parameter);
        return;
    }
    case PARAMETER_TYPE_CONJUNCTION: {
        processConjunction(criteria, parameter);
        return;
    }
    case PARAMETER_TYPE_NESTED_PROPERTY: {
        processNestedParameter(criteria, element, parameter);
        return;
    }
    case PARAMETER_TYPE_COUNT: {
        final Projection countProjection = Projections.count(element);
        setProjection(criteria, countProjection);
        return;
    }
    case PARAMETER_TYPE_ROW_COUNT: {
        final Projection rowCount = Projections.rowCount();
        setProjection(criteria, rowCount);
        return;
    }
    case PARAMETER_TYPE_SUM: {
        final AggregateProjection sum = Projections.sum(element);
        setProjection(criteria, sum);
        return;
    }
    case PARAMETER_TYPE_MAX: {
        final AggregateProjection max = Projections.max(element);
        setProjection(criteria, max);
        return;
    }
    case PARAMETER_TYPE_MIN: {
        final AggregateProjection min = Projections.min(element);
        setProjection(criteria, min);
        return;
    }
    case PARAMETER_TYPE_AVG: {
        final AggregateProjection avg = Projections.avg(element);
        setProjection(criteria, avg);
        return;
    }
    case PARAMETER_TYPE_GROUP_BY: {
        final PropertyProjection groupProperty = Projections.groupProperty(element);
        setProjection(criteria, groupProperty);
        return;
    }
    case PARAMETER_TYPE_COUNT_DISTINCT: {
        final CountProjection countDistinct = Projections.countDistinct(element);
        setProjection(criteria, countDistinct);
        return;
    }
    case PARAMETER_TYPE_DISTINCT_PROP: {
        final Projection distinct = Projections.distinct(Projections.property(element));
        setProjection(criteria, distinct);
        return;
    }
    case PARAMETER_TYPE_UNIT_PROP: {
        final PropertyProjection property = Projections.property(element);
        setProjection(criteria, property);
        return;
    }
    }
}

From source file:com.ut.tekir.invoice.yeni.LimitationChecker.java

License:LGPL

public DetachedCriteria buildCriteriaForWarehouse() {

    DetachedCriteria crit = DetachedCriteria.forClass(ProductTxn.class);

    crit.createAlias("product", "product");
    crit.createAlias("warehouse", "warehouse");

    ProjectionList pl = Projections.projectionList();
    pl.add(Projections.groupProperty("product.code"), "prodcode")
            .add(Projections.groupProperty("product.name"), "prodname")
            .add(Projections.groupProperty("product.group"), "group")
            .add(Projections.groupProperty("product.barcode1"), "barcode")
            .add(Projections.groupProperty("warehouse.code"), "warecode")
            .add(Projections.groupProperty("warehouse.name"), "warename")
            .add(Projections.sum("quantity.value"), "quantity")
            .add(Projections.avg("unitPrice.value"), "unitPrice")
            .add(Projections.sqlGroupProjection("{alias}.UNIT as unit, "
                    + "sum( case {alias}.trade_action when 0 then {alias}.QUANTITY else 0 end ) as INQTY, "
                    + "sum( case {alias}.trade_action when 1 then {alias}.QUANTITY else 0 end ) as OUTQTY , "
                    + "sum( case {alias}.trade_action when 2 then {alias}.QUANTITY else 0 end ) as BUYRETQTY, "
                    + "sum( case {alias}.trade_action when 3 then {alias}.QUANTITY else 0 end ) as SELLRETQTY, "
                    + "sum( case {alias}.trade_action when 6 then {alias}.QUANTITY else 0 end ) as RESQTY , "
                    + "sum( case {alias}.trade_action when 7 then {alias}.QUANTITY else 0 end ) as DELQTY ",
                    "UNIT",
                    new String[] { "unit", "inqty", "outqty", "buyretqty", "sellretqty", "resqty", "delqty" },
                    new Type[] { Hibernate.STRING, Hibernate.DOUBLE, Hibernate.DOUBLE, Hibernate.DOUBLE,
                            Hibernate.DOUBLE, Hibernate.DOUBLE, Hibernate.DOUBLE }));

    crit.setProjection(pl);/*from w  ww .j ava  2  s .  c o m*/

    crit.add(Restrictions.eq("active", true));

    //Evran kendisini toplam deerlere eklemiyoruz.
    if (filterModel.getDocId() != null) {
        crit.add(Restrictions.ne("documentId", filterModel.getDocId()));
    }

    if (filterModel.getBarcode() != null && filterModel.getBarcode().length() > 0) {
        Criterion criteria1 = Restrictions.eq("product.barcode1", filterModel.getBarcode());
        Criterion criteria2 = Restrictions.eq("product.barcode2", filterModel.getBarcode());
        Criterion criteria3 = Restrictions.eq("product.barcode3", filterModel.getBarcode());

        crit.add(Restrictions.or(criteria1, Restrictions.or(criteria2, criteria3)));
    }

    if (filterModel.getProduct() != null) {
        crit.add(Restrictions.eq("product", filterModel.getProduct()));
    }
    crit.addOrder(Order.asc("product.name"));

    return crit;
}

From source file:com.ut.tekir.report.ProductStatusReportBean.java

License:LGPL

public DetachedCriteria buildCriteria() {

    DetachedCriteria crit = DetachedCriteria.forClass(ProductTxn.class);

    crit.createAlias("product", "product");
    crit.createAlias("warehouse", "warehouse");

    //TODO: Unit Price'n farkl dvizlerde olma sorunu zle...
    ProjectionList pl = Projections.projectionList();
    pl.add(Projections.groupProperty("product.code"), "prodcode")
            .add(Projections.groupProperty("product.name"), "prodname") //.add( Projections.groupProperty("action"), "action" )
            //.add( Projections.groupProperty("amount.currency"), "currency" )
            .add(Projections.groupProperty("product.group"), "group")
            .add(Projections.groupProperty("product.barcode1"), "barcode")
            .add(Projections.sum("quantity.value"), "quantity")
            .add(Projections.avg("unitPrice.value"), "unitPrice")
            .add(Projections.sqlGroupProjection("{alias}.UNIT as unit, " +
    //"sum( case {alias}.finance_action when 0 then {alias}.QUANTITY else 0 end ) as INQTY, " +
    //"sum( case {alias}.finance_action when 0 then 0 else {alias}.QUANTITY end ) as OUTQTY",
                    "sum( case {alias}.trade_action when 0 then {alias}.QUANTITY else 0 end ) as INQTY, "
                    + "sum( case {alias}.trade_action when 1 then {alias}.QUANTITY else 0 end ) as OUTQTY , "
                    + "sum( case {alias}.trade_action when 2 then {alias}.QUANTITY else 0 end ) as BUYRETQTY, "
                    + "sum( case {alias}.trade_action when 3 then {alias}.QUANTITY else 0 end ) as SELLRETQTY, "
                    + "sum( case {alias}.trade_action when 6 then {alias}.QUANTITY else 0 end ) as RESQTY , "
                    + "sum( case {alias}.trade_action when 7 then {alias}.QUANTITY else 0 end ) as DELQTY ",
                    "UNIT",
                    new String[] { "unit", "inqty", "outqty", "buyretqty", "sellretqty", "resqty", "delqty" },
                    new Type[] { Hibernate.STRING, Hibernate.DOUBLE, Hibernate.DOUBLE, Hibernate.DOUBLE,
                            Hibernate.DOUBLE, Hibernate.DOUBLE, Hibernate.DOUBLE }));

    if (warehouseBase) {
        //Depo krlml
        pl.add(Projections.groupProperty("warehouse.code"), "warecode")
                .add(Projections.groupProperty("warehouse.name"), "warename");
        crit.addOrder(Order.asc("warehouse.code"));
    }//from www.ja  v a  2 s .  c o  m

    crit.setProjection(pl);

    crit.add(Restrictions.eq("active", true));

    if (code != null && code.length() > 0) {
        crit.add(Restrictions.ilike("product.code", code, MatchMode.START));
    }

    if (name != null && name.length() > 0) {
        crit.add(Restrictions.ilike("product.name", name, MatchMode.START));
    }

    if (productType != null) {

        if (getProductType() == 1) {
            crit.add(Restrictions.like("this.productType", ProductType.Product));
        } else if (getProductType() == 2) {
            crit.add(Restrictions.like("this.productType", ProductType.Service));

        }
    }

    if (barcode != null && barcode.length() > 0) {
        Criterion criteria1 = Restrictions.like("product.barcode1", barcode, MatchMode.START);
        Criterion criteria2 = Restrictions.like("product.barcode2", barcode, MatchMode.START);
        Criterion criteria3 = Restrictions.like("product.barcode3", barcode, MatchMode.START);

        crit.add(Restrictions.or(criteria1, Restrictions.or(criteria2, criteria3)));
    }

    if (group != null) {
        crit.add(Restrictions.eq("product.group", group));
    }

    if (warehouse != null) {
        crit.add(Restrictions.eq("warehouse", warehouse));
    }

    if (beginDate != null) {
        crit.add(Restrictions.ge("date", beginDate));
    }

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

    if (category != null) {
        crit.add(Restrictions.eq("product.category", category));
    }
    if (docCode != null && docCode.length() > 0) {
        crit.add(Restrictions.ilike("code", docCode, MatchMode.START));
    }

    if (getDocumentType() != null && getDocumentType() != DocumentType.Unknown) {
        crit.add(Restrictions.eq("this.documentType", getDocumentType()));
    }

    if (getWorkBunch() != null) {
        crit.add(Restrictions.eq("this.workBunch", getWorkBunch()));
    }

    /*
    crit.addOrder( Order.asc("date"));
    crit.addOrder( Order.asc("serial"));
     * 
     */

    crit.addOrder(Order.asc("product.name"));

    log.debug("Sonu : #0", crit);

    return crit;
}

From source file:com.ut.tekir.stock.ProductTxnReportBean.java

License:LGPL

public DetachedCriteria buildCriteriaForWarehouse() {

    DetachedCriteria crit = DetachedCriteria.forClass(ProductTxn.class);

    crit.createAlias("product", "product");
    crit.createAlias("warehouse", "warehouse");

    ProjectionList pl = Projections.projectionList();
    pl.add(Projections.groupProperty("product.code"), "prodcode")
            .add(Projections.groupProperty("product.name"), "prodname")
            .add(Projections.groupProperty("product.group"), "group")
            .add(Projections.groupProperty("product.barcode1"), "barcode")
            .add(Projections.groupProperty("warehouse.code"), "warecode")
            .add(Projections.groupProperty("warehouse.name"), "warename")
            .add(Projections.sum("quantity.value"), "quantity")
            .add(Projections.avg("unitPrice.value"), "unitPrice")
            .add(Projections.sqlGroupProjection("{alias}.UNIT as unit, "
                    + "sum( case {alias}.trade_action when 0 then {alias}.QUANTITY else 0 end ) as INQTY, "
                    + "sum( case {alias}.trade_action when 1 then {alias}.QUANTITY else 0 end ) as OUTQTY , "
                    + "sum( case {alias}.trade_action when 2 then {alias}.QUANTITY else 0 end ) as BUYRETQTY, "
                    + "sum( case {alias}.trade_action when 3 then {alias}.QUANTITY else 0 end ) as SELLRETQTY, "
                    + "sum( case {alias}.trade_action when 6 then {alias}.QUANTITY else 0 end ) as RESQTY , "
                    + "sum( case {alias}.trade_action when 7 then {alias}.QUANTITY else 0 end ) as DELQTY ",
                    "UNIT",
                    new String[] { "unit", "inqty", "outqty", "buyretqty", "sellretqty", "resqty", "delqty" },
                    new Type[] { Hibernate.STRING, Hibernate.DOUBLE, Hibernate.DOUBLE, Hibernate.DOUBLE,
                            Hibernate.DOUBLE, Hibernate.DOUBLE, Hibernate.DOUBLE }));

    crit.setProjection(pl);//from  w  w  w .  j av  a2  s .c om

    crit.add(Restrictions.eq("active", true));

    if (filterModel.getBarcode() != null && filterModel.getBarcode().length() > 0) {
        Criterion criteria1 = Restrictions.eq("product.barcode1", filterModel.getBarcode());
        Criterion criteria2 = Restrictions.eq("product.barcode2", filterModel.getBarcode());
        Criterion criteria3 = Restrictions.eq("product.barcode3", filterModel.getBarcode());

        crit.add(Restrictions.or(criteria1, Restrictions.or(criteria2, criteria3)));
    }

    if (filterModel.getProduct() != null) {
        crit.add(Restrictions.eq("product", filterModel.getProduct()));
    }
    crit.addOrder(Order.asc("product.name"));

    return crit;
}

From source file:db.DBConnector.java

private void updateDescObjGrade() {

    Criteria criteria = getSession().createCriteria(GradeExt.class);
    criteria.setProjection(Projections.avg("this.value"))
            .add(Restrictions.eq("this.idDescObj", pageOfDataGrid.getSelectedDescribedObj().getId()));
    int grade = Double.valueOf(criteria.uniqueResult().toString()).intValue();
    pageOfDataGrid.getSelectedDescribedObj().setGrade(grade);
    pageOfDataGrid.getSelectedDescribedObj()
            .setAmountOfGrade(pageOfDataGrid.getSelectedDescribedObj().getAmountOfGrade() + 1);
    getSession().update(pageOfDataGrid.getSelectedDescribedObj());
    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("You have rated"));

    /* Query query = getSession().createQuery("select new map(round(avg(value)) as rating, count(value) as gradeCount)  from GradeExt g where g.idDescObj.id=:id");
    query.setParameter("id", describedObjExt.getId());
            //from   w  ww .j  a v a  2 s  . c  o m
    List list = query.list();
            
    HashMap<String, Object> map = (HashMap<String, Object>) list.get(0);
            
    long gradeCount = Long.valueOf(map.get("gradeCount").toString());
    int grade = Float.valueOf(map.get("rating").toString()).intValue();
            
    query = getSession().createQuery("update DescribedObjExt set grade = :grade "
        + " where id = :id");
            
    query.setParameter("grade", grade);
    query.setParameter("id", describedObjExt.getId());
            
    int result = query.executeUpdate();*/
}

From source file:de.sub.goobi.helper.ProjectHelper.java

License:Open Source License

/**
 * static to reduce load/*w ww.j  a  v  a  2s . co m*/
 *
 * @param project
 *            object
 * @return a GoobiCollection of the following structure: GoobiCollection 1-n
 *         representing the steps each step has the following properties @
 *         stepTitle, stepOrder,
 *         stepCount,stepImageCount,totalProcessCount,totalImageCount which
 *         can get extracted by the IGoobiCollection Interface using the
 *         getItem(&lt;name&gt;) method standard workflow of the project
 *         according to the definition that only steps shared by all
 *         processes are returned. The workflow order is returned according
 *         to the average order return by a grouping by step title consider
 *         workflow structure to be a prototype, it would probably make
 *         things easier, to either assemble the underlying construction in
 *         separate classes or to create a new class with these properties
 */

@SuppressWarnings("unchecked")
public static synchronized List<StepInformation> getProjectWorkFlowOverview(Project project) {
    Long totalNumberOfProc = 0l;
    Long totalNumberOfImages = 0l;

    Session session = Helper.getHibernateSession();

    Criteria critTotals = session.createCriteria(Process.class, "proc");
    critTotals.add(Restrictions.eq("proc.template", Boolean.FALSE));
    critTotals.add(Restrictions.eq("proc.project", project));

    ProjectionList proList = Projections.projectionList();

    proList.add(Projections.count("proc.id"));
    proList.add(Projections.sum("proc.sortHelperImages"));

    critTotals.setProjection(proList);

    List<Object> list = critTotals.list();

    for (Object obj : list) {
        Object[] row = (Object[]) obj;

        totalNumberOfProc = (Long) row[FieldList.totalProcessCount.fieldLocation];
        totalNumberOfImages = (Long) row[FieldList.totalImageCount.fieldLocation];
        ;
    }

    proList = null;
    list = null;

    Criteria critSteps = session.createCriteria(Task.class);

    critSteps.createCriteria("process", "proc");
    critSteps.addOrder(Order.asc("ordering"));

    critSteps.add(Restrictions.eq("proc.template", Boolean.FALSE));
    critSteps.add(Restrictions.eq("proc.project", project));

    proList = Projections.projectionList();

    proList.add(Projections.groupProperty(("title")));
    proList.add(Projections.count("id"));
    proList.add(Projections.avg("ordering"));

    critSteps.setProjection(proList);

    // now we have to discriminate the hits where the max number of hits
    // doesn't reach numberOfProcs
    // and extract a workflow, which is the workflow common for all
    // processes according to its titel
    // the position will be calculated by the average of 'reihenfolge' of
    // steps

    list = critSteps.list();

    String title;
    Double averageStepOrder;
    Long numberOfSteps;
    Long numberOfImages;

    List<StepInformation> workFlow = new ArrayList<>();

    for (Object obj : list) {
        Object[] row = (Object[]) obj;

        title = (String) (row[FieldList.stepName.fieldLocation]);
        numberOfSteps = (Long) (row[FieldList.stepCount.fieldLocation]);
        averageStepOrder = (Double) (row[FieldList.stepOrder.fieldLocation]);

        // in this step we only take the steps which are present in each of
        // the workflows
        if (numberOfSteps.equals(totalNumberOfProc)) {
            StepInformation newStep = new StepInformation(title, averageStepOrder);
            newStep.setNumberOfTotalImages(totalNumberOfImages.intValue());
            newStep.setNumberOfTotalSteps(totalNumberOfProc.intValue());
            workFlow.add(newStep);
        }
    }

    Criteria critStepDone = session.createCriteria(Task.class, "step");

    critStepDone.createCriteria("process", "proc");

    critStepDone.add(Restrictions.eq("step.processingStatus", TaskStatus.DONE.getValue()));
    critStepDone.add(Restrictions.eq("proc.template", Boolean.FALSE));
    critStepDone.add(Restrictions.eq("proc.project", project));

    ProjectionList proCount = Projections.projectionList();

    proCount.add(Projections.groupProperty(("step.title")));
    proCount.add(Projections.count("proc.id"));
    proCount.add(Projections.sum("proc.sortHelperImages"));

    critStepDone.setProjection(proCount);

    list = critStepDone.list();

    for (Object obj : list) {

        Object[] row = (Object[]) obj;

        title = (String) (row[FieldList.stepName.fieldLocation]);
        numberOfSteps = (Long) (row[FieldList.stepCount.fieldLocation]);
        numberOfImages = (Long) (row[FieldList.imageCount.fieldLocation]);

        // getting from the workflow collection the collection which
        // represents step <title>
        // we only created one for each step holding the counts of processes
        for (StepInformation currentStep : workFlow) {
            if (currentStep.getTitle().equals(title)) {
                currentStep.setNumberOfStepsDone(numberOfSteps.intValue());
                currentStep.setNumberOfImagesDone(numberOfImages.intValue());
            }
        }
    }
    Comparator<StepInformation> comp = new compareWorkflowSteps();
    Collections.sort(workFlow, comp);
    return workFlow;
}

From source file:edu.depaul.armada.dao.ContainerLogDaoHibernate.java

License:Open Source License

/**
 * Returns a double after calculating the average usage of whatever data it
 * is passed. This method is a utility called by all of the data-specific
 * get average methods in the class./*from  w w w.j  a  va  2  s  .  c  o  m*/
 * @param containerId long
 * @param property String
 * @return double
 */
private double getAverage(long containerId, String property) {
    Criteria criteria = newCriteria();
    criteria.createAlias("container", "container");
    criteria.add(Restrictions.eq("container.id", containerId));
    criteria.setProjection(Projections.avg(property));
    Double result = (Double) criteria.uniqueResult();
    return (result == null) ? 0.0 : result;
}

From source file:edu.depaul.armada.dao.ContainerLogDaoHibernate.java

License:Open Source License

/**
 * Returns a List<Metric> from all of the containers with a specified ID, within a
 * a particular amount of time, and with an average of a specified field.
 * @param containerId long// ww w.  ja v  a  2  s.  com
 * @param periodCount int
 * @param fieldToAverage String
 * @return List<Metric>
 */
@Override
public List<Metric> findWithContainerIdAndPeriod(long containerId, int periodCount, String fieldToAverage) {
    List<Metric> metrics = new ArrayList<Metric>(periodCount);
    Calendar cal = Calendar.getInstance();
    for (int i = 0; i < periodCount; i++) {
        Date end = cal.getTime();
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        cal.add(Calendar.HOUR_OF_DAY, -1);
        Date start = cal.getTime();

        Criteria criteria = newCriteria();
        criteria.createAlias("container", "container");
        criteria.add(Restrictions.eq("container.id", containerId));
        criteria.add(Restrictions.le("timestamp", end));
        criteria.add(Restrictions.gt("timestamp", start)); // we don't want overlap here
        criteria.setProjection(Projections.avg(fieldToAverage));
        Object result = criteria.uniqueResult();
        int count = (result == null) ? 0 : ((Double) result).intValue();
        Metric temp = new Metric();
        temp.setHour(hour);
        temp.setValue(count);
        metrics.add(temp);
    }
    Collections.reverse(metrics); // we want the current time to be the last hour
    return metrics;
}

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

License:Open Source License

/**
 * Average value/* ww  w.j  av  a  2s.com*/
 * 
 * @param kpi
 * @return
 */
public Double averageValue(Projectkpi kpi) {

    Criteria crit = getSession().createCriteria(getPersistentClass());

    crit.add(Restrictions.eq(Historickpi.PROJECTKPI, kpi)).setProjection(Projections.avg(Historickpi.VALUEKPI));

    return (Double) crit.uniqueResult();
}

From source file:eu.jangos.manager.controller.RealmService.java

License:Apache License

/**
 * Returns the average population of all servers in the database.
 * @return A float number corresponding to the average population.
 *//*  w  w w. ja v  a2s. c  om*/
public double getAveragePopulation() {
    logger.debug("Calculation average population.");

    try (Session session = HibernateUtil.getSessionFactory().openSession()) {
        return (double) session.createCriteria(Realm.class).setProjection(Projections.avg("population"))
                .uniqueResult();
    } catch (HibernateException he) {
        return 0;
    }
}