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.server.core.model.custom.RoomModel.java

public final void updateRoomAndGameStatus() {
    Session session = DataSource.openSession();
    int roomStatus = 0;
    int gameStatus = 0;
    try {//  ww  w .  jav  a2 s  .c  o  m
        roomStatus = (int) session.createCriteria(Roominfo.class)
                .setProjection(Projections.groupProperty("roomStatus")).add(Restrictions.eq("roomId", _roomid))
                .uniqueResult();

        gameStatus = Integer.parseInt(GameResource.bjGameModel.readStringValue("gameStatus"));

    } catch (Exception e) {
        _log.error("roomAndGameStatus:" + e.getMessage());
    }
    session.close();

    if (roomStatus == 1 && gameStatus == 1) {
        _roomAndGameStatus = true;
        return;
    }
    _roomAndGameStatus = false;
}

From source file:org.transitime.reports.RoutePerformanceQuery.java

License:Open Source License

public List<Object[]> query(String agencyId, Date startDate, Date endDate, double allowableEarlyMin,
        double allowableLateMin, String predictionType, String predictionSource) {

    int msecLo = (int) (allowableEarlyMin * 60 * 1000);
    int msecHi = (int) (allowableLateMin * 60 * 1000);

    // Project to: # of predictions in which route is on time / # of predictions
    // for route. This cannot be done with pure Criteria API. This could be
    // moved to a separate class or XML file.
    String sqlProjection = "avg(predictionAccuracyMsecs BETWEEN " + Integer.toString(msecLo) + " AND "
            + Integer.toString(msecHi) + ") AS avgAccuracy";

    try {/*www  . j  a  v  a  2  s  .c om*/
        session = HibernateUtils.getSession(agencyId);

        Projection proj = Projections.projectionList().add(Projections.groupProperty("routeId"), "routeId")
                .add(Projections.sqlProjection(sqlProjection, new String[] { "avgAccuracy" },
                        new Type[] { DoubleType.INSTANCE }), "performance");

        Criteria criteria = session.createCriteria(PredictionAccuracy.class).setProjection(proj)
                .add(Restrictions.between("arrivalDepartureTime", startDate, endDate));

        if (predictionType == PREDICTION_TYPE_AFFECTED)
            criteria.add(Restrictions.eq("affectedByWaitStop", true));
        else if (predictionType == PREDICTION_TYPE_NOT_AFFECTED)
            criteria.add(Restrictions.eq("affectedByWaitStop", false));

        if (predictionSource != "")
            criteria.add(Restrictions.eq("predictionSource", predictionSource));

        criteria.addOrder(Order.desc("performance"));

        criteria.setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP);

        @SuppressWarnings("unchecked")
        List<Object[]> results = criteria.list();

        return results;
    } catch (HibernateException e) {
        logger.error(e.toString());
        return null;
    } finally {
        session.close();
    }
}

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
 * /*from ww w .j av  a2 s  . 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
 * /*from www.  ja  v  a2  s  .  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> 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:ru.trett.cis.DAO.AssetDAOImpl.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public List<ResultMapper> deviceModelGroupAndCount() {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Asset.class);
    return criteria.createAlias("deviceModel", "dm")
            .setProjection(Projections.projectionList().add(Projections.groupProperty("deviceModel.id"))
                    .add(Projections.rowCount(), "data").add(Projections.property("dm.model"), "name"))
            .setResultTransformer(Transformers.aliasToBean(ResultMapper.class)).setCacheable(true).list();
}

From source file:src.dao.VeiculoDAO.java

@SuppressWarnings("unchecked")
/**// www . j av a 2  s .  c om
 *
 * @return List<Usuario>
 *
 * Mtodo retorna uma lista de Marcas
 */
