Example usage for org.hibernate Query setFetchSize

List of usage examples for org.hibernate Query setFetchSize

Introduction

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

Prototype

Query<R> setFetchSize(int fetchSize);

Source Link

Document

Sets a JDBC fetch size hint for the query.

Usage

From source file:edu.ur.hibernate.ir.user.db.HbIrUserDAO.java

License:Apache License

/**
 * Get a list of users ordered by username for the specified affiliation
 * //from   w w  w  . j a va 2 s .  com
 * @param affiliationId - the affiliation id
 * @param rowStart - Start row to fetch the data from
 * @param maxResults - maximum number of results to fetch
 * @param sortType - The order to sort by (ascending/descending)
 * 
 * @return List of users
 */
@SuppressWarnings("unchecked")
public List<IrUser> getUsersByAffiliationEmailOrder(Long affiliationId, int rowStart, int maxResults,
        OrderType orderType) {
    Query q = null;
    if (orderType.equals(OrderType.DESCENDING_ORDER)) {
        q = hbCrudDAO.getSessionFactory().getCurrentSession()
                .getNamedQuery("getUsersByAffiliationOrderByEmailDesc");
    } else {
        q = hbCrudDAO.getSessionFactory().getCurrentSession()
                .getNamedQuery("getUsersByAffiliationOrderByEmailAsc");
    }

    q.setParameter("affiliationId", affiliationId);
    q.setFirstResult(rowStart);
    q.setMaxResults(maxResults);
    q.setFetchSize(maxResults);
    return (List<IrUser>) q.list();
}

From source file:edu.ur.hibernate.ir.user.db.HbIrUserDAO.java

License:Apache License

/**
 * Get a list of users ordered by last name, first name by role and affiliation
 * //from   w  w  w.j ava2  s .  co  m
 * @param roleId - the role id
 * @param affiliationId - the affiliation id
 * @param rowStart - Start row to fetch the data from
 * @param maxResults - maximum number of results to fetch
 * @param sortType - The order to sort by (ascending/descending)
 * 
 * @return List of users
 */
@SuppressWarnings("unchecked")
public List<IrUser> getUsersByRoleAffiliationFullNameOrder(Long roleId, Long affiliationId, int rowStart,
        int maxResults, OrderType orderType) {
    Query q = null;
    if (orderType.equals(OrderType.DESCENDING_ORDER)) {
        q = hbCrudDAO.getSessionFactory().getCurrentSession()
                .getNamedQuery("getUserByAffiliationRoleOrderByNameDesc");
    } else {
        q = hbCrudDAO.getSessionFactory().getCurrentSession()
                .getNamedQuery("getUserByAffiliationRoleOrderByNameAsc");
    }

    q.setParameter("affiliationId", affiliationId);
    q.setParameter("roleId", roleId);
    q.setFirstResult(rowStart);
    q.setMaxResults(maxResults);
    q.setFetchSize(maxResults);
    return (List<IrUser>) q.list();

}

From source file:edu.ur.hibernate.ir.user.db.HbIrUserDAO.java

License:Apache License

/**
 * Get a list of users ordered with a specified role by Username by role and affiliation
 * /*from   w ww  . ja  v  a 2 s. co m*/
 * @param roleId - the role id
 * @param affiliationId - the affiliationId
 * @param rowStart - Start row to fetch the data from
 * @param maxResults - maximum number of results to fetch
 * @param sortType - The order to sort by (ascending/descending)
 * 
 * @return List of users
 */
@SuppressWarnings("unchecked")
public List<IrUser> getUsersByRoleAffiliationUsernameOrder(Long roleId, Long affiliationId, int rowStart,
        int maxResults, OrderType orderType) {
    Query q = null;
    if (orderType.equals(OrderType.DESCENDING_ORDER)) {
        q = hbCrudDAO.getSessionFactory().getCurrentSession()
                .getNamedQuery("getUserByAffiliationRoleOrderByUsernameDesc");
    } else {
        q = hbCrudDAO.getSessionFactory().getCurrentSession()
                .getNamedQuery("getUserByAffiliationRoleOrderByUsernameAsc");
    }

    q.setParameter("affiliationId", affiliationId);
    q.setParameter("roleId", roleId);
    q.setFirstResult(rowStart);
    q.setMaxResults(maxResults);
    q.setFetchSize(maxResults);
    return (List<IrUser>) q.list();
}

From source file:edu.ur.hibernate.ir.user.db.HbIrUserDAO.java

License:Apache License

