Example usage for org.hibernate SQLQuery uniqueResult

List of usage examples for org.hibernate SQLQuery uniqueResult

Introduction

In this page you can find the example usage for org.hibernate SQLQuery uniqueResult.

Prototype

R uniqueResult();

Source Link

Document

Convenience method to return a single instance that matches the query, or null if the query returns no results.

Usage

From source file:org.apache.usergrid.apm.service.SessionDBServiceImpl.java

License:Apache License

@Override
public Long getCompactSessionMetricsRowCount() {
    String query = "SELECT MAX(id) from COMPACT_SESSION_METRICS";
    Transaction transaction = null;/*w w  w.  j a  v a2 s.  c o m*/
    Session session = null;
    try {
        session = ServiceFactory.getAnalyticsHibernateSession();
        transaction = session.beginTransaction();
        SQLQuery sqlquery = session.createSQLQuery(query);

        Number number = (Number) sqlquery.uniqueResult();
        transaction.commit();
        if (number != null)
            return number.longValue();
        else
            return 0L;
    } catch (HibernateException e) {
        e.printStackTrace();
        log.error("Problem getting Compact Session Metrics Count");
        throw new HibernateException("Cannot get compact session metrics. ", e);
    }

}

From source file:org.apache.usergrid.apm.service.SessionDBServiceImpl.java

License:Apache License

@Override
public Long getSummarySessionMetricsRowCountByApp(Long appId) {
    String query = "SELECT COUNT(*) from SUMMARY_SESSION_METRICS as t where t.appId = :appId";
    Transaction transaction = null;/*from   w  ww.java 2  s  .c  o  m*/
    Session session = null;
    Long totalCount = 0L;
    try {
        session = ServiceFactory.getAnalyticsHibernateSession();
        transaction = session.beginTransaction();
        SQLQuery sqlquery = session.createSQLQuery(query);
        sqlquery.setParameter("appId", appId);
        totalCount = ((Number) sqlquery.uniqueResult()).longValue();
        transaction.commit();
    } catch (HibernateException e) {
        e.printStackTrace();
        transaction.rollback();
        throw new HibernateException("Cannot get client session metrics. ", e);
    }

    return totalCount;

}

From source file:org.apache.usergrid.apm.service.SessionDBServiceImpl.java

License:Apache License

@Override
public Long getClientSessionMetricsRowCount() {

    String query = "SELECT MAX(id) from CLIENT_SESSION_METRICS";
    Transaction transaction = null;//from   ww  w.java2  s .  co  m
    Session session = null;
    try {
        session = ServiceFactory.getAnalyticsHibernateSession();
        transaction = session.beginTransaction();
        SQLQuery sqlquery = session.createSQLQuery(query);
        Number number = (Number) sqlquery.uniqueResult();
        transaction.commit();
        if (number != null)
            return number.longValue();
        else
            return 0L;
    } catch (HibernateException e) {
        e.printStackTrace();
        log.error("Problem getting Client Session Metrics Count");
        transaction.rollback();
        throw new HibernateException("Cannot get client session metrics. ", e);
    }
    /*
    Session s = ServiceFactory.getAnalyticsHibernateSession();
    Transaction t = s.beginTransaction();
    Number count = (Number)s.createCriteria(ClientSessionMetrics.class).    
    setProjection(Projections.rowCount()).uniqueResult();
    t.commit();
    log.info("available row count for Client Session Metrics is = " + (count!=null?count.intValue():count));
    return count != null ? count.intValue() : 0;
     */
}

From source file:org.apache.usergrid.apm.service.SessionDBServiceImpl.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public AggregatedSessionData getAggreateSessionData(SessionChartCriteria chartCriteria)
        throws HibernateException {
    String query = "SELECT count(*)  as totalSessions, count(distinct deviceId) as totalUniqueUsers,"
            + " avg(sessionLength) as avgSessionLength FROM SUMMARY_SESSION_METRICS "
            + SessionMetricsChartUtil.getWhereClauseForAggregateSessionData(chartCriteria);

    log.info("Aggregated session data query is " + query);
    Session session = null;//from   www .  ja  va2 s .c o  m
    Transaction transaction = null;
    try {
        session = ServiceFactory.getAnalyticsHibernateSession();
        transaction = session.beginTransaction();
        SQLQuery sqlquery = session.createSQLQuery(query);
        sqlquery.setResultTransformer(Transformers.aliasToBean(AggregatedSessionData.class));
        AggregatedSessionData data = (AggregatedSessionData) sqlquery.uniqueResult();
        transaction.commit();
        log.info("aggregated session data " + data.toString());

        /*//List<Long> results = (List<Long>) sqlquery.list();
        Object[] rawResult = (Object[]) sqlquery.uniqueResult();
        log.info("there should be 3 columns returned " + rawResult.length);
        AggregatedSessionData data = new AggregatedSessionData();
        data.setTotalSessions( ((BigInteger) rawResult[0]).longValue());
        data.setTotalUniqueUsers(((BigInteger)rawResult[1]).longValue());
        data.setAvgSessionLength(((BigDecimal) rawResult[2]).longValue());*/
        return data;

    } catch (HibernateException e) {
        e.printStackTrace();
        transaction.rollback();
        throw new HibernateException("Cannot get aggregated data from summary session metrics. ", e);
    }

}

From source file:org.b3mn.poem.Structure.java

License:Open Source License

public static Structure instance(int owner_id, String hierarchy) {
    Structure structure = null;//from w  w  w  .j  a  va  2s.  com
    SQLQuery query = Persistance.getSession().createSQLQuery("select * from ensure_descendant(:hierarchy,:id)")
            .addEntity("structure", Structure.class);
    query.setString("hierarchy", hierarchy);
    query.setInteger("id", owner_id);
    try {
        structure = (Structure) query.uniqueResult();
    } catch (Exception e) {
        e.printStackTrace();
    }
    Persistance.commit();
    return structure;
}

From source file:org.caisi.dao.BedProgramDao.java

License:Open Source License

public String[] getProgramInfo(int programId) {
    String[] result = new String[3];

    SQLQuery query = getSession()
            .createSQLQuery("SELECT name,address,phone,fax from program where id=" + programId);
    query.addScalar("name", Hibernate.STRING);
    query.addScalar("address", Hibernate.STRING);
    query.addScalar("phone", Hibernate.STRING);
    query.addScalar("fax", Hibernate.STRING);
    Object[] o = (Object[]) query.uniqueResult();
    if (o != null) {
        result[0] = new String(o[0] + "\n" + o[1]);
        result[1] = (String) o[2];
        result[2] = (String) o[3];
    }/*from   www .j av a 2 s.  c  om*/
    return result;
}

From source file:org.egov.pgr.dashboard.repository.DashboardRepository.java

License:Open Source License

public Object[] fetchComplaintAgeing(final String querykey, final String wardName) {
    final SQLQuery qry = getQuery(querykey);
    final DateTime currentDate = new DateTime();
    qry.setParameter("grtthn90", endOfGivenDate(currentDate.minusDays(90)).toDate());
    qry.setParameter("lsthn90", endOfGivenDate(currentDate.minusDays(90)).toDate());
    qry.setParameter("grtthn45", endOfGivenDate(currentDate.minusDays(45)).toDate());
    qry.setParameter("grtthn15", endOfGivenDate(currentDate.minusDays(15)).toDate());
    qry.setParameter("lsthn45", endOfGivenDate(currentDate.minusDays(45)).toDate());
    qry.setParameter("lsthn15", endOfGivenDate(currentDate.minusDays(15)).toDate());
    qry.setParameter("currdate", endOfGivenDate(currentDate).toDate());
    if (wardName != null)
        qry.setParameter("wardName", wardName);
    return (Object[]) qry.uniqueResult();
}

From source file:org.egov.wtms.application.service.DefaultersWTReportService.java

License:Open Source License

public long getTotalCount(final String fromAmount, final String toAmount, final String ward)
        throws ParseException {

    StringBuilder queryStr = new StringBuilder();
    queryStr = queryStr.append("select count(dcbinfo.hscno) from egwtr_mv_dcb_view dcbinfo").append(
            " INNER JOIN eg_boundary wardboundary on dcbinfo.wardid = wardboundary.id INNER JOIN eg_boundary localboundary")
            .append(" on dcbinfo.locality = localboundary.id");
    if (Double.parseDouble(toAmount) == 0)
        queryStr.append(" where dcbinfo.arr_balance+dcbinfo.curr_balance >=" + fromAmount);
    else//from ww  w.j av a2 s.com
        queryStr.append(" where dcbinfo.arr_balance+dcbinfo.curr_balance >=" + fromAmount
                + " and dcbinfo.arr_balance+dcbinfo.curr_balance <=" + toAmount);
    queryStr.append(" and dcbinfo.connectionstatus = '" + ConnectionStatus.ACTIVE.toString() + "'");
    if (ward != null && !ward.isEmpty())
        queryStr.append(" and wardboundary.id = '" + ward + "'");
    final SQLQuery finalQuery = getCurrentSession().createSQLQuery(queryStr.toString());
    final Long count = ((BigInteger) finalQuery.uniqueResult()).longValue();
    return count;
}

From source file:org.egov.wtms.application.service.DefaultersWTReportService.java

License:Open Source License

public long getTotalCountFromLimit(final String fromAmount, final String toAmount, final String ward,
        final String topDefaulters) throws ParseException {

    StringBuilder queryStr = new StringBuilder();
    queryStr = queryStr.append("select count(*) from (select * from egwtr_mv_dcb_view dcbinfo").append(
            " INNER JOIN eg_boundary wardboundary on dcbinfo.wardid = wardboundary.id INNER JOIN eg_boundary localboundary")
            .append(" on dcbinfo.locality = localboundary.id");
    if (Double.parseDouble(toAmount) == 0)
        queryStr.append(" where dcbinfo.arr_balance+dcbinfo.curr_balance >=" + fromAmount);
    else//from w w  w.ja  v a  2  s .c  o m
        queryStr.append(" where dcbinfo.arr_balance+dcbinfo.curr_balance >=" + fromAmount
                + " and dcbinfo.arr_balance+dcbinfo.curr_balance <=" + toAmount);
    queryStr.append(" and dcbinfo.connectionstatus = '" + ConnectionStatus.ACTIVE.toString() + "'");
    if (ward != null && !ward.isEmpty())
        queryStr.append(" and wardboundary.id = '" + ward + "'");
    if (!topDefaulters.isEmpty())
        queryStr.append(" limit " + topDefaulters);
    queryStr.append(") as count");
    final SQLQuery finalQuery = getCurrentSession().createSQLQuery(queryStr.toString());
    final Long count = ((BigInteger) finalQuery.uniqueResult()).longValue();
    return count;
}

From source file:org.generationcp.middleware.dao.dms.DmsProjectDao.java

License:Open Source License

public StudyMetadata getStudyMetadataForGeolocationId(final Integer geolocationId) {
    Preconditions.checkNotNull(geolocationId);
    try {//w  w  w. j  a  va  2s.co m
        final SQLQuery query = this.getSession()
                .createSQLQuery(DmsProjectDao.GET_STUDY_METADATA_BY_GEOLOCATION_ID);
        query.addScalar("studyDbId");
        query.addScalar("trialOrNurseryId");
        query.addScalar("studyName");
        query.addScalar("studyType");
        query.addScalar("seasonId");
        query.addScalar("trialDbId");
        query.addScalar("trialName");
        query.addScalar("startDate");
        query.addScalar("endDate");
        query.addScalar("deleted");
        query.addScalar("locationID");
        query.setParameter("geolocationId", geolocationId);
        final Object result = query.uniqueResult();
        if (result != null) {
            final Object[] row = (Object[]) result;
            final StudyMetadata studyMetadata = new StudyMetadata();
            studyMetadata.setStudyDbId(geolocationId);
            studyMetadata.setNurseryOrTrialId((row[1] instanceof Integer) ? (Integer) row[1] : null);
            studyMetadata.setStudyName((row[2] instanceof String) ? (String) row[2] : null);
            studyMetadata.setStudyType((row[3] instanceof Integer) ? ((Integer) row[3]).toString() : null);
            if (row[4] instanceof String && !StringUtils.isBlank((String) row[4])) {
                studyMetadata.addSeason(TermId.getById(Integer.parseInt((String) row[4])).toString());
            }
            studyMetadata.setTrialDbId((row[5] instanceof Integer) ? (Integer) row[5] : null);
            studyMetadata.setTrialName((row[6] instanceof String) ? (String) row[6] : null);
            studyMetadata.setStartDate((row[7] instanceof String) ? (String) row[7] : null);
            studyMetadata.setEndDate((row[8] instanceof String) ? (String) row[8] : null);
            studyMetadata.setActive(Boolean.FALSE.equals(row[9]));
            studyMetadata
                    .setLocationId((row[10] instanceof String) ? Integer.parseInt((String) row[10]) : null);
            return studyMetadata;
        } else {
            return null;
        }
    } catch (final HibernateException e) {
        final String message = "Error with getStudyMetadataForGeolocationId() query from study with geoloCationId: "
                + geolocationId;
        DmsProjectDao.LOG.error(message, e);
        throw new MiddlewareQueryException(message, e);
    }
}