Example usage for org.hibernate SQLQuery setMaxResults

List of usage examples for org.hibernate SQLQuery setMaxResults

Introduction

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

Prototype

@Override
    Query<R> setMaxResults(int maxResult);

Source Link

Usage

From source file:org.trpr.dataaccess.orm.handler.HibernateHandler.java

License:Apache License

/**
 * Helper method to execute a native SQL query and return the results as a List of PersistentEntity instances.
 * Note that this implementation doesnot support scalar values to be returned and instead expects all resultant data to be
 * mapped to a PersistentEntity defined for the purpose. This approach helps to maintain consistency in the {@link #findEntities(Criteria)}
 * interface implementation and also provide for standard Hibernate-to-Java entity type mapping semantics.
 *//*ww  w. j  av  a2  s  . co  m*/
@SuppressWarnings("unchecked")
private List<PersistentEntity> findObjectBySQLQuery(final Criteria criteria) {
    return (List<PersistentEntity>) this.getTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            SQLQuery sqlQueryObject = session.createSQLQuery(criteria.getQuery());
            sqlQueryObject.addEntity(criteria.getManagedClass());
            sqlQueryObject.setFirstResult(criteria.getFirstResult());
            if (criteria.getMaxResults() > 0) {
                sqlQueryObject.setMaxResults(criteria.getMaxResults());
            }
            return sqlQueryObject.list();
        }
    });
}

From source file:org.yamj.core.database.dao.ArtworkDao.java

License:Open Source License

public List<QueueDTO> getArtworkQueue(final CharSequence sql, final int maxResults) {
    SQLQuery query = currentSession().createSQLQuery(sql.toString());
    query.setReadOnly(true);//from   ww  w . ja  v a2  s  .  c  o  m
    query.setCacheable(true);
    if (maxResults > 0) {
        query.setMaxResults(maxResults);
    }

    List<QueueDTO> queueElements = new ArrayList<>();

    List<Object[]> objects = query.list();
    for (Object[] object : objects) {
        QueueDTO queueElement = new QueueDTO();
        queueElement.setId(convertRowElementToLong(object[0]));
        queueElement.setArtworkType(convertRowElementToString(object[1]));
        queueElement.setDate(convertRowElementToDate(object[3]));
        if (queueElement.getDate() == null) {
            queueElement.setDate(convertRowElementToDate(object[2]));
        }
        queueElements.add(queueElement);
    }

    Collections.sort(queueElements);
    return queueElements;
}

From source file:org.yamj.core.database.dao.ArtworkDao.java

License:Open Source License

public List<QueueDTO> getArtworkLocatedQueue(final int maxResults) {
    final StringBuilder sql = new StringBuilder();
    sql.append("SELECT DISTINCT loc.id, loc.create_timestamp, loc.update_timestamp ");
    sql.append("FROM artwork_located loc ");
    sql.append("WHERE loc.status in ('NEW','UPDATED')");

    SQLQuery query = currentSession().createSQLQuery(sql.toString());
    query.setReadOnly(true);/*from w w  w  .j a  v  a  2s.c  o  m*/
    query.setCacheable(true);
    if (maxResults > 0) {
        query.setMaxResults(maxResults);
    }

    List<QueueDTO> queueElements = new ArrayList<>();
    List<Object[]> objects = query.list();
    for (Object[] object : objects) {
        QueueDTO queueElement = new QueueDTO();
        queueElement.setId(convertRowElementToLong(object[0]));
        queueElement.setDate(convertRowElementToDate(object[2]));
        if (queueElement.getDate() == null) {
            queueElement.setDate(convertRowElementToDate(object[1]));
        }
        queueElements.add(queueElement);
    }

    Collections.sort(queueElements);
    return queueElements;
}

From source file:org.yamj.core.database.dao.MediaDao.java

License:Open Source License

public List<QueueDTO> getMediaQueue(final CharSequence sql, final int maxResults) {
    SQLQuery query = currentSession().createSQLQuery(sql.toString());
    query.setReadOnly(true);/* w  w w .j  a v  a  2 s .co  m*/
    query.setCacheable(true);
    if (maxResults > 0) {
        query.setMaxResults(maxResults);
    }

    List<QueueDTO> queueElements = new ArrayList<>();

    List<Object[]> objects = query.list();
    for (Object[] object : objects) {
        QueueDTO queueElement = new QueueDTO();
        queueElement.setId(convertRowElementToLong(object[0]));
        queueElement.setDate(convertRowElementToDate(object[2]));
        if (queueElement.getDate() == null) {
            queueElement.setDate(convertRowElementToDate(object[1]));
        }
        queueElements.add(queueElement);
    }

    Collections.sort(queueElements);
    return queueElements;
}

From source file:org.yamj.core.database.dao.MetadataDao.java

License:Open Source License

