Example usage for org.hibernate.criterion Projections groupProperty

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

Introduction

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

Prototype

public static PropertyProjection groupProperty(String propertyName) 

Source Link

Document

A grouping property value projection

Usage

From source file:org.n52.sos.ds.hibernate.util.HibernateCriteriaQueryUtilities.java

License:Open Source License

/**
 * @return a Map containing the bounding box for each offering
 *///from w  ww.j av  a2  s  .  c om
@Deprecated
public static Map<String, TimePeriod> getTemporalBoundingBoxesForOfferings(Session session) {
    if (session != null) {
        Criteria criteria = session.createCriteria(Observation.class)
                .add(Restrictions.eq(Observation.DELETED, false));
        criteria.createAlias(Observation.OFFERINGS, "off");
        criteria.setProjection(
                Projections.projectionList().add(Projections.min(Observation.PHENOMENON_TIME_START))
                        .add(Projections.max(Observation.PHENOMENON_TIME_START))
                        .add(Projections.max(Observation.PHENOMENON_TIME_END))
                        .add(Projections.groupProperty("off." + Offering.IDENTIFIER)));

        List<?> temporalBoundingBoxes = criteria.list();
        if (!temporalBoundingBoxes.isEmpty()) {
            HashMap<String, TimePeriod> temporalBBoxMap = new HashMap<String, TimePeriod>(
                    temporalBoundingBoxes.size());
            for (Object recordObj : temporalBoundingBoxes) {
                if (recordObj instanceof Object[]) {
                    Object[] record = (Object[]) recordObj;
                    TimePeriod value = createTimePeriod((Timestamp) record[0], (Timestamp) record[1],
                            (Timestamp) record[2]);
                    temporalBBoxMap.put((String) record[3], value);
                }
            }
            LOGGER.debug(temporalBoundingBoxes.toString());
            return temporalBBoxMap;
        }
    }
    return new HashMap<String, TimePeriod>(0);
}

From source file:org.onebusaway.transit_data_federation.impl.reporting.UserReportingDaoImpl.java

License:Apache License

@SuppressWarnings("unchecked")
@Override//from w ww. j a  v  a2s .co m
public List<T2<Object, Integer>> getTripProblemReportSummaries(final TripProblemReportQueryBean query,
        final ETripProblemGroupBy groupBy) {

    List<Object[]> rows = _template.executeFind(new HibernateCallback<List<Object[]>>() {

        @Override
        public List<Object[]> doInHibernate(Session session) throws HibernateException, SQLException {

            Criteria c = session.createCriteria(TripProblemReportRecord.class);

            ProjectionList projections = Projections.projectionList();
            projections.add(Projections.rowCount());
            switch (groupBy) {
            case TRIP:
                projections.add(Projections.groupProperty("tripId.agencyId"));
                projections.add(Projections.groupProperty("tripId.id"));
                break;
            case STATUS:
                projections.add(Projections.groupProperty("status"));
                break;
            case LABEL:
                projections.add(Projections.groupProperty("label"));
                break;
            }
            c.setProjection(projections);

            addQueryToCriteria(query, c);

            return c.list();
        }
    });

    List<T2<Object, Integer>> results = new ArrayList<T2<Object, Integer>>(rows.size());

    for (Object[] row : rows) {
        Integer count = (Integer) row[0];
        Object key = getKeyForTripProblemReportSummariesRow(row, groupBy);
        results.add(Tuples.tuple(key, count.intValue()));
    }

    return results;
}

From source file:org.openmrs.module.amrscustomization.db.HibernateAMRSCustomizationDAO.java

License:Open Source License

