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:org.ims.dao.template.ImsDAOTemplate.java

public List<Map> executeCustomSQL(final String sql) {
    List<Map> data = (List<Map>) getHibernateTemplate().execute(new HibernateCallback() {

        @Override/*from  w w  w  .  j a va2s . c  o  m*/
        public List<Map> doInHibernate(Session sn) throws HibernateException {
            SQLQuery query = sn.createSQLQuery(sql);
            query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
            return (List<Map>) query.list();

        }
    });
    return data;

}

From source file:org.jboss.seam.wiki.plugin.blog.BlogDAO.java

License:LGPL

public List<BlogEntry> findBlogEntriesInDirectory(WikiDirectory startDir, WikiDocument ignoreDoc, Pager pager,
        Integer year, Integer month, Integer day, String tag, boolean countComments) {

    final Map<Long, BlogEntry> blogEntryMap = new HashMap<Long, BlogEntry>();

    StringBuilder queryString = new StringBuilder();
    queryString.append("select").append(" ");
    for (int i = 0; i < getWikiDocumentSQLColumnNames().length; i++) {
        queryString.append(getWikiDocumentSQLColumnNames()[i]);
        if (i != getWikiDocumentSQLColumnNames().length - 1)
            queryString.append(", ");
    }//from   ww  w. ja v a  2s .co m
    queryString.append(", '0' as COMMENT_COUNT").append(" ");
    queryString.append(getblogEntryFromClause(tag));
    queryString.append(getBlogEntryWhereClause(ignoreDoc, year, month, day, tag));

    queryString.append(" ");
    queryString.append("order by doc2.CREATED_ON desc");

    SQLQuery query = getSession().createSQLQuery(queryString.toString());

    bindBlogEntryWhereClause(query, startDir, ignoreDoc, year, month, day, tag);

    query.setComment("Finding all blogEntry documents recursively in dir: " + startDir.getName());
    query.addEntity(WikiDocument.class);
    query.addScalar("COMMENT_COUNT", Hibernate.LONG);
    query.setFirstResult(pager.getQueryFirstResult());
    query.setMaxResults(pager.getQueryMaxResults());

    query.setResultTransformer(new ResultTransformer() {
        public Object transformTuple(Object[] result, String[] aliases) {
            BlogEntry be = new BlogEntry();
            be.setEntryDocument((WikiDocument) result[0]);
            blogEntryMap.put(be.getEntryDocument().getId(), be); // Put in map so we can attach comment count later
            return be;
        }

        public List transformList(List list) {
            return list;
        }
    });

    List<BlogEntry> result = (List<BlogEntry>) query.list();

    if (countComments && result.size() > 0) {
        // The risk here is that pager.getQueryMaxResults() is too large for the IN() operator of some DBs...
        StringBuilder commentQueryString = new StringBuilder();
        commentQueryString.append("select doc.NODE_ID as DOC_ID, count(c3.NODE_ID) as COMMENT_COUNT")
                .append(" ");
        commentQueryString.append("from WIKI_DOCUMENT doc").append(" ");
        commentQueryString.append("left outer join WIKI_NODE c1 on doc.NODE_ID = c1.PARENT_NODE_ID")
                .append(" ");
        commentQueryString.append("left outer join WIKI_COMMENT c2 on c1.NODE_ID = c2.NODE_ID").append(" ");
        commentQueryString.append("left outer join WIKI_COMMENT c3 on c2.NS_THREAD = c3.NS_THREAD").append(" ");
        commentQueryString.append("where doc.NODE_ID in (:blogEntriesIds)").append(" ");
        commentQueryString.append("group by doc.NODE_ID");

        SQLQuery commentQuery = getSession().createSQLQuery(commentQueryString.toString());
        commentQuery.setComment("Finding comment count for blog entries");
        commentQuery.addScalar("DOC_ID");
        commentQuery.addScalar("COMMENT_COUNT");
        commentQuery.setParameterList("blogEntriesIds", blogEntryMap.keySet());

        commentQuery.setResultTransformer(new ResultTransformer() {
            public Object transformTuple(Object[] result, String[] aliases) {
                BlogEntry be = blogEntryMap.get(((BigInteger) result[0]).longValue());
                be.setCommentCount(((BigInteger) result[1]).longValue());
                return null;
            }

            public List transformList(List list) {
                return list;
            }
        });
        commentQuery.list();
    }

    return result;
}

From source file:org.jboss.seam.wiki.plugin.blog.BlogDAO.java

License:LGPL

private List<BlogEntryCount> countBlogEntries(WikiDirectory startDir, WikiDocument ignoreDoc,
        final boolean projectYear, final boolean projectMonth, final boolean projectDay, Integer limitYear,
        Integer limitMonth, Integer limitDay, String tag) {

    // Sanity input check
    if (projectDay && (!projectMonth || !projectYear))
        throw new IllegalArgumentException("Can't project on day without months or year");
    if (projectMonth && !projectYear)
        throw new IllegalArgumentException("Can't project on month without year");

    StringBuilder queryString = new StringBuilder();

    queryString.append("select count(doc.NODE_ID) as NUM_OF_ENTRIES").append(" ");
    if (projectYear)
        queryString.append(", ").append("year(doc2.CREATED_ON) as YEAR");
    if (projectMonth)
        queryString.append(", ").append("month(doc2.CREATED_ON) as MONTH");
    if (projectDay)
        queryString.append(", ").append("day(doc2.CREATED_ON) as DAY");
    queryString.append(" ");

    queryString.append(getblogEntryFromClause(tag));
    queryString.append(getBlogEntryWhereClause(ignoreDoc, limitYear, limitMonth, limitDay, tag));

    if (projectYear || projectMonth || projectDay)
        queryString.append("group by").append(" ");
    if (projectYear)
        queryString.append("year(doc2.CREATED_ON)");
    if (projectMonth)
        queryString.append(", month(doc2.CREATED_ON)");
    if (projectDay)
        queryString.append(", day(doc2.CREATED_ON)");

    if (projectYear || projectMonth || projectDay)
        queryString.append("order by").append(" ");
    if (projectYear)
        queryString.append("YEAR desc");
    if (projectMonth)
        queryString.append(", MONTH desc");
    if (projectDay)
        queryString.append(", DAY desc");

    SQLQuery query = getSession().createSQLQuery(queryString.toString());

    bindBlogEntryWhereClause(query, startDir, ignoreDoc, limitYear, limitMonth, limitDay, tag);

    query.setComment("Finding blogEntry counts");
    query.addScalar("NUM_OF_ENTRIES", Hibernate.LONG);
    if (projectYear)
        query.addScalar("YEAR", Hibernate.INTEGER);
    if (projectMonth)
        query.addScalar("MONTH", Hibernate.INTEGER);
    if (projectDay)
        query.addScalar("DAY", Hibernate.INTEGER);

    query.setResultTransformer(new ResultTransformer() {
        public Object transformTuple(Object[] result, String[] aliases) {
            BlogEntryCount beCount = new BlogEntryCount();
            beCount.setNumOfEntries((Long) result[0]);
            if (projectYear)
                beCount.setYear((Integer) result[1]);
            if (projectMonth)
                beCount.setMonth((Integer) result[2]);
            if (projectDay)
                beCount.setDay((Integer) result[3]);
            return beCount;
        }//from   w  ww .  ja v a2 s . co  m

        public List transformList(List list) {
            return list;
        }
    });

    return (List<BlogEntryCount>) query.list();
}

From source file:org.opnlp.opnlp2.datacontroller.DataController.java

public void loadDataFromDatabase() {
    Session session = HibernateUtil.getSessionFactory().openSession();
    String sql = SQLQuery;/*from   w  ww.  j a  v  a  2  s  . c  o m*/
    SQLQuery query = session.createSQLQuery(sql);
    //        query.addEntity(Poslanik.class);
    query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
    List results = query.list();

    for (Object object : results) {
        Map row = (Map) object;
        DataRow data = new DataRow();
        data.setId((Integer) row.get("ID"));
        data.setTekst(row.get("tekst").toString());
        data.setPoslanik(row.get("Poslanik").toString());
        data.setDatum(row.get("Datum").toString());
        dataset.add(data);

        //            System.out.println("ID: " + row.get("ID") + "Tekst: " + row.get("tekst") + "Poslanik: " + row.get("Poslanik") + "Datum:" + row.get("Datum"));
        //            dataRow = (DataRow) object;
        //            System.out.println(dataRow.getId() + "\t" + dataRow.getTekst()+ "\t" + dataRow.getPoslanik()+ "\t" + dataRow.getDatum());
    }
}

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

License:Open Source License

public <T> T findBySQLQuery(Class<T> returnType, SQLQueryDetails sqlQueryDetails) {

    SQLQuery sqlQuery;

    sqlQuery = constructSQLQuery(sqlQueryDetails);

    if (Durable.class.isAssignableFrom(returnType)) {

        return returnType.cast(sqlQuery.addEntity(returnType).uniqueResult());
    } else if (!SqlType.isKnownType(returnType)) {

        return returnType
                .cast(sqlQuery.setResultTransformer(Transformers.aliasToBean(returnType)).uniqueResult());
    } else {//from  ww w. j a  v a2s .com

        Object obj;

        if ((obj = sqlQuery.uniqueResult()) != null) {

            return returnType.cast(obj);
        }

        return null;
    }
}

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

License:Open Source License

public <T> List<T> listBySQLQuery(Class<T> returnType, SQLQueryDetails sqlQueryDetails) {

    SQLQuery sqlQuery;

    sqlQuery = constructSQLQuery(sqlQueryDetails);

    if (Durable.class.isAssignableFrom(returnType)) {

        return Collections.checkedList(sqlQuery.addEntity(returnType).list(), returnType);
    } else if (!SqlType.isKnownType(returnType)) {

        return Collections.checkedList(
                sqlQuery.setResultTransformer(Transformers.aliasToBean(returnType)).list(), returnType);
    } else {// w w  w .  j  av a 2  s  .c o  m

        LinkedList<T> returnList = new LinkedList<T>();

        for (Object obj : sqlQuery.list()) {
            returnList.add(returnType.cast(obj));
        }

        return returnList;
    }
}

From source file:org.squashtest.tm.service.internal.repository.hibernate.HibernateCampaignLibraryNodeDao.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from w  w  w.j a  v a2 s  .co m
public List<Long> getParentsIds(long entityId) {
    SQLQuery query = currentSession().createSQLQuery(NativeQueries.CLN_FIND_SORTED_PARENT_IDS);
    query.setResultTransformer(new SqLIdResultTransformer());
    query.setParameter(ParameterNames.NODE_ID, entityId, LongType.INSTANCE);
    return query.list();
}

From source file:org.squashtest.tm.service.internal.repository.hibernate.HibernateRequirementDao.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//www. ja v  a2s. c  o  m
public List<Long> findAllRequirementsIdsByLibrary(long libraryId) {
    Session session = currentSession();
    SQLQuery query = session.createSQLQuery(FIND_ALL_FOR_LIBRARY_QUERY);
    query.setParameter("libraryId", libraryId);
    query.setResultTransformer(new SqLIdResultTransformer());
    return query.list();
}

From source file:org.squashtest.tm.service.internal.repository.hibernate.HibernateRequirementLibraryNodeDao.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//  w  ww.  java 2  s  .c  om
public List<Long> getParentsIds(long entityId) {
    SQLQuery query = currentSession().createSQLQuery(NativeQueries.RLN_FIND_SORTED_PARENT_IDS);
    query.setResultTransformer(new SqLIdResultTransformer());
    query.setParameter(ParameterNames.NODE_ID, entityId, LongType.INSTANCE);
    return query.list();
}

From source file:org.yamj.core.hibernate.HibernateDao.java

License:Open Source License

/**
 * Execute a query to return the results
 *
 * Gets the options from the wrapper for start and max
 *
 * Puts the total count returned from the query into the wrapper
 *
 * @param <T>//w ww .  ja  va  2 s . c om
 * @param T The class to return the transformed results of.
 * @param sqlScalars
 * @param wrapper
 * @return
 */
@SuppressWarnings("rawtypes")
public <T> List<T> executeQueryWithTransform(Class T, SqlScalars sqlScalars, IApiWrapper wrapper) {
    SQLQuery query = sqlScalars.createSqlQuery(currentSession());
    query.setReadOnly(true);
    query.setCacheable(true);

    if (T != null) {
        if (T.equals(String.class)) {
            // no transformer needed
        } else if (T.equals(Long.class)) {
            // no transformer needed
        } else if (T.equals(Object[].class)) {
            // no transformer needed
        } else {
            query.setResultTransformer(Transformers.aliasToBean(T));
        }
    }

    // Add the scalars to the query
    sqlScalars.populateScalars(query);

    List<T> queryResults = query.list();

    // If the wrapper is populated, then run the query to get the maximum results
    if (wrapper != null) {
        wrapper.setTotalCount(queryResults.size());

        // If there is a start or max set, we will need to re-run the query after setting the options
        IOptions options = wrapper.getOptions();
        if (options != null) {
            if (options.getStart() > 0 || options.getMax() > 0) {
                if (options.getStart() > 0) {
                    query.setFirstResult(options.getStart());
                }

                if (options.getMax() > 0) {
                    query.setMaxResults(options.getMax());
                }
                // This will get the trimmed list
                queryResults = query.list();
            }
        }
    }

    return queryResults;
}