public List<QueueDTO> getMetadataQueue(final CharSequence sql, final int maxResults) {
    SQLQuery query = currentSession().createSQLQuery(sql.toString());
    query.setReadOnly(true);// w  ww .  ja v a  2 s. c o m
    query.setCacheable(true);
    if (maxResults > 0) {
        query.setMaxResults(maxResults);
    }

    List<QueueDTO> queueElements = new ArrayList<>();

    List<Object[]> objects = query.list();
    for (Object[] object : objects) {
        QueueDTO queueElement = new QueueDTO();
        queueElement.setId(convertRowElementToLong(object[0]));
        queueElement.setMetadataType(convertRowElementToString(object[1]));
        queueElement.setDate(convertRowElementToDate(object[3]));
        if (queueElement.getDate() == null) {
            queueElement.setDate(convertRowElementToDate(object[2]));
        }
        queueElements.add(queueElement);
    }

    Collections.sort(queueElements);
    return queueElements;
}

From source file:org.yamj.core.database.dao.TrailerDao.java

License:Open Source License

public List<QueueDTO> getTrailerQueueForScanning(final int maxResults) {
    final StringBuilder sql = new StringBuilder();
    sql.append("select vd.id,'");
    sql.append(MetaDataType.MOVIE);/*from  ww  w . jav  a  2 s  .c  o m*/
    sql.append("' as metatype,vd.create_timestamp,vd.update_timestamp ");
    sql.append("from videodata vd ");
    sql.append("where vd.trailer_status in ('NEW','UPDATED') ");
    sql.append("and vd.status='DONE' ");
    sql.append("and vd.episode<0 ");
    sql.append("union ");
    sql.append("select ser.id,'");
    sql.append(MetaDataType.SERIES);
    sql.append("' as mediatype,ser.create_timestamp,ser.update_timestamp ");
    sql.append("from series ser ");
    sql.append("where ser.trailer_status in ('NEW','UPDATED') ");
    sql.append("and ser.status='DONE' ");

    SQLQuery query = currentSession().createSQLQuery(sql.toString());
    query.setReadOnly(true);
    query.setCacheable(true);
    if (maxResults > 0) {
        query.setMaxResults(maxResults);
    }

    List<QueueDTO> queueElements = new ArrayList<>();

    List<Object[]> objects = query.list();
    for (Object[] object : objects) {
        QueueDTO queueElement = new QueueDTO();
        queueElement.setId(convertRowElementToLong(object[0]));
        queueElement.setMetadataType(convertRowElementToString(object[1]));
        queueElement.setDate(convertRowElementToDate(object[3]));
        if (queueElement.getDate() == null) {
            queueElement.setDate(convertRowElementToDate(object[2]));
        }
        queueElements.add(queueElement);
    }

    Collections.sort(queueElements);
    return queueElements;
}

From source file:org.yamj.core.database.dao.TrailerDao.java

License:Open Source License

public List<QueueDTO> getTrailerQueueForProcessing(final int maxResults) {
    final StringBuilder sql = new StringBuilder();
    sql.append("SELECT DISTINCT t.id, t.create_timestamp, t.update_timestamp ");
    sql.append("FROM trailer t ");
    sql.append("WHERE t.status in ('NEW','UPDATED')");

    SQLQuery query = currentSession().createSQLQuery(sql.toString());
    query.setReadOnly(true);/*from  w w  w .  j  a v a 2s  .com*/
    query.setCacheable(true);
    if (maxResults > 0) {
        query.setMaxResults(maxResults);
    }

    List<QueueDTO> queueElements = new ArrayList<>();
    List<Object[]> objects = query.list();
    for (Object[] object : objects) {
        QueueDTO queueElement = new QueueDTO();
        queueElement.setId(convertRowElementToLong(object[0]));
        queueElement.setDate(convertRowElementToDate(object[2]));
        if (queueElement.getDate() == null) {
            queueElement.setDate(convertRowElementToDate(object[1]));
        }
        queueElements.add(queueElement);
    }

    Collections.sort(queueElements);
    return queueElements;
}

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>//from ww w  .ja  va  2 s. com
 * @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;
}

From source file:ubic.gemma.persistence.service.analysis.expression.diff.DifferentialExpressionResultDaoImpl.java

License:Apache License

@Override
public List<Double> findGeneInResultSets(Gene gene, ExpressionAnalysisResultSet resultSet,
        Collection<Long> arrayDesignIds, Integer limit) {

    StopWatch timer = new StopWatch();
    timer.start();/*from  ww  w.  j  a v a  2 s .  c  om*/

    List<Double> results;

    Session session = this.getSessionFactory().getCurrentSession();
    org.hibernate.SQLQuery queryObject = session
            .createSQLQuery(DifferentialExpressionResultDaoImpl.fetchResultsByResultSetAndGeneQuery);

    queryObject.setLong("gene_id", gene.getId());
    queryObject.setLong("rs_id", resultSet.getId());

    if (limit != null) {
        queryObject.setMaxResults(limit);
    }

    queryObject.addScalar("CORRECTED_PVALUE", new DoubleType());
    //noinspection unchecked
    results = queryObject.list();

    timer.stop();
    if (AbstractDao.log.isDebugEnabled())
        AbstractDao.log.debug("Fetching probeResults from resultSet " + resultSet.getId() + " for gene "
                + gene.getId() + "and " + arrayDesignIds.size() + "arrays took : " + timer.getTime() + " ms");

    return results;
}