public List<Form> getPopularRecentFormsForUser(User user) {
    String monthsStr = Context.getAdministrationService()
            .getGlobalProperty(AMRSCustomizationConstants.GP_RECENT_FORMS_INTERVAL);
    Integer months = AMRSCustomizationConstants.DEFAULT_RECENT_FORMS_INTERVAL;
    try {//from  w w  w .  j a  va2 s  .com
        months = Integer.parseInt(monthsStr);
    } catch (NumberFormatException ex) {
        log.warn("could not interpret " + monthsStr + " interval as an integer.");
    }

    Calendar monthsAgo = Calendar.getInstance();
    monthsAgo.add(Calendar.MONTH, -1 * months);

    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.groupProperty("form"));
    projectionList.add(Projections.alias(Projections.rowCount(), "total"));

    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Encounter.class)
            .add(Restrictions.and(Restrictions.eq("creator", user),
                    Restrictions.gt("dateCreated", monthsAgo.getTime())))
            .setProjection(projectionList).addOrder(Order.desc("total")).setMaxResults(5);

    List<Form> forms = new ArrayList<Form>();
    List<Object[]> foo = crit.list();
    for (Object[] result : foo) {
        log.warn(result[0] + ": " + result[1]);
        forms.add((Form) result[0]);
    }

    return forms;
}

From source file:org.openmrs.module.clinicalsummary.db.hibernate.HibernateReminderDAO.java

License:Open Source License

/**
 * @see ReminderDAO#aggregateReminders(java.util.Map, java.util.Collection, java.util.Date, java.util.Date)
 *//*from   w  w w .j  a v  a  2  s.c o m*/
@Override
@SuppressWarnings("unchecked")
public List<Object[]> aggregateReminders(final Map<String, Collection<OpenmrsObject>> restrictions,
        final Collection<String> groupingProperties, final Date reminderStart, final Date reminderEnd)
        throws DAOException {

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Reminder.class);

    if (MapUtils.isNotEmpty(restrictions)) {
        Reminder reminder = new Reminder();
        for (String property : restrictions.keySet()) {
            Collection<OpenmrsObject> objects = restrictions.get(property);
            if (CollectionUtils.isNotEmpty(objects) && PropertyUtils.isReadable(reminder, property))
                criteria.add(Restrictions.in(property, objects));
        }
    }

    if (reminderStart != null)
        criteria.add(Restrictions.ge("reminderDatetime", reminderStart));

    if (reminderEnd != null)
        criteria.add(Restrictions.le("reminderDatetime", reminderEnd));

    ProjectionList projectionList = Projections.projectionList();
    for (String groupingProperty : groupingProperties) {
        // group by the property and order by the same property desc and the property must not null
        criteria.add(Restrictions.isNotNull(groupingProperty));
        projectionList.add(Projections.groupProperty(groupingProperty));
        criteria.addOrder(Order.asc(groupingProperty));
    }
    // add the row count projection to the projection list
    projectionList.add(Projections.rowCount());
    criteria.setProjection(projectionList);

    return criteria.list();
}

From source file:org.openmrs.module.clinicalsummary.db.hibernate.HibernateUtilDAO.java

License:Open Source License

/**
 * @see UtilDAO#getOrderedObs(java.util.Map, java.util.Date, java.util.Date)
 *//*w  w w  . ja  v  a  2  s.com*/
@Override
@SuppressWarnings("unchecked")
public List<Object[]> aggregateOrderedObs(final Map<String, Collection<OpenmrsObject>> restrictions,
        final Collection<String> groupingProperties, final StatusType statusType, final Date startTime,
        final Date endTime) throws DAOException {

    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(OrderedObs.class);

    // hack to prevent results for tests ordered concept when grouping results on concept
    if (groupingProperties.contains("concept"))
        criteria.add(Restrictions
                .not(Restrictions.eq("concept", CacheUtils.getConcept(EvaluableNameConstants.TESTS_ORDERED))));

    if (MapUtils.isNotEmpty(restrictions)) {
        OrderedObs orderedObs = new OrderedObs();
        for (String property : restrictions.keySet()) {
            Collection<OpenmrsObject> objects = restrictions.get(property);
            if (CollectionUtils.isNotEmpty(objects) && PropertyUtils.isReadable(orderedObs, property))
                criteria.add(Restrictions.in(property, objects));
        }
    }

    if (statusType != null)
        criteria.add(Restrictions.eq("status", statusType));

    if (startTime != null)
        criteria.add(Restrictions.ge("orderedDatetime", startTime));

    if (endTime != null)
        criteria.add(Restrictions.le("orderedDatetime", endTime));

    ProjectionList projectionList = Projections.projectionList();
    for (String groupingProperty : groupingProperties) {
        // group by the property and order by the same property desc and the property must not null
        criteria.add(Restrictions.isNotNull(groupingProperty));
        projectionList.add(Projections.groupProperty(groupingProperty));
        criteria.addOrder(Order.asc(groupingProperty));
    }
    // add the row count projection to the projection list
    projectionList.add(Projections.rowCount());
    criteria.setProjection(projectionList);

    return criteria.list();
}