/**
 * Get a list of users ordered by username for the specified role affiliation
 * //w ww .  jav a 2 s.  com
 * @param roleId - the role id
 * @param affiliationId - the affiliation id
 * @param rowStart - Start row to fetch the data from
 * @param maxResults - maximum number of results to fetch
 * @param sortType - The order to sort by (ascending/descending)
 * 
 * @return List of users
 */
@SuppressWarnings("unchecked")
public List<IrUser> getUsersByRoleAffiliationEmailOrder(Long roleId, Long affiliationId, int rowStart,
        int maxResults, OrderType orderType) {
    Query q = null;
    if (orderType.equals(OrderType.DESCENDING_ORDER)) {
        q = hbCrudDAO.getSessionFactory().getCurrentSession()
                .getNamedQuery("getUsersByAffiliationRoleOrderByEmailDesc");
    } else {
        q = hbCrudDAO.getSessionFactory().getCurrentSession()
                .getNamedQuery("getUsersByAffiliationRoleOrderByEmailAsc");
    }

    q.setParameter("affiliationId", affiliationId);
    q.setParameter("roleId", roleId);
    q.setFirstResult(rowStart);
    q.setMaxResults(maxResults);
    q.setFetchSize(maxResults);
    return (List<IrUser>) q.list();
}

From source file:edu.ur.hibernate.ir.user.db.HbIrUserGroupDAO.java

License:Apache License

@SuppressWarnings("unchecked")
public List<IrUserGroup> getUserGroups(int rowStart, int numberOfResultsToShow, String sortType) {
    Session session = hbCrudDAO.getSessionFactory().getCurrentSession();
    Query q = null;
    if (sortType.equalsIgnoreCase("asc")) {
        q = session.getNamedQuery("getUserGroupsOrderByNameAsc");
    } else {//from  ww  w .j  a va 2 s  .c om
        q = session.getNamedQuery("getUserGroupsOrderByNameDesc");
    }

    q.setFirstResult(rowStart);
    q.setMaxResults(numberOfResultsToShow);
    q.setReadOnly(true);
    q.setFetchSize(numberOfResultsToShow);
    return q.list();
}

From source file:edu.ur.hibernate.ir.user.db.HbPersonalCollectionDAO.java

License:Apache License

/**
 * Get personal collections sorting according to the sort and filter information for the 
 * specified user - this only returns root personal collection.
 * //from  ww  w.j a v a  2 s . c  o m
 * Sort is applied based on the order of sort information in the list (1st to last).
 * Starts at the specified row start location and stops at specified row end.
 * 
 * @param userId
 * @param rowStart
 * @param maxNumToFetch
 * @return List of root collections containing the specified information.
 */
@SuppressWarnings("unchecked")
public List<PersonalCollection> getRootPersonalCollections(final Long userId, final int rowStart,
        final int maxNumToFetch) {
    List<PersonalCollection> personalCollections = (List<PersonalCollection>) hbCrudDAO.getHibernateTemplate()
            .executeFind(new HibernateCallback() {
                public Object doInHibernate(Session session) {
                    Query query = session.getNamedQuery("getRootPersonalCollections");
                    query.setParameter(1, userId);
                    query.setFirstResult(rowStart);
                    query.setMaxResults(maxNumToFetch);
                    query.setFetchSize(maxNumToFetch);
                    return query.list();
                }
            });
    return personalCollections;
}

From source file:fr.gael.dhus.database.dao.interfaces.HibernateDao.java

License:Open Source License

/**
 * <p>Returns a List of <b>T</b> entities, where HQL clauses can be
 * specified.</p>/*from www.  j  a v  a  2s.  c om*/
 * 
 * Note: This method is useful in read only. It can be use to delete or 
 * create <b>T</b> entities, but caution with <code>top</code> and 
 * <code>skip</code> arguments.
 * 
 * @param clauses query clauses (WHERE, ORDER BY, GROUP BY), if null no
 * clauses are apply.
 * @param skip number of entities to skip.
 * @param n  number of entities max returned.
 * @return a list of <b>T</b> entities.
 */
@SuppressWarnings("unchecked")
public List<T> scroll(final String clauses, final int skip, final int n) {
    StringBuilder hql = new StringBuilder();
    hql.append("FROM ").append(entityClass.getName());
    if (clauses != null)
        hql.append(" ").append(clauses);

    Session session;
    boolean newSession = false;
    try {
        session = getSessionFactory().getCurrentSession();
    } catch (HibernateException e) {
        session = getSessionFactory().openSession();
        newSession = true;
    }

    Query query = session.createQuery(hql.toString());
    if (skip > 0)
        query.setFirstResult(skip);
    if (n > 0) {
        query.setMaxResults(n);
        query.setFetchSize(n);
    }

    logger.info("Execution of HQL: " + hql.toString());
    long start = System.currentTimeMillis();

    List<T> result = (List<T>) query.list();
    logger.info("HQL executed in " + (System.currentTimeMillis() - start) + "ms.");

    if (newSession) {
        session.disconnect();
    }

    return result;
}

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