From source file:ubic.gemma.persistence.service.analysis.expression.diff.DifferentialExpressionResultDaoImpl.java

License:Apache License

@Override
public Map<ExpressionExperimentValueObject, List<DifferentialExpressionValueObject>> find(Gene gene,
        double threshold, Integer limit) {

    StopWatch timer = new StopWatch();
    timer.start();/*from   w  w  w  .jav a  2 s  .  c  o  m*/

    Session session = this.getSessionFactory().getCurrentSession();
    String sql = DifferentialExpressionResultDaoImpl.fetchResultsByGeneSQL;

    if (threshold > 0.0) {
        sql = sql + " and d.CORRECTED_PVALUE < :threshold ";
    }

    if (limit != null) {
        sql = sql + "  order by d.PVALUE ASC ";
    }

    SQLQuery query = session.createSQLQuery(sql);

    query.setParameter("gene_id", gene.getId());
    if (limit != null) {
        query.setMaxResults(limit);
    }
    if (threshold > 0.0) {
        query.setParameter("threshold", threshold);
    }

    Map<ExpressionExperimentValueObject, List<DifferentialExpressionValueObject>> results = new HashMap<>();

    //noinspection unchecked
    List<Object[]> qResult = query.list();

    Set<Long> resultSets = new HashSet<>();

    Map<Long, DifferentialExpressionValueObject> resultsInter = new HashMap<>();
    Set<Long> probeIds = new HashSet<>();
    GeneValueObject genevo = new GeneValueObject(gene);

    for (Object[] rec : qResult) {
        Long id = SQLUtils.asId(rec[0]);

        if (!resultsInter.containsKey(id)) {

            DifferentialExpressionValueObject vo = new DifferentialExpressionValueObject(id);
            vo.setP((Double) rec[1]);
            vo.setCorrP((Double) rec[2]);
            vo.setProbeId(SQLUtils.asId(rec[3])); // fill in probe name later.
            probeIds.add(vo.getProbeId());
            vo.setResultSetId(SQLUtils.asId(rec[4]));
            if (threshold > 0)
                vo.setMetThreshold(true);

            vo.setGene(genevo);

            // gather up result sets so we can fetch the experiments, experimental factors
            resultSets.add(vo.getResultSetId());

            resultsInter.put(id, vo);

        }

        resultsInter.get(id).addContrast(SQLUtils.asId(rec[9]), SQLUtils.asId(rec[5]), (Double) rec[6],
                (Double) rec[7], SQLUtils.asId(rec[8]));
    }

    // gather up probe information
    Map<Long, String> probeNames = new HashMap<>();
    if (!probeIds.isEmpty()) {
        //noinspection unchecked
        for (Object[] rec : (List<Object[]>) session
                .createQuery("select id,name from CompositeSequence where id in (:ids)")
                .setParameterList("ids", probeIds).list()) {
            probeNames.put((Long) rec[0], (String) rec[1]);
        }
    }

    /*
     * load the result set information.
     */
    if (resultSets.isEmpty())
        return results;

    //noinspection unchecked
    List<Object[]> ees = session.createQuery(
            "select ee, rs from  ExpressionAnalysisResultSet rs join fetch rs.experimentalFactors join rs.analysis a join a.experimentAnalyzed ee"
                    + " where rs.id in (:rsids)")
            .setParameterList("rsids", resultSets).list();

    /*
     * Finish populating the objects
     */
    for (Object[] oa : ees) {
        ExpressionAnalysisResultSet rs = (ExpressionAnalysisResultSet) oa[1];
        ExpressionExperimentValueObject evo = ((BioAssaySet) oa[0]).createValueObject();

        if (!results.containsKey(evo)) {
            results.put(evo, new ArrayList<DifferentialExpressionValueObject>());
        }

        for (Iterator<DifferentialExpressionValueObject> it = resultsInter.values().iterator(); it.hasNext();) {

            DifferentialExpressionValueObject dvo = it.next();
            dvo.setExpressionExperiment(evo);
            dvo.setProbe(probeNames.get(dvo.getProbeId()));
            dvo.getExperimentalFactors().clear();

            for (ExperimentalFactor ef : rs.getExperimentalFactors()) {
                dvo.getExperimentalFactors().add(new ExperimentalFactorValueObject(ef));

            }

            if (dvo.getResultSetId().equals(rs.getId())) {
                results.get(evo).add(dvo);
                it.remove();
            }

        }
    }

    AbstractDao.log.debug("Num experiments with probe analysis results (with limit = " + limit + ") : "
            + results.size() + ". Number of results (probes x contrasts) returned in total: " + qResult.size());

    timer.stop();
    if (timer.getTime() > 1000) {
        AbstractDao.log.info("Diff ex results: " + timer.getTime() + " ms");
    }

    return results;
}