From source file:org.openmrs.module.dataintegrityworkflow.db.hibernate.HibernateDataIntegrityWorkflowDAO.java

License:Open Source License

public List getCheckRecordStatusCounts(IntegrityCheck integrityCheck) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(IntegrityCheckResult.class);
    criteria.add(Restrictions.eq("integrityCheck", integrityCheck));
    ProjectionList projList = Projections.projectionList();
    projList.add(Projections.groupProperty("status"), "statusId");
    projList.add(Projections.rowCount(), "count");
    criteria.setProjection(projList);/*ww  w.j  a v a  2  s.  c o m*/
    return criteria.list();
}

From source file:org.openmrs.module.hospitalcore.db.hibernate.HibernateInventoryDAO.java

public List<InventoryStoreDrugTransactionDetail> listStoreDrugAvaiable(Integer storeId,
        Collection<Integer> drugs, Collection<Integer> formulations) throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession()
            .createCriteria(InventoryStoreDrugTransactionDetail.class, "transactionDetail")
            .createAlias("transactionDetail.transaction", "transaction")
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    ProjectionList proList = Projections.projectionList();
    proList.add(Projections.groupProperty("drug")).add(Projections.groupProperty("formulation"))
            .add(Projections.sum("currentQuantity"));
    criteria.add(Restrictions.eq("transaction.store.id", storeId));
    if (drugs != null) {
        criteria.createCriteria("transactionDetail.drug", Criteria.INNER_JOIN)
                .add(Restrictions.in("id", drugs));
    }/*ww w.  j a va  2s  .c  o m*/
    criteria.add(Restrictions.eq("transaction.typeTransaction", ActionValue.TRANSACTION[0]));
    if (formulations != null) {
        criteria.createCriteria("transactionDetail.formulation", Criteria.INNER_JOIN)
                .add(Restrictions.in("id", formulations));
    }
    criteria.setProjection(proList);
    criteria.add(Restrictions.ge("transactionDetail.dateExpiry", new Date()));
    List<Object> lst = criteria.list();
    if (lst == null || lst.size() == 0)
        return null;
    List<InventoryStoreDrugTransactionDetail> list = new ArrayList<InventoryStoreDrugTransactionDetail>();
    // System.out.println("lst size: "+lst.size());
    for (int i = 0; i < lst.size(); i++) {
        Object[] row = (Object[]) lst.get(i);
        InventoryStoreDrugTransactionDetail tDetail = new InventoryStoreDrugTransactionDetail();
        tDetail.setDrug((InventoryDrug) row[0]);
        tDetail.setFormulation((InventoryDrugFormulation) row[1]);
        tDetail.setCurrentQuantity((Integer) row[2]);
        list.add(tDetail);
        // System.out.println("I: "+i+" drug: "+tDetail.getDrug().getName()+" formulation: "+tDetail.getFormulation().getName()+" quantity: "+tDetail.getCurrentQuantity());
    }
    return list;
}

From source file:org.openmrs.module.hospitalcore.db.hibernate.HibernateInventoryDAO.java