public List<String> listarMarcas() {
    Session sessao = null;
    Transaction transacao = null;
    List resultado = null;
    try {
        //Abre uma sessao no banco de dados
        sessao = HibernateUtil.getSessionFactory().openSession();
        transacao = sessao.beginTransaction();
        resultado = sessao.createCriteria(Veiculo.class)
                .setProjection(Projections.projectionList().add(Projections.groupProperty("marca"))).list();
        //Confirma a transacao
        transacao.commit();
        //retona a lista de marcas
        return resultado;
    } catch (HibernateException e) {
        throw new ExceptionInInitializerError(
                "No foi possvel selecionar os Veiculo.Erro: " + e.getMessage());
    } finally {
        try {
            sessao.close();
        } catch (Throwable e) {
            throw new ExceptionInInitializerError(
                    "Erro ao fechar a operao consulta.Erro: " + e.getMessage());
        }
    }
}

From source file:test.com.heliosapm.aa4h.XMLQueryTest.java

License:Apache License

/**
 * Tests a basic row count with a group by job
 * @throws Exception on any error/*from  www  .  j  a  v  a 2 s. com*/
 */
@Test
public void testEmpCountByJobDept() throws Exception {
    List results = session.createCriteria(Emp.class).createAlias("job", "j").createAlias("dept", "d")
            .setProjection(Projections.projectionList().add(Projections.rowCount(), "empCount")
                    .add(Projections.groupProperty("j.jobName"), "jobid")
                    .add(Projections.groupProperty("d.dname"), "department"))
            .list();
    for (Object o : results) {
        log(o);
    }

    setXmlQuery();
    final List<?> result = XMLQueryParser.execute(xmlQuery, session);
    Assert.assertNotNull("Result was null", result);
    Assert.assertFalse("Result was empty", result.isEmpty());
    for (Object o : result) {
        log(o);
    }
    //final Map<Object, Object> map = jdbcHelper.queryForMap("SELECT JOB_NAME, COUNT(*) FROM EMP E, JOB J WHERE E.JOB_ID = J.JOB_ID GROUP BY JOB_NAME");
    //Assert.assertEquals("Count not [" + jdbcCount + "]", jdbcCount, hCount);
}

From source file:to.etc.domui.hibernate.model.CriteriaCreatingVisitor.java

License:Open Source License

@Override
public void visitPropertySelection(QPropertySelection n) throws Exception {
    String name = parseSubcriteria(n.getProperty());

    switch (n.getFunction()) {
    default:/*from  w w  w.  j ava  2s.com*/
        throw new IllegalStateException("Unexpected selection item function: " + n.getFunction());
    case AVG:
        m_lastProj = Projections.avg(name);
        break;
    case MAX:
        m_lastProj = Projections.max(name);
        break;
    case MIN:
        m_lastProj = Projections.min(name);
        break;
    case SUM:
        m_lastProj = Projections.sum(name);
        break;
    case COUNT:
        m_lastProj = Projections.count(name);
        break;
    case COUNT_DISTINCT:
        m_lastProj = Projections.countDistinct(name);
        break;
    case ID:
        m_lastProj = Projections.id();
        break;
    case PROPERTY:
        m_lastProj = Projections.groupProperty(name);
        break;
    case ROWCOUNT:
        m_lastProj = Projections.rowCount();
        break;
    case DISTINCT:
        m_lastProj = Projections.distinct(Projections.property(name));
        break;
    }
}

From source file:ua.gov.uz.pv.entity.controller.worstKMController.java

public List getWorstPch() {
    List<Deviation> otst;//from www.  j a  va  2  s  . c o m
    otst = (List<Deviation>) session.createCriteria(Deviation.class)
            .add(Restrictions.between("dateMeasuring", getStartDate(), getEndDate()))
            .setFetchMode("direction", FetchMode.JOIN).setFetchMode("railway", FetchMode.JOIN)
            .add(Restrictions.eq("railway.idRailway", selectedRailway))
            .setProjection(Projections.projectionList().add(Projections.groupProperty("direction"))
                    .add(Projections.groupProperty("line")).add(Projections.groupProperty("km"))
                    .add(Projections.groupProperty("m")).add(Projections.rowCount(), "deviation"))
            .list();
    return otst;
}