Example usage for org.hibernate SQLQuery setResultTransformer

List of usage examples for org.hibernate SQLQuery setResultTransformer

Introduction

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

Prototype

@Deprecated
Query<R> setResultTransformer(ResultTransformer transformer);

Source Link

Document

Set a strategy for handling the query results.

Usage

From source file:net.lc4ever.framework.activiti.engine.impl.AbstractNativeQueryHibernate.java

License:Open Source License

/**
 * @see org.activiti.engine.query.NativeQuery#list()
 *//*  w  ww . j a va  2  s  .  com*/
@Override
public List<U> list() {
    return crudService.callback(new HibernateCallback<List<U>>() {
        @SuppressWarnings("unchecked")
        @Override
        public List<U> doInHibernate(final Session session) throws HibernateException, SQLException {
            SQLQuery query = session.createSQLQuery(selectClause);
            if (parameters != null) {
                for (Map.Entry<String, Object> entry : parameters.entrySet()) {
                    query.setParameter(entry.getKey(), entry.getValue());
                }
            }
            if (resultTransformer != null)
                query.setResultTransformer(resultTransformer);
            return query.list();
        }
    });
}

From source file:net.lc4ever.framework.activiti.engine.impl.AbstractNativeQueryHibernate.java

License:Open Source License

/**
 * @see org.activiti.engine.query.NativeQuery#listPage(int, int)
 *///from  w ww  .j a v a  2s.c  o  m
@Override
public List<U> listPage(final int firstResult, final int maxResults) {
    return crudService.callback(new HibernateCallback<List<U>>() {
        @SuppressWarnings("unchecked")
        @Override
        public List<U> doInHibernate(final Session session) throws HibernateException, SQLException {
            SQLQuery query = session.createSQLQuery(selectClause);
            if (parameters != null) {
                for (Map.Entry<String, Object> entry : parameters.entrySet()) {
                    query.setParameter(entry.getKey(), entry.getValue());
                }
            }
            if (resultTransformer != null)
                query.setResultTransformer(resultTransformer);
            query.setFirstResult(firstResult);
            query.setMaxResults(maxResults);
            return query.list();
        }
    });
}

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

License:Apache License

@SuppressWarnings("unchecked")
public List<CompactClientLog> getNewCompactClientLogUsingNativeSqlQuery(LogChartCriteria cq) {
    SqlOrderGroupWhere og = LogChartUtil.getOrdersAndGroupings(cq);

    //String query = "SELECT * FROM COMPACT_CLIENT_LOG where " + og.whereClause +
    //" group by " + og.groupBy + " order by " + og.orderBy;
    String query = "SELECT sum(assertCount) as assertCount, sum(debugCount) as debugCount,"
            + " sum(errorAndAboveCount) as errorAndAboveCount, sum(errorCount) as errorCount, sum(infoCount) as infoCount,"
            + "sum(verboseCount) as verboseCount, sum(warnCount) as warnCount, sum(crashCount) as crashCount,"
            + " endMinute, endHour, endDay, endWeek,endMonth, devicePlatform,appConfigType, applicationVersion,deviceModel,deviceOperatingSystem,networkCarrier,networkType "
            + " FROM COMPACT_CLIENT_LOG where " + og.whereClause + " group by " + og.groupBy + " order by "
            + og.orderBy;/*from w ww.  j av  a  2 s . co m*/

    Session session = null;
    Transaction transaction = null;
    List<CompactClientLog> returnList = null;
    try {
        session = ServiceFactory.getAnalyticsHibernateSession();
        transaction = session.beginTransaction();
        SQLQuery sqlquery = session.createSQLQuery(query).addScalar("assertCount", Hibernate.LONG)
                .addScalar("debugCount", Hibernate.LONG).addScalar("errorAndAboveCount", Hibernate.LONG)
                .addScalar("errorCount", Hibernate.LONG).addScalar("infoCount", Hibernate.LONG)
                .addScalar("verboseCount", Hibernate.LONG).addScalar("warnCount", Hibernate.LONG)
                .addScalar("crashCount", Hibernate.LONG).addScalar("endMinute", Hibernate.LONG)
                .addScalar("endHour", Hibernate.LONG).addScalar("endDay", Hibernate.LONG)
                .addScalar("endWeek", Hibernate.LONG).addScalar("endMonth", Hibernate.LONG)
                .addScalar("devicePlatform").addScalar("deviceOperatingSystem").addScalar("appConfigType")//Hibernate.custom(com.ideawheel.portal.model.String.class))
                .addScalar("applicationVersion").addScalar("deviceModel").addScalar("networkCarrier")
                .addScalar("networkType");

        sqlquery.setResultTransformer(Transformers.aliasToBean(CompactClientLog.class));
        returnList = (List<CompactClientLog>) sqlquery.list();
        transaction.commit();

    } catch (HibernateException e) {
        e.printStackTrace();
        transaction.rollback();
        throw new HibernateException("Cannot get compact client logs. ", e);
    }
    return returnList;

}

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

License:Apache License

@SuppressWarnings("unchecked")
public List<CompactNetworkMetrics> getCompactNetworkMetricsUsingNativeSqlQuery(MetricsChartCriteria cq) {

    SqlOrderGroupWhere og = NetworkMetricsChartUtil.getOrdersAndGroupings(cq);

    String query = "SELECT sum(numSamples) as numSamples, sum(numErrors) as numErrors,"
            + " sum(sumLatency) as sumLatency, max(maxLatency) as maxLatency, min(minLatency) as minLatency,"
            + " sum(sumServerLatency) as sumServerLatency, max(maxServerLatency) as maxServerLatency, min(minServerLatency) as minServerLatency,"
            + " endMinute, endHour, endDay, endWeek,endMonth, devicePlatform,appConfigType, applicationVersion,deviceModel,deviceOperatingSystem,networkCarrier,networkType,domain "
            + " FROM COMPACT_NETWORK_METRICS where " + og.whereClause + " group by " + og.groupBy + " order by "
            + og.orderBy;/*from  w  ww .  j a  va2s .c  o  m*/

    Session session = null;
    Transaction transaction = null;
    List<CompactNetworkMetrics> returnList = null;
    try {
        session = ServiceFactory.getAnalyticsHibernateSession();
        transaction = session.beginTransaction();
        SQLQuery sqlquery = session.createSQLQuery(query).addScalar("numSamples", Hibernate.LONG)
                .addScalar("numErrors", Hibernate.LONG).addScalar("sumLatency", Hibernate.LONG)
                .addScalar("maxLatency", Hibernate.LONG).addScalar("minLatency", Hibernate.LONG)
                .addScalar("sumServerLatency", Hibernate.LONG).addScalar("maxServerLatency", Hibernate.LONG)
                .addScalar("minServerLatency", Hibernate.LONG).addScalar("endMinute", Hibernate.LONG)
                .addScalar("endHour", Hibernate.LONG).addScalar("endDay", Hibernate.LONG)
                .addScalar("endWeek", Hibernate.LONG).addScalar("endMonth", Hibernate.LONG)
                .addScalar("devicePlatform").addScalar("appConfigType")//Hibernate.custom(com.ideawheel.portal.model.String.class))
                .addScalar("applicationVersion").addScalar("deviceModel").addScalar("deviceOperatingSystem")
                .addScalar("networkCarrier").addScalar("networkType").addScalar("domain");

        sqlquery.setResultTransformer(Transformers.aliasToBean(CompactNetworkMetrics.class));
        returnList = (List<CompactNetworkMetrics>) sqlquery.list();
        transaction.commit();

    } catch (HibernateException e) {
        transaction.rollback();
        e.printStackTrace();
        throw new HibernateException("Cannot get compact network metrics ", e);
    }
    return returnList;

}

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

License:Apache License

@SuppressWarnings("unchecked")
@Override//from www .  j  a v a2 s  . c  o m
public List<CompactSessionMetrics> getNewCompactSessionMetricsUsingNativeSqlQuery(SessionChartCriteria cq) {
    SqlOrderGroupWhere og = SessionMetricsChartUtil.getOrdersAndGroupings(cq);

    //String query = "SELECT * FROM COMPACT_SESSION_METRICS where " + og.whereClause +
    //" group by " + og.groupBy + " order by " + og.orderBy;

    String query = "SELECT sum(sessionCount) as sessionCount, sum(numUniqueUsers) as numUniqueUsers,"
            + " sum(sumSessionLength) as sumSessionLength, "
            + " endMinute, endHour, endDay,endWeek,endMonth, devicePlatform,CONFIG_TYPE as appConfigType, applicationVersion,deviceModel,deviceOperatingSystem,networkCarrier,networkType "
            + " FROM COMPACT_SESSION_METRICS where " + og.whereClause + " group by " + og.groupBy + " order by "
            + og.orderBy;

    log.info("Getting compact session metrics with query " + query);

    Session session = null;
    Transaction transaction = null;
    List<CompactSessionMetrics> returnList = null;
    try {
        session = ServiceFactory.getAnalyticsHibernateSession();
        transaction = session.beginTransaction();
        SQLQuery sqlquery = session.createSQLQuery(query).addScalar("sessionCount", Hibernate.LONG)
                .addScalar("numUniqueUsers", Hibernate.LONG).addScalar("sumSessionLength", Hibernate.LONG)
                .addScalar("endMinute", Hibernate.LONG).addScalar("endHour", Hibernate.LONG)
                .addScalar("endDay", Hibernate.LONG).addScalar("endWeek", Hibernate.LONG)
                .addScalar("endMonth", Hibernate.LONG).addScalar("devicePlatform").addScalar("appConfigType")//Hibernate.custom(com.ideawheel.portal.model.String.class))        
                .addScalar("applicationVersion").addScalar("deviceModel").addScalar("deviceOperatingSystem")
                .addScalar("networkCarrier").addScalar("networkType");

        sqlquery.setResultTransformer(Transformers.aliasToBean(CompactSessionMetrics.class));
        returnList = (List<CompactSessionMetrics>) sqlquery.list();
        transaction.commit();

    } catch (HibernateException e) {
        e.printStackTrace();
        transaction.rollback();
        throw new HibernateException("Cannot get compact session metrics. ", e);
    }
    return returnList;

}

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 w w w.j av a 2  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.apache.usergrid.apm.service.SessionDBServiceImpl.java

License:Apache License

@SuppressWarnings("unchecked")
@Override/*from  w  w  w.j  av  a 2 s  .  c om*/
public List<CompactSessionMetrics> getSessionChartDataForHourlyGranularity(SessionChartCriteria cq) {
    SqlOrderGroupWhere og = SessionMetricsChartUtil.getOrdersAndGroupingsForSummarySessionMetrics(cq);

    /*query will be ultimately of following form. We are using endMinute on where clause because that's where index exists.
            
    SELECT count(*) as numSession, avg(sessionLength) as sesLen, deviceModel,endHour FROM instaops_analytics.SUMMARY_SESSION_METRICS 
    where appId=3 and endMinute > 22516200 and endMinute < 22520040 
    group by endHour,deviceModel order by endHour,deviceModel asc;*/

    String query = "SELECT count(*) as sessionCount, avg(sessionLength) as sumSessionLength,"
            + "endHour,deviceModel,devicePlatform,deviceOperatingSystem, CONFIG_TYPE as appConfigType, "
            + "applicationVersion,networkCarrier,networkType " + " FROM SUMMARY_SESSION_METRICS where "
            + og.whereClause + " group by " + og.groupBy + " order by " + og.orderBy;

    log.info("Getting summary session metrics with query " + query);

    Session session = null;
    Transaction transaction = null;
    try {
        session = ServiceFactory.getAnalyticsHibernateSession();
        transaction = session.beginTransaction();
        SQLQuery sqlquery = session.createSQLQuery(query).addScalar("sessionCount", Hibernate.LONG)
                .addScalar("sumSessionLength", Hibernate.LONG).addScalar("endHour", Hibernate.LONG)
                .addScalar("deviceModel").addScalar("devicePlatform").addScalar("deviceOperatingSystem")
                .addScalar("appConfigType")//Hibernate.custom(com.ideawheel.portal.model.String.class))        
                .addScalar("applicationVersion").addScalar("networkCarrier").addScalar("networkType");
        sqlquery.setResultTransformer(Transformers.aliasToBean(CompactSessionMetrics.class));
        List<CompactSessionMetrics> returnList = (List<CompactSessionMetrics>) sqlquery.list();
        transaction.commit();
        return returnList;

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

}

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

License:Apache License

@SuppressWarnings("unchecked")
@Override//from  w  ww .ja  v a2  s.c  om
public List<AttributeValueChartData> getCountFromSummarySessionMetrics(SessionChartCriteria cq)
        throws HibernateException {

    //Index on SummarySessionMetrics is on columns appId, endMinute
    String columnName = SessionMetricsChartUtil.getColumnName(cq);
    Long startMinuteValue = cq.getStartDate().getTime() / 1000 / 60;
    Long endMinuteValue = cq.getEndDate().getTime() / 1000 / 60;

    String query = "SELECT " + columnName + " as attribute , count(*)  as value FROM SUMMARY_SESSION_METRICS "
            + " where appId = " + cq.getAppId() + " and endMinute >= " + startMinuteValue + " and endMinute <= "
            + endMinuteValue + " group by attribute order by value desc";

    log.info("Query for SummarySessionMetrics table is " + query);
    Session session = null;
    Transaction transaction = null;
    try {
        session = ServiceFactory.getAnalyticsHibernateSession();
        transaction = session.beginTransaction();
        SQLQuery sqlquery = session.createSQLQuery(query).addScalar("attribute", Hibernate.STRING)
                .addScalar("value", Hibernate.LONG);
        sqlquery.setResultTransformer(Transformers.aliasToBean(AttributeValueChartData.class));
        List<AttributeValueChartData> result = (List<AttributeValueChartData>) sqlquery.list();
        transaction.commit();
        return result;

    } catch (HibernateException e) {
        e.printStackTrace();
        transaction.rollback();
        throw new HibernateException("Cannot get total count for column " + columnName, e);
    }

}

From source file:org.conventionsframework.dao.impl.BaseHibernateDaoImpl.java

License:Apache License

/**
 *
 * @param nativeQuery//  www .  j  av  a 2 s  .  c o m
 * @param params
 * @param class entity to be queried, if no entity is passed persistentClass
 * will be used
 * @param result transformer
 * @param Scalar
 * @return
 */
@Override
public List findByNativeQuery(String nativeQuery, Map params, Class entity, ResultTransformer rt,
        ScalarReturn scalar) {
    SQLQuery query = getSession().createSQLQuery(nativeQuery);
    if (scalar != null) {
        query.addScalar(scalar.getColumnAlias(), scalar.getType());
    }
    if (rt != null) {
        query.setResultTransformer(rt);
    }
    if (entity != null) {
        query.addEntity(entity);
    } else {
        query.addEntity(getPersistentClass());
    }

    Set<Map.Entry> rawParameters = params.entrySet();
    for (Map.Entry entry : rawParameters) {
        query.setParameter(entry.getKey().toString(), entry.getValue());
    }
    return query.list();
}

From source file:org.ednovo.gooru.infrastructure.persistence.hibernate.resource.ResourceRepositoryHibernate.java

License:Open Source License

@SuppressWarnings("rawtypes")
@Override//from ww  w  . jav a  2s  . com
public List getResourceFlatten(List<Long> contentIds) {

    String contentIdsJoined = StringUtils.join(contentIds, ",");
    String sql = "SELECT vrm.*, vrcd.*, vrsd.scollection_gooru_oids, vrcf.* from v_resource_meta vrm left join v_resource_coll_data vrcd on vrcd.content_id = vrm.id left join v_resource_scoll_data vrsd on vrsd.resource_id = vrm.id left outer join v_resource_cust_fields vrcf on vrcf.custom_fields_content_id = vrm.id where vrm.id in ("
            + contentIdsJoined + ")";
    SQLQuery query = getSession().createSQLQuery(sql);
    query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
    return query.list();
}