public List<InventoryStoreDrugTransactionDetail> listViewStockBalance(Integer storeId, Integer categoryId,
        String drugName, String fromDate, String toDate, boolean isExpiry, int min, int max)
        throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession()
            .createCriteria(InventoryStoreDrugTransactionDetail.class, "transactionDetail")
            .createAlias("transactionDetail.transaction", "transaction")
            .createAlias("transactionDetail.drug", "drugAlias")
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    ProjectionList proList = Projections.projectionList();
    proList.add(Projections.groupProperty("drug")).add(Projections.groupProperty("formulation"))
            .add(Projections.sum("currentQuantity")).add(Projections.sum("quantity"))
            .add(Projections.sum("issueQuantity"));
    criteria.add(Restrictions.eq("transaction.store.id", storeId));
    if (categoryId != null) {
        criteria.add(Restrictions.eq("drugAlias.category.id", categoryId));
    }// w ww  .  j  av a 2 s.c o  m
    if (!StringUtils.isBlank(drugName)) {
        criteria.add(Restrictions.like("drugAlias.name", "%" + drugName + "%"));
    }
    if (!StringUtils.isBlank(fromDate) && StringUtils.isBlank(toDate)) {
        String startFromDate = fromDate + " 00:00:00";
        String endFromDate = fromDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startFromDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endFromDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listSubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    } else if (StringUtils.isBlank(fromDate) && !StringUtils.isBlank(toDate)) {
        String startToDate = toDate + " 00:00:00";
        String endToDate = toDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startToDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endToDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listSubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    } else if (!StringUtils.isBlank(fromDate) && !StringUtils.isBlank(toDate)) {
        String startToDate = fromDate + " 00:00:00";
        String endToDate = toDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startToDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endToDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listInventorySubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    }
    if (isExpiry) {
        criteria.add(Restrictions.lt("transactionDetail.dateExpiry", new Date()));
    } else {
        criteria.add(Restrictions.ge("transactionDetail.dateExpiry", new Date()));
    }

    /*
     * Sagar Bele : 13-08-2012 Bug #330 ( [INVENTORY]-error in Current
     * quantity of pharmacy )
     */
    criteria.add(Restrictions.ge("transactionDetail.currentQuantity", 0));

    criteria.setProjection(proList);
    if (max > 0) {
        criteria.setFirstResult(min).setMaxResults(max);
    }
    List<Object> lst = criteria.list();
    if (lst == null || lst.size() == 0)
        return null;
    List<InventoryStoreDrugTransactionDetail> list = new ArrayList<InventoryStoreDrugTransactionDetail>();
    for (int i = 0; i < lst.size(); i++) {
        Object[] row = (Object[]) lst.get(i);
        InventoryStoreDrugTransactionDetail tDetail = new InventoryStoreDrugTransactionDetail();
        tDetail.setDrug((InventoryDrug) row[0]);
        tDetail.setFormulation((InventoryDrugFormulation) row[1]);
        tDetail.setCurrentQuantity((Integer) row[2]);
        tDetail.setQuantity((Integer) row[3]);
        tDetail.setIssueQuantity((Integer) row[4]);
        list.add(tDetail);
    }

    return list;
}

From source file:org.openmrs.module.hospitalcore.db.hibernate.HibernateInventoryDAO.java

public Integer countViewStockBalance(Integer storeId, Integer categoryId, String drugName, String fromDate,
        String toDate, boolean isExpiry) throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession()
            .createCriteria(InventoryStoreDrugTransactionDetail.class, "transactionDetail")
            .createAlias("transactionDetail.transaction", "transaction")
            .createAlias("transactionDetail.drug", "drugAlias");

    ProjectionList proList = Projections.projectionList();
    proList.add(Projections.groupProperty("drug")).add(Projections.groupProperty("formulation"))
            .add(Projections.sum("currentQuantity")).add(Projections.sum("quantity"))
            .add(Projections.sum("issueQuantity"));
    criteria.add(Restrictions.eq("transaction.store.id", storeId));
    if (categoryId != null) {
        criteria.add(Restrictions.eq("drugAlias.category.id", categoryId));
    }//w w  w.j a va  2 s .  c  o m
    if (!StringUtils.isBlank(drugName)) {
        criteria.add(Restrictions.like("drugAlias.name", "%" + drugName + "%"));
    }
    if (!StringUtils.isBlank(fromDate) && StringUtils.isBlank(toDate)) {
        String startFromDate = fromDate + " 00:00:00";
        String endFromDate = fromDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startFromDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endFromDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listSubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    } else if (StringUtils.isBlank(fromDate) && !StringUtils.isBlank(toDate)) {
        String startToDate = toDate + " 00:00:00";
        String endToDate = toDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startToDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endToDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listSubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    } else if (!StringUtils.isBlank(fromDate) && !StringUtils.isBlank(toDate)) {
        String startToDate = fromDate + " 00:00:00";
        String endToDate = toDate + " 23:59:59";
        try {
            criteria.add(Restrictions.and(
                    Restrictions.ge("transactionDetail.createdOn", formatter.parse(startToDate)),
                    Restrictions.le("transactionDetail.createdOn", formatter.parse(endToDate))));
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("listInventorySubStoreIndent>>Error convert date: " + e.toString());
            e.printStackTrace();
        }
    }
    if (isExpiry) {
        criteria.add(Restrictions.lt("transactionDetail.dateExpiry", new Date()));
    } else {
        criteria.add(Restrictions.ge("transactionDetail.dateExpiry", new Date()));
    }
    criteria.setProjection(proList);
    List<Object> list = criteria.list();
    Number total = 0;
    if (!CollectionUtils.isEmpty(list)) {
        total = (Number) list.size();
    }
    return total.intValue();
}

From source file:org.openmrs.module.inventory.db.hibernate.HibernateInventoryDAO.java

License:Open Source License

public List<InventoryStoreDrugTransactionDetail> listStoreDrugAvaiable(Integer storeId,
        Collection<Integer> drugs, Collection<Integer> formulations) throws DAOException {
    Criteria criteria = sessionFactory.getCurrentSession()
            .createCriteria(InventoryStoreDrugTransactionDetail.class, "transactionDetail")
            .createAlias("transactionDetail.transaction", "transaction")
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

    ProjectionList proList = Projections.projectionList();
    proList.add(Projections.groupProperty("drug")).add(Projections.groupProperty("formulation"))
            .add(Projections.sum("currentQuantity"));
    criteria.add(Restrictions.eq("transaction.store.id", storeId));
    if (drugs != null) {
        criteria.createCriteria("transactionDetail.drug", Criteria.INNER_JOIN)
                .add(Restrictions.in("id", drugs));
    }//from  w  w  w  . j  a v  a  2 s. c  o  m
    criteria.add(Restrictions.eq("transaction.typeTransaction", ActionValue.TRANSACTION[0]));
    if (formulations != null) {
        criteria.createCriteria("transactionDetail.formulation", Criteria.INNER_JOIN)
                .add(Restrictions.in("id", formulations));
    }
    criteria.setProjection(proList);
    criteria.add(Restrictions.ge("transactionDetail.dateExpiry", new Date()));
    List<Object> lst = criteria.list();
    if (lst == null || lst.size() == 0) {
        return null;
    }
    List<InventoryStoreDrugTransactionDetail> list = new ArrayList<InventoryStoreDrugTransactionDetail>();
    // System.out.println("lst size: "+lst.size());
    for (int i = 0; i < lst.size(); i++) {
        Object[] row = (Object[]) lst.get(i);
        InventoryStoreDrugTransactionDetail tDetail = new InventoryStoreDrugTransactionDetail();
        tDetail.setDrug((InventoryDrug) row[0]);
        tDetail.setFormulation((InventoryDrugFormulation) row[1]);
        tDetail.setCurrentQuantity((Integer) row[2]);
        list.add(tDetail);
        // System.out.println("I: "+i+" drug: "+tDetail.getDrug().getName()+" formulation: "+tDetail.getFormulation().getName()+" quantity: "+tDetail.getCurrentQuantity());
    }
    return list;
}