License:Apache License

protected void applyFetchSizeSetting(HibernateQueryOptions queryOptions, HibernateQueryExecutionContext context,
        Query query) {
    Integer fetchSize = HibernateGeneratorUtils.getFetchSize(queryOptions, context.getFetchSize());
    if (fetchSize != null) {
        query.setFetchSize(fetchSize);
    }//from   w  w w  . j a va  2  s  .c  o m
}

From source file:org.codehaus.groovy.grails.orm.hibernate.metaclass.ExecuteQueryPersistentMethod.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override/* w ww  . j av a2s  .  co  m*/
protected Object doInvokeInternal(Class clazz, String methodName, Closure additionalCriteria,
        Object[] arguments) {
    checkMethodSignature(clazz, arguments);

    final String query = arguments[0].toString();
    final Map queryMetaParams = extractQueryMetaParams(arguments);
    final List positionalParams = extractPositionalParams(arguments);
    final Map namedParams = extractNamedParams(arguments);

    return getHibernateTemplate().executeFind(new HibernateCallback<Object>() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query q = session.createQuery(query);
            SimpleTypeConverter converter = new SimpleTypeConverter();
            // process paginate params
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_MAX)) {
                Integer maxParam = converter.convertIfNecessary(
                        queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_MAX), Integer.class);
                q.setMaxResults(maxParam.intValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_OFFSET)) {
                Integer offsetParam = converter.convertIfNecessary(
                        queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_OFFSET), Integer.class);
                q.setFirstResult(offsetParam.intValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_CACHE)) {
                q.setCacheable(
                        ((Boolean) queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_CACHE)).booleanValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_FETCH_SIZE)) {
                Integer fetchSizeParam = converter.convertIfNecessary(
                        queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_FETCH_SIZE), Integer.class);
                q.setFetchSize(fetchSizeParam.intValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_TIMEOUT)) {
                Integer timeoutParam = converter.convertIfNecessary(
                        queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_TIMEOUT), Integer.class);
                q.setFetchSize(timeoutParam.intValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_READ_ONLY)) {
                q.setReadOnly(
                        ((Boolean) queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_READ_ONLY)).booleanValue());
            }
            if (queryMetaParams.containsKey(GrailsHibernateUtil.ARGUMENT_FLUSH_MODE)) {
                q.setFlushMode((FlushMode) queryMetaParams.get(GrailsHibernateUtil.ARGUMENT_FLUSH_MODE));
            }
            // process positional HQL params
            int index = 0;
            for (Object parameter : positionalParams) {
                q.setParameter(index++, parameter instanceof CharSequence ? parameter.toString() : parameter);
            }

            // process named HQL params
            for (Object o : namedParams.entrySet()) {
                Map.Entry entry = (Map.Entry) o;
                if (!(entry.getKey() instanceof String)) {
                    throw new GrailsQueryException("Named parameter's name must be of type String");
                }
                String parameterName = (String) entry.getKey();
                if (!QUERY_META_PARAMS.contains(parameterName)) {
                    Object parameterValue = entry.getValue();
                    if (parameterValue == null) {
                        throw new IllegalArgumentException(
                                "Named parameter [" + entry.getKey() + "] value may not be null");
                    }
                    if (Collection.class.isAssignableFrom(parameterValue.getClass())) {
                        q.setParameterList(parameterName, (Collection) parameterValue);
                    } else if (parameterValue.getClass().isArray()) {
                        q.setParameterList(parameterName, (Object[]) parameterValue);
                    } else if (parameterValue instanceof CharSequence) {
                        q.setParameter(parameterName, parameterValue.toString());
                    } else {
                        q.setParameter(parameterName, parameterValue);
                    }
                }
            }
            return q.list();
        }
    });
}

From source file:org.easybatch.extensions.hibernate.HibernateRecordReader.java

License:Open Source License

@Override
public void open() {
    currentRecordNumber = 0;/*from w w  w  .  j  a  v a2s. co m*/
    Query hibernateQuery = session.createQuery(query);
    hibernateQuery.setReadOnly(true);
    if (maxResults >= 1) {
        hibernateQuery.setMaxResults(maxResults);
    }
    if (fetchSize >= 1) {
        hibernateQuery.setFetchSize(fetchSize);
    }
    scrollableResults = hibernateQuery.scroll(ScrollMode.FORWARD_ONLY);
}