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.opentaps.financials.domain.ledger.EncumbranceRepository.java

License:Open Source License

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
public BigDecimal getTotalEncumberedValue(String organizationPartyId, Map<String, String> accountingTags,
        Timestamp asOfDate) throws RepositoryException {
    Session session = null;//from  w  w  w .j  a  v  a 2 s.  c om
    BigDecimal encumberedValueTotal = null;

    try {
        session = getInfrastructure().getSession();

        // retrieve max snapshot time under asOfDate
        Criteria lastSnapshotDate = session.createCriteria(EncumbranceSnapshot.class);
        lastSnapshotDate.add(Restrictions.le(EncumbranceSnapshot.Fields.snapshotDatetime.getName(), asOfDate));
        lastSnapshotDate.setProjection(Projections.max(EncumbranceSnapshot.Fields.snapshotDatetime.getName()));
        List<Timestamp> snapshotMaxDate = lastSnapshotDate.list();
        Timestamp ts = snapshotMaxDate.get(0);
        if (ts == null) {
            Debug.logWarning("There is no encumbrance snapshot created before " + asOfDate.toString(), MODULE);
            return null;
        }
        Debug.logInfo("Using encumbrance snapshot from " + ts.toString(), MODULE);

        Criteria snapshot = session.createCriteria(EncumbranceSnapshot.class);
        snapshot.add(Restrictions.eq(EncumbranceSnapshot.Fields.snapshotDatetime.getName(), ts));
        List<EncumbranceSnapshot> snapshots = snapshot.list();

        String snapshotId = snapshots.get(0).getEncumbranceSnapshotId();

        Criteria encumberedValueCriteria = session.createCriteria(EncumbranceDetail.class);
        encumberedValueCriteria.add(Restrictions.eq(
                String.format("id.%1$s", EncumbranceDetail.Fields.encumbranceSnapshotId.getName()),
                snapshotId));
        encumberedValueCriteria.add(
                Restrictions.eq(EncumbranceDetail.Fields.organizationPartyId.getName(), organizationPartyId));
        buildAccountingTagConditions(encumberedValueCriteria, accountingTags);
        encumberedValueCriteria
                .setProjection(Projections.sum(EncumbranceDetail.Fields.encumberedAmount.getName()));
        List<BigDecimal> totals = encumberedValueCriteria.list();
        encumberedValueTotal = totals.get(0);

    } catch (InfrastructureException e) {
        throw new RepositoryException(e.getMessage());
    } catch (HibernateException e) {
        // return the RepositoryException with the message of exception
        throw new RepositoryException(e.getMessage());
    } finally {
        if (session != null) {
            session.close();
        }
    }

    return encumberedValueTotal;
}

From source file:org.sakaiproject.scorm.dao.hibernate.AttemptDaoImpl.java

License:Educational Community License

public Attempt lookupNewest(long contentPackageId, String learnerId) {
    // First figure out the highest attempt nr..
    DetachedCriteria sub = DetachedCriteria.forClass(Attempt.class)
            .add(Restrictions.eq("contentPackageId", contentPackageId))
            .add(Restrictions.eq("learnerId", learnerId)).setProjection(Projections.max("attemptNumber"));
    // Than use it as restriction
    DetachedCriteria criteria = DetachedCriteria.forClass(Attempt.class)
            .add(Restrictions.eq("contentPackageId", contentPackageId))
            .add(Restrictions.eq("learnerId", learnerId)).add(Subqueries.propertyEq("attemptNumber", sub));

    return uniqueResult(criteria);
}

From source file:org.sculptor.framework.accessimpl.jpahibernate.JpaHibFindByConditionStatAccessImpl.java

License:Apache License

private void addStatProjection(Criteria criteria) throws PersistenceException {
    ProjectionList projList = Projections.projectionList();
    projList.add(Projections.rowCount());
    for (ColumnStatRequest<T> column : statRequest) {
        if (column.isFlag(COUNT)) {
            projList.add(Projections.count(column.getColumn().getName()));
        }/* ww w  . j  a v  a2 s  . com*/
        if (column.isFlag(MIN)) {
            projList.add(Projections.min(column.getColumn().getName()));
        }
        if (column.isFlag(MAX)) {
            projList.add(Projections.max(column.getColumn().getName()));
        }
        if (column.isFlag(AVERAGE)) {
            projList.add(Projections.avg(column.getColumn().getName()));
        }
        if (column.isFlag(SUM)) {
            projList.add(Projections.sum(column.getColumn().getName()));
        }
        if (column.isFlag(GROUP_BY_VAL)) {
            projList.add(Projections.groupProperty(column.getColumn().getName()));
        }

        // Time groups
        for (ColumnStatType flag : TIME_GROUPS) {
            if (column.isFlag(flag)) {
                projList.add(makeTimeGroupBy(column, flag, criteria));
            }
        }
    }

    criteria.setProjection(projList);
}

From source file:org.shredzone.cilla.core.repository.impl.PageDaoHibImpl.java

License:Open Source License

@Transactional(readOnly = true)
@Override//from  ww  w. j  a v a  2  s.  c o m
public Date[] fetchMinMaxModification() {
    Date now = new Date();

    Criteria crit = getCurrentSession().createCriteria(Page.class);

    crit.add(Restrictions.and(Restrictions.isNotNull("publication"), Restrictions.le("publication", now)));

    crit.add(Restrictions.or(Restrictions.isNull("expiration"), Restrictions.gt("expiration", now)));

    crit.add(Restrictions.eq("hidden", false));

    ProjectionList proj = Projections.projectionList();
    proj.add(Projections.min(pageOrder.getColumn()));
    proj.add(Projections.max(pageOrder.getColumn()));
    crit.setProjection(proj);
    Object[] row = (Object[]) crit.uniqueResult();

    Date[] result = new Date[2];
    result[0] = (Date) row[0];
    result[1] = (Date) row[1];
    return result;
}

From source file:org.smallmind.persistence.orm.hibernate.HibernateDao.java

License:Open Source License

public I lastId() {

    return findByCriteria(getIdClass(), new CriteriaDetails() {

        @Override//from  w w  w  .jav a 2s .c  o  m
        public Criteria completeCriteria(Criteria criteria) {

            return criteria.setProjection(Projections.max("id"));
        }
    });
}

From source file:org.wise.portal.dao.ideabasket.impl.HibernateIdeaBasketDao.java

License:Open Source License

/**
 * Get all the latest IdeaBaskets with the given run id
 * /*  w  w  w.j  ava 2s .  c  o  m*/
 * we will basically be performing this query
 * select * from vle_database.ideaBasket i where id in(SELECT max(id) FROM vle_database.ideaBasket i where runid=<insert runId> group by workgroupid)
 * 
 * @param runId the id of the run
 * @return all the latest IdeaBaskets for a run id
 */
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
public List<IdeaBasket> getLatestIdeaBasketsForRunId(long runId) {
    Session session = this.getHibernateTemplate().getSessionFactory().getCurrentSession();

    /*
     * create a projection that will give us the latest idea basket id
     * for each workgroup id in the run. the projection will return 
     * an array of array objects that will look like [id, workgroupId].
     * each workgroup id will only appear once.
     */
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.max("id"));
    projectionList.add(Projections.groupProperty("workgroupId"));

    //this first query will filter on the runId and the projection
    List latestIdeaBasketIdsProjection = session.createCriteria(IdeaBasket.class)
            .add(Restrictions.eq("runId", runId)).setProjection(projectionList).list();

    //the list that will contain all the idea basket ids we want
    List<Long> ideaBasketIds = new ArrayList<Long>();

    //loop through all the results from our first query
    for (int x = 0; x < latestIdeaBasketIdsProjection.size(); x++) {
        //get the idea basket id
        Object[] projection = (Object[]) latestIdeaBasketIdsProjection.get(x);
        Long ideaBasketId = (Long) projection[0];
        ideaBasketIds.add(ideaBasketId);
    }

    List<IdeaBasket> result = new ArrayList<IdeaBasket>();

    if (ideaBasketIds.size() > 0) {
        //this second query will retrieve all the idea basket ids we retrieved from the first query
        result = session.createCriteria(IdeaBasket.class).add(createIdOrCriterion(ideaBasketIds, 0)).list();
    }

    return result;
}

From source file:org.wise.portal.dao.ideabasket.impl.HibernateIdeaBasketDao.java

License:Open Source License

/**
 * Get all the latest IdeaBaskets with the given run id
 * //  ww  w  .j  a v  a 2  s.  co  m
 * we will basically be performing this query
 * select * from vle_database.ideaBasket i where id in(SELECT max(id) FROM vle_database.ideaBasket i where runid=<insert runId> and workgroupid in(<insert workgroup ids>) group by workgroupid)
 * 
 * @param runId the id of the run
 * @param workgroupIds a list of workgroup ids
 * @return all the latest IdeaBaskets for a run id
 */
@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
public List<IdeaBasket> getLatestIdeaBasketsForRunIdWorkgroupIds(long runId, List<Long> workgroupIds) {
    Session session = this.getHibernateTemplate().getSessionFactory().getCurrentSession();

    /*
     * create a projection that will give us the latest idea basket id
     * for each workgroup id in the run. the projection will return 
     * an array of array objects that will look like [id, workgroupId].
     * each workgroup id will only appear once.
     */
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.max("id"));
    projectionList.add(Projections.groupProperty("workgroupId"));

    //this first query will filter on the runId and workgroupids and the projection
    List latestIdeaBasketIdsProjection = session.createCriteria(IdeaBasket.class)
            .add(Restrictions.eq("runId", runId)).add(Restrictions.in("workgroupId", workgroupIds))
            .setProjection(projectionList).list();

    //the list that will contain all the idea basket ids we want
    List<Long> ideaBasketIds = new ArrayList<Long>();

    //loop through all the results from our first query
    for (int x = 0; x < latestIdeaBasketIdsProjection.size(); x++) {
        //get the idea basket id
        Object[] projection = (Object[]) latestIdeaBasketIdsProjection.get(x);
        Long ideaBasketId = (Long) projection[0];
        ideaBasketIds.add(ideaBasketId);
    }

    List<IdeaBasket> result = new ArrayList<IdeaBasket>();

    if (ideaBasketIds.size() > 0) {
        //this second query will retrieve all the idea basket ids we retrieved from the first query
        result = session.createCriteria(IdeaBasket.class).add(createIdOrCriterion(ideaBasketIds, 0)).list();
    }

    return result;
}

From source file:pe.gob.mef.gescon.hibernate.impl.ArchivoConocimientoDaoImpl.java

@Override
public TarchivoConocimiento getLastTarchivoByTconocimiento(Tconocimiento tconocimiento) throws Exception {
    DetachedCriteria proj = DetachedCriteria.forClass(TarchivoConocimiento.class);
    proj.setProjection(Projections.max("nversion"));
    DetachedCriteria criteria = DetachedCriteria.forClass(TarchivoConocimiento.class);
    criteria.add(Restrictions.eq("tconocimiento.nconocimientoid", tconocimiento.getNconocimientoid()));
    criteria.add(Property.forName("nversion").eq(proj));
    return (TarchivoConocimiento) DataAccessUtils.uniqueResult(getHibernateTemplate().findByCriteria(criteria));
}

From source file:pe.gob.mef.gescon.hibernate.impl.ArchivoHistorialDaoImpl.java

@Override
public TarchivoHist getLastTarchivoHistByTbaselegalHist(TbaselegalHist tbaselegal) throws Exception {
    DetachedCriteria proj = DetachedCriteria.forClass(TarchivoHist.class);
    proj.setProjection(Projections.max("nversion"));
    DetachedCriteria criteria = DetachedCriteria.forClass(TarchivoHist.class);
    criteria.add(Restrictions.eq("nhistorialid", tbaselegal.getNhistorialid()));
    criteria.add(Restrictions.eq("nbaselegalid", tbaselegal.getNbaselegalid()));
    criteria.add(Property.forName("nversion").eq(proj));
    return (TarchivoHist) DataAccessUtils.uniqueResult(getHibernateTemplate().findByCriteria(criteria));
}

From source file:pe.gob.mef.gescon.hibernate.impl.BaseLegalHistorialDaoImpl.java

@Override
public TbaselegalHist getLastThistorialByTbaselegal(BigDecimal idbaselegal) throws Exception {
    DetachedCriteria proj = DetachedCriteria.forClass(TbaselegalHist.class);
    proj.setProjection(Projections.max("nversion"));
    proj.add(Restrictions.eq("nbaselegalid", idbaselegal));
    DetachedCriteria criteria = DetachedCriteria.forClass(TbaselegalHist.class);
    criteria.add(Restrictions.eq("nbaselegalid", idbaselegal));
    criteria.add(Property.forName("nversion").eq(proj));
    return (TbaselegalHist) DataAccessUtils.uniqueResult(getHibernateTemplate().findByCriteria(criteria));
}