Example usage for org.hibernate Query setMaxResults

List of usage examples for org.hibernate Query setMaxResults

Introduction

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

Prototype

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

Source Link

Usage

From source file:alpha.portal.dao.hibernate.AlphaCardDaoHibernate.java

License:Apache License

/**
 * List the last 20 changes of AlphaCards in AlphaCases where I take part.
 * //  w  w  w  .j av  a 2 s.  co  m
 * @param caseIDs
 *            A String array with the caseIDs of the cases where I take part
 * 
 * @return A list with AlphaCards
 */
public List<AlphaCard> listDashBoardAlphaCards(final String[] caseIDs) {
    Session session;
    boolean sessionOwn = false;
    try {
        session = this.getSessionFactory().getCurrentSession();
    } catch (final Exception e) {
        session = this.getSessionFactory().openSession();
        sessionOwn = true;
    }

    String queryStr = "from alphacard where";
    // add all caseIDs in 'where' with OR clause
    for (int i = 0; i < caseIDs.length; i++) {
        queryStr = queryStr.concat(" alphaCardIdentifier.caseId = " + "'" + caseIDs[i] + "'");
        if (i < (caseIDs.length - 1)) {
            queryStr = queryStr.concat(" or");
        }
    }

    // order the result descending
    queryStr = queryStr.concat(" order by alphaCardIdentifier.sequenceNumber DESC");

    final Query query = session.createQuery(queryStr);
    // only the top 20 results
    query.setMaxResults(20);

    return query.list();
}

From source file:apm.common.core.DaoImpl.java

License:Open Source License

/**
 * QL //from www. j  a v a  2s.c o m
 * @param page
 * @param qlString
 * @param parameter
 * @return
 */
@SuppressWarnings("unchecked")
public <E> Page<E> find(Page<E> page, String qlString, Object... parameter) {
    // get count
    if (!page.isDisabled() && !page.isNotCount()) {
        String countQlString = "select count(*) " + removeSelect(removeOrders(qlString));
        //           page.setCount(Long.valueOf(createQuery(countQlString, parameter).uniqueResult().toString()));
        Query query = createQuery(countQlString, parameter);
        List<Object> list = query.list();
        if (list.size() > 0) {
            page.setCount(Long.valueOf(list.get(0).toString()));
        } else {
            page.setCount(list.size());
        }
        if (page.getCount() < 1) {
            return page;
        }
    }
    // order by
    String ql = qlString;
    if (StringUtils.isNotBlank(page.getOrderBy())) {
        ql += " order by " + page.getOrderBy();
    }
    Query query = createQuery(ql, parameter);
    // set page
    if (!page.isDisabled()) {
        query.setFirstResult(page.getFirstResult());
        query.setMaxResults(page.getMaxResults());
    }
    page.setList(query.list());
    return page;
}

From source file:apm.common.core.DaoImpl.java

License:Open Source License

/**
* SQL //  w  w  w. j av  a2 s  .  co  m
* @param page
* @param sqlString
* @param resultClass
* @param parameter
* @return
*/
@SuppressWarnings("unchecked")
public <E> Page<E> findBySql(Page<E> page, String sqlString, Class<?> resultClass, Object... parameter) {
    // get count
    if (!page.isDisabled() && !page.isNotCount()) {
        String countSqlString = "select count(*) " + removeSelect(removeOrders(sqlString));
        //           page.setCount(Long.valueOf(createSqlQuery(countSqlString, parameter).uniqueResult().toString()));
        Query query = createSqlQuery(countSqlString, parameter);
        List<Object> list = query.list();
        if (list.size() > 0) {
            page.setCount(Long.valueOf(list.get(0).toString()));
        } else {
            page.setCount(list.size());
        }
        if (page.getCount() < 1) {
            return page;
        }
    }
    // order by
    String sql = sqlString;
    if (StringUtils.isNotBlank(page.getOrderBy())) {
        sql += " order by " + page.getOrderBy();
    }
    SQLQuery query = createSqlQuery(sql, parameter);
    // set page
    if (!page.isDisabled()) {
        query.setFirstResult(page.getFirstResult());
        query.setMaxResults(page.getMaxResults());
    }
    setResultTransformer(query, resultClass);
    page.setList(query.list());
    return page;
}

From source file:app.persistencia.DAO.java

/**
 * Esta funcion nos devuelve el valor mximo del campo ID de la base de
 * datos// ww w . j  a  v a 2s . c  o m
 *
 * @param entidad String que se refiere al nombre de la clase de la que
 * queremos obtener el ID. No confundir con el nombre de la tabla de la base
 * de datos a la que persistimos.
 *
 * @return ID - integer
 */
public int getID(String entidad) {
    cerrarConexion();
    abrirConexion();
    int max = -1;
    System.out.println("MAX: " + max);
    try {

        Query q1 = session.createQuery("select max(id) from " + entidad);
        q1.setMaxResults(1);
        max = (int) q1.uniqueResult();
        max = max + 1;
        System.out.println("MAX: " + max);

    } catch (HibernateException e) {
        System.out.println(
                "Error al consultar la ID de la entidad " + entidad + " . Mas detalles -->" + e.getMessage());
    }

    return max;

}

From source file:ar.com.zauber.commons.web.cache.impl.repo.hibernate.HibernateLastModifiedRepository.java

License:Apache License

/** @see LastModifiedRepository#getMaxTimestamp(List) */
public final Long getMaxTimestamp(final List<StringEntityKey> keys) {
    if (keys.size() == 0) {
        return this.getTimestamp(keys.get(0));
    }/*from  w w  w  . j  a  v  a 2 s.com*/

    String[] keyStrings = new String[keys.size()];
    for (int i = 0; i < keys.size(); i++) {
        keyStrings[i] = keys.get(i).getAsString();
    }

    Query query = this.sessionFactory.getCurrentSession()
            .getNamedQuery("lastModified.orderedTimestampsForEntities");

    query.setParameterList("entitiesKey", keyStrings);
    query.setMaxResults(1);
    return (Long) query.uniqueResult();
}

From source file:at.treedb.db.hibernate.DAOhibernate.java

License:Open Source License

@Override
public List<?> query(String query, int start, int length, HashMap<String, Object> map) {
    Query q;
    if (isStatelessSession) {
        q = statelessSession.createQuery(query);
    } else {//from   w  w  w .jav a 2 s .c  o m
        q = session.createQuery(query);
    }
    if (map != null) {
        Iterator<String> iter = map.keySet().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            Object o = map.get(key);
            q.setParameter(key, o);
        }
    }
    q.setFirstResult(start);
    q.setMaxResults(length);
    return q.list();
}

From source file:au.edu.anu.metadatastores.harvester.HarvestContentService.java

License:Open Source License

/**
 * Get the next row of harvest content to process
 * /*  www.j  ava 2 s  .  c o  m*/
 * @param system The system to get the harvest content for
 * @return The harvest content record
 */
public HarvestContent getNextHarvestContent(String system) {
    Session session = HarvesterHibernateUtil.getSessionFactory().openSession();
    try {
        Query query = session.createQuery("FROM HarvestContent WHERE system = :system ORDER BY hid");
        query.setParameter("system", system);

        HarvestContent content = (HarvestContent) query.setMaxResults(1).uniqueResult();

        return content;
    } finally {
        session.close();
    }
}

From source file:au.org.theark.lims.model.dao.BioCollectionDao.java

License:Open Source License

public List<BioCollectionCustomFieldData> getBioCollectionCustomFieldDataList(
        BioCollection bioCollectionCriteria, ArkFunction arkFunction, int first, int count) {
    List<BioCollectionCustomFieldData> bioCollectionCustomFieldDataList = new ArrayList<BioCollectionCustomFieldData>();

    StringBuffer sb = new StringBuffer();
    sb.append(" FROM  CustomFieldDisplay AS cfd ");
    sb.append("LEFT JOIN cfd.bioCollectionCustomFieldData as fieldList ");
    sb.append(" with fieldList.bioCollection.id = :bioCollectionId ");
    sb.append("  WHERE cfd.customField.study.id IN (:studyId)");
    sb.append(" AND cfd.customField.arkFunction.id = :functionId");
    sb.append(" ORDER BY cfd.sequence");

    Query query = getSession().createQuery(sb.toString());
    query.setParameter("bioCollectionId", bioCollectionCriteria.getId());

    // Allow child studies to inherit parent defined custom fields
    List studyList = new ArrayList();
    studyList.add(bioCollectionCriteria.getStudy().getId());
    if (bioCollectionCriteria.getStudy().getParentStudy() != null
            && bioCollectionCriteria.getStudy().getParentStudy() != bioCollectionCriteria.getStudy()) {
        studyList.add(bioCollectionCriteria.getStudy().getParentStudy().getId());
    }/*from ww w. jav  a2  s. c om*/
    query.setParameterList("studyId", studyList);
    query.setParameter("functionId", arkFunction.getId());
    query.setFirstResult(first);
    query.setMaxResults(count);

    List<Object[]> listOfObjects = query.list();
    for (Object[] objects : listOfObjects) {
        CustomFieldDisplay cfd = new CustomFieldDisplay();
        BioCollectionCustomFieldData bccfd = new BioCollectionCustomFieldData();
        if (objects.length > 0 && objects.length >= 1) {

            cfd = (CustomFieldDisplay) objects[0];
            if (objects[1] != null) {
                bccfd = (BioCollectionCustomFieldData) objects[1];
            } else {
                bccfd.setCustomFieldDisplay(cfd);
            }
            bioCollectionCustomFieldDataList.add(bccfd);
        }
    }
    return bioCollectionCustomFieldDataList;
}

From source file:au.org.theark.lims.model.dao.BiospecimenDao.java

License:Open Source License

public List<BiospecimenCustomFieldData> getBiospecimenCustomFieldDataList(Biospecimen biospecimenCriteria,
        ArkFunction arkFunction, int first, int count) {
    List<BiospecimenCustomFieldData> biospecimenCustomFieldDataList = new ArrayList<BiospecimenCustomFieldData>();

    StringBuffer sb = new StringBuffer();
    sb.append(" FROM  CustomFieldDisplay AS cfd ");
    sb.append("LEFT JOIN cfd.biospecimenCustomFieldData as fieldList ");
    sb.append(" with fieldList.biospecimen.id = :biospecimenId ");
    sb.append("  where cfd.customField.study.id IN (:studyId)");
    sb.append(" and cfd.customField.arkFunction.id = :functionId");
    sb.append(" order by cfd.sequence");

    Query query = getSession().createQuery(sb.toString());
    query.setParameter("biospecimenId", biospecimenCriteria.getId());

    // Allow child studies to inherit parent defined custom fields
    List studyList = new ArrayList();
    studyList.add(biospecimenCriteria.getStudy().getId());
    if (biospecimenCriteria.getStudy().getParentStudy() != null
            && biospecimenCriteria.getStudy().getParentStudy() != biospecimenCriteria.getStudy()) {
        studyList.add(biospecimenCriteria.getStudy().getParentStudy().getId());
    }/*  ww  w.  ja  va  2 s.c om*/
    query.setParameterList("studyId", studyList);
    query.setParameter("functionId", arkFunction.getId());
    query.setFirstResult(first);
    query.setMaxResults(count);

    List<Object[]> listOfObjects = query.list();
    for (Object[] objects : listOfObjects) {
        CustomFieldDisplay cfd = new CustomFieldDisplay();
        BiospecimenCustomFieldData bscfd = new BiospecimenCustomFieldData();
        if (objects.length > 0 && objects.length >= 1) {

            cfd = (CustomFieldDisplay) objects[0];
            if (objects[1] != null) {
                bscfd = (BiospecimenCustomFieldData) objects[1];
            } else {
                bscfd.setCustomFieldDisplay(cfd);
            }
            biospecimenCustomFieldDataList.add(bscfd);
        }
    }
    return biospecimenCustomFieldDataList;
}

From source file:au.org.theark.phenotypic.model.dao.PhenotypicDao.java

License:Open Source License

public List<PhenoDataSetData> getPhenoDataList(PhenoDataSetCollection phenoCollection,
        PhenoDataSetCategory phenoDataSetCategory, int first, int count) {

    List<PhenoDataSetData> phenoDataList = new ArrayList<PhenoDataSetData>();

    // The following HQL is based on this SQL, except that we don't need the CustomField
    //      SELECT *
    //        FROM study.custom_field cf
    //       INNER JOIN study.custom_field_display cfd
    //          ON cfd.custom_field_id = cf.id
    //       INNER JOIN study.custom_field_group cfg
    //          ON cfd.custom_field_group_id = cfg.id
    //       INNER JOIN pheno.pheno_collection pc
    //          ON pc.custom_field_group_id = cfg.id
    //        LEFT JOIN pheno.pheno_data pd
    //          ON pd.custom_field_display_id = cfd.id
    //         AND pd.pheno_collection_id = pc.id
    //       WHERE pc.id = 1;

    /*      //from w  w w.  j a  v a2s .  co  m
     * WARNING: Do no try to do a HQL WITH clause between "pd.phenoCollection.id" and another table's column!
     * Even though it looks like it should work in SQL (as above), for an unknown reason HQL parsing will fail - like this:
     * ----
     * Caused by: org.hibernate.hql.ast.QuerySyntaxException: with-clause referenced two different from-clause elements 
     * [  FROM au.org.theark.core.model.study.entity.CustomFieldDisplay AS cfd  
     * INNER JOIN cfd.customFieldGroup cfg  
     * INNER JOIN cfg.phenoCollection pc   
     * LEFT JOIN cfd.phenoData AS pd   
     * WITH pd.phenoCollection.id = pc.id 
     * WHERE pc.id = :pcId ORDER BY cfd.sequence ]
     * ----
     * Thus the present work-around is to use an argument "pcId" for the WITH criteria.
     */
    StringBuffer sb = new StringBuffer();
    sb.append("SELECT pdsfd, pdsd ");
    sb.append("  FROM PhenoDataSetFieldDisplay AS pdsfd ");
    sb.append(" INNER JOIN pdsfd.phenoDataSetGroup AS pdsg ");
    sb.append(" INNER JOIN pdsg.phenoDataSetCollections pdsc ");
    sb.append("  LEFT JOIN pdsfd.phenoDataSetData AS pdsd ");
    sb.append("  WITH pdsd.phenoDataSetCollection.id = :pcId ");
    sb.append(" WHERE pdsc.id = :pcId ");
    sb.append(" and pdsfd.phenoDataSetCategory = :phenoDataSetCategory ");
    sb.append(" and pdsfd.phenoDataSetField is not null ");
    sb.append(" ORDER BY pdsfd.phenoDataSetFiledOrderNumber ");

    Query query = getSession().createQuery(sb.toString());
    query.setParameter("pcId", phenoCollection.getId());
    query.setParameter("phenoDataSetCategory", phenoDataSetCategory);
    query.setFirstResult(first);
    query.setMaxResults(count);

    List<Object[]> listOfObjects = query.list();
    for (Object[] objects : listOfObjects) {
        PhenoDataSetFieldDisplay pfd = new PhenoDataSetFieldDisplay();
        PhenoDataSetData phenoData = new PhenoDataSetData();
        if (objects.length > 0 && objects.length >= 1) {
            pfd = (PhenoDataSetFieldDisplay) objects[0];
            if (objects[1] != null) {
                phenoData = (PhenoDataSetData) objects[1];
            } else {
                phenoData.setPhenoDataSetFieldDisplay(pfd);
            }
            phenoDataList.add(phenoData);
        }
    }
    return phenoDataList;
}