Example usage for org.hibernate Query setResultTransformer

List of usage examples for org.hibernate Query setResultTransformer

Introduction

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

Prototype

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

Source Link

Document

Set a strategy for handling the query results.

Usage

From source file:onl.netfishers.netshot.RestService.java

License:Open Source License

/**
 * Gets the group devices.//from  w  w  w.jav a  2 s . co  m
 *
 * @param request the request
 * @param id the id
 * @return the group devices
 * @throws WebApplicationException the web application exception
 */
@GET
@Path("devices/group/{id}")
@RolesAllowed("readonly")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<RsLightDevice> getGroupDevices(@PathParam("id") Long id) throws WebApplicationException {
    logger.debug("REST request, get devices from group {}.", id);
    Session session = Database.getSession();
    DeviceGroup group;
    try {
        group = (DeviceGroup) session.get(DeviceGroup.class, id);
        if (group == null) {
            logger.error("Unable to find the group {}.", id);
            throw new NetshotBadRequestException("Can't find this group",
                    NetshotBadRequestException.NETSHOT_INVALID_GROUP);
        }
        Query query = session.createQuery(
                RestService.DEVICELIST_BASEQUERY + "from Device d join d.ownerGroups g where g.id = :id")
                .setLong("id", id);
        @SuppressWarnings("unchecked")
        List<RsLightDevice> devices = query.setResultTransformer(Transformers.aliasToBean(RsLightDevice.class))
                .list();
        return devices;
    } catch (HibernateException e) {
        logger.error("Unable to fetch the devices of group {}.", id, e);
        throw new NetshotBadRequestException("Unable to fetch the devices",
                NetshotBadRequestException.NETSHOT_DATABASE_ACCESS_ERROR);
    } finally {
        session.close();
    }
}

From source file:Operaciones.Destajo.java

public void buscaDestajos() {
    String consulta = "select id_destajo, fecha_destajo, avance, importe, notas from destajo where id_orden="
            + ord + " and especialidad='" + this.global + "' order by id_destajo asc;";
    Session session = HibernateUtil.getSessionFactory().openSession();
    try {/*w ww  .jav a 2s  .com*/
        Query q = session.createSQLQuery(consulta);
        q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
        List resultList = q.list();
        model.setRowCount(0);
        for (Object o : resultList) {
            java.util.HashMap respuesta = (java.util.HashMap) o;
            Object[] renglon = new Object[19];
            //Orden actor = (Orden) o;
            renglon[0] = respuesta.get("id_destajo");
            renglon[1] = respuesta.get("fecha_destajo");
            renglon[2] = respuesta.get("avance");
            renglon[3] = respuesta.get("importe");
            renglon[4] = respuesta.get("notas");
            model.addRow(renglon);
        }
        resultList = null;
    } catch (Exception e) {
        System.out.println(e);
    }
    if (session != null)
        if (session.isOpen())
            session.close();
}

From source file:org.apache.abdera.protocol.server.adapters.hibernate.HibernateCollectionAdapter.java

License:Apache License

@Override
public Entry getEntry(Object entryId) throws Exception {
    Session session = getSessionFactory().openSession();

    Query query = session.getNamedQuery(config.getFeedId() + "-get-entry");
    query.setParameter("id", entryId);
    query.setResultTransformer(new AtomEntryResultTransformer(
            config.getServerConfiguration().getServerUri() + "/" + config.getFeedId(), getAbdera(), null));

    Entry entry = (Entry) query.uniqueResult();

    session.close();/*  ww  w .  ja v a2 s  .c  o m*/
    return entry;
}

From source file:org.apache.abdera.protocol.server.adapters.hibernate.HibernateCollectionAdapter.java

License:Apache License

@Override
public Feed getFeed() throws Exception {
    Session session = getSessionFactory().openSession();

    String queryName = config.getFeedId() + "-get-feed";
    Query query = session.getNamedQuery(queryName);

    Feed feed = createFeed();/*w ww.jav  a  2s.c om*/
    query.setResultTransformer(new AtomEntryResultTransformer(
            config.getServerConfiguration().getServerUri() + "/" + config.getFeedId(), this.getAbdera(), feed));
    query.list();

    session.close();
    return feed;
}

From source file:org.babyfish.hibernate.internal.QueryTemplateImpl.java

License:Open Source License

@Override
protected void setTupleTransfromer(XTypedQuery<?> query, CompoundSelection<Tuple> tupleSelection) {
    org.hibernate.Query hqlQuery = query.unwrap(org.hibernate.Query.class);
    hqlQuery.setResultTransformer(new TupleResultTransformer(tupleSelection));
}

From source file:org.cgiar.ccafs.marlo.data.dao.impl.StandardDAO.java

License:Open Source License

/**
 * This method make a query that returns a not mapped object result from the model.
 * /*from   ww  w.  ja v  a2 s.  co  m*/
 * @param sqlQuery is a string representing an HQL query.
 */
public List<Map<String, Object>> findCustomQuery(String sqlQuery) {
    Session session = null;
    Transaction tx = null;

    try {
        session = this.openSession();
        tx = this.initTransaction(session);

        session.flush();
        session.clear();
        Query query = session.createSQLQuery(sqlQuery);
        query.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
        List<Map<String, Object>> result = query.list();
        this.commitTransaction(tx);

        return result;
    } catch (Exception e) {
        if (tx != null) {
            this.rollBackTransaction(tx);
        }
        e.printStackTrace();
        return null;
    } finally {
        if (session.isOpen()) {
            // Flushing the changes always.
        }
    }
}

From source file:org.cgiar.ccafs.marlo.data.dao.mysql.AbstractMarloDAO.java

License:Open Source License

/**
 * This method make a query that returns a not mapped object result from the model.
 * /*w  w  w .  jav  a 2  s.  c  o  m*/
 * @param sqlQuery is a string representing an SQL query.
 */
public List<Map<String, Object>> excuteStoreProcedure(String storeProcedure, String sqlQuery) {
    this.sessionFactory.getCurrentSession().createSQLQuery(storeProcedure).executeUpdate();
    Query query = this.sessionFactory.getCurrentSession().createSQLQuery(sqlQuery);
    query.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
    query.setFlushMode(FlushMode.COMMIT);

    List<Map<String, Object>> result = query.list();
    return result;

}

From source file:org.cgiar.ccafs.marlo.data.dao.mysql.AbstractMarloDAO.java

License:Open Source License

/**
 * This method make a query that returns a not mapped object result from the model.
 * //from   w w  w  . j  a  va  2s. c o  m
 * @param sqlQuery is a string representing an HQL query.
 */
public List<Map<String, Object>> findCustomQuery(String sqlQuery) {
    Query query = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery);
    query.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
    query.setFlushMode(FlushMode.COMMIT);
    List<Map<String, Object>> result = query.list();

    return result;

}

From source file:org.cgiar.ccafs.marlo.data.dao.mysql.FundingSourceMySQLDAO.java

License:Open Source License

@Override
public List<FundingSourceSearchSummary> searchFundingSourcesByInstitution(String userInput, Long institutionID,
        int year, long crpID, long phaseID) {
    StringBuilder q = new StringBuilder();

    q.append(/*from w  w  w . j  a  va 2  s . c  o m*/
            "SELECT sub.id AS id, sub.name AS name, sub.type AS type, sub.typeId AS typeId, sub.financeCode AS financeCode, sub.w1w2 AS w1w2, sub.budget AS budget, SUM(pb.amount) AS usedAmount ");
    q.append("FROM ");

    q.append(
            "(SELECT DISTINCT fs.id AS `id`, fsi.title AS `name`, bt.name AS `type`, bt.id AS `typeId`, fsi.finance_code AS `financeCode`, fsi.w1w2 AS `w1w2`, fsb.budget AS `budget` ");

    q.append("FROM funding_sources_info fsi ");
    q.append(
            "INNER JOIN funding_sources fs ON fs.id = fsi.funding_source_id AND fs.is_active AND fs.global_unit_id = "
                    + crpID + " ");

    // Only add the INNER JOIN if an institutionId was provided.
    if (institutionID != null) {
        q.append(
                "INNER JOIN funding_source_institutions fsin ON fs.id = fsin.funding_source_id AND fsin.institution_id = "
                        + institutionID + " AND fsin.id_phase = " + phaseID + " ");
    }
    q.append("LEFT JOIN budget_types bt ON bt.id = fsi.type ");
    q.append("LEFT JOIN funding_source_budgets fsb ON fs.id = fsb.funding_source_id ");
    q.append("WHERE 1=1 ");
    q.append("AND fsi.title IS NOT NULL ");
    q.append("AND (fsi.status IS NULL OR fsi.status IN (1,2,4,7) ) ");
    q.append("AND (fsi.title LIKE '%" + userInput + "%' ");
    q.append("OR fsi.funding_source_id LIKE '%" + userInput + "%' ");
    q.append("OR CONCAT('FS', fsi.funding_source_id) LIKE '%" + userInput + "%' ");
    q.append("OR fsi.finance_code LIKE '%" + userInput + "%' ");
    q.append("OR (SELECT NAME FROM budget_types bt WHERE bt.id = fsi.type) LIKE '%" + userInput + "%' ) ");
    q.append("AND fsi.id_phase = " + phaseID);
    q.append(" AND fsi.end_date IS NOT NULL ");
    q.append("AND ( ( fsb.id IS NULL OR ( fsb.year = " + year + " AND fsb.id_phase = " + phaseID + " ) ) ");
    // q.append("AND ( ( fsb.id IS NULL OR ( fsb.id_phase = " + phaseID + " ) ) ");
    q.append(" AND (" + year + " <= YEAR(fsi.end_date) OR " + year + " <= YEAR(fsi.extended_date) ) ) ");
    q.append(") AS sub ");
    q.append("LEFT JOIN project_budgets pb ON pb.funding_source_id = sub.id AND pb.is_active=1 ");
    q.append("WHERE pb.id IS NULL OR (pb.year= " + year + " AND pb.id_phase=" + phaseID + ") ");
    q.append("GROUP BY sub.id, sub.name, sub.type, sub.typeId, sub.financeCode, sub.w1w2, sub.budget ");
    q.append("ORDER BY sub.id, sub.name");

    Query query = this.getSessionFactory().getCurrentSession().createSQLQuery(q.toString());
    query.setResultTransformer(new AliasToBeanResultTransformer(FundingSourceSearchSummary.class));
    List<FundingSourceSearchSummary> result = query.list();

    return result;

}

From source file:org.codehaus.grepo.query.hibernate.generator.QueryGeneratorBase.java

License:Apache License

protected void applyResultTransformerSetting(HibernateQueryOptions queryOptions, Query query) {
    ResultTransformer resultTransformer = HibernateGeneratorUtils.getResultTransformer(queryOptions);
    if (resultTransformer != null) {
        query.setResultTransformer(resultTransformer);
    }//from w  w  w.j a  va2  s .  co m
}