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:org.openmrs.module.amrsreports.db.hibernate.MohHibernateCoreDAO.java

License:Open Source License

@Override
public List<Object> executeScrollingHqlQuery(String query, Map<String, Object> substitutions) {
    Query q = sessionFactory.getCurrentSession().createQuery(query);

    applySubstitutions(q, substitutions);

    // optimizations go here
    q.setFetchSize(Integer.MIN_VALUE);
    q.setReadOnly(true);/*from  w  w w  . j a va  2 s  . co m*/

    List<Object> res = new ArrayList<Object>();

    long i = 0;

    ScrollableResults sr = q.scroll(ScrollMode.FORWARD_ONLY);
    while (sr.next()) {

        // rows always come back as an array
        Object[] o = sr.get();

        // but if there is only one object in the row, add it instead of the array
        if (o.length == 1)
            res.add(o[0]);
        else
            res.add(o);

        if (++i % 500 == 0)
            log.warn("processed #" + i);
    }

    log.warn("done. processed " + i + " total rows.");

    sr.close();

    return res;
}

From source file:org.openspaces.persistency.hibernate.iterator.DefaultScrollableDataIterator.java

License:Open Source License

protected ScrollableResults createCursor() {
    session = sessionFactory.openSession();
    session.setFlushMode(FlushMode.MANUAL);
    transaction = session.beginTransaction();
    if (entityName != null) {
        Criteria criteria = session.createCriteria(entityName);
        criteria.setCacheable(false);// w ww.j  ava2 s  . co m
        criteria.setFlushMode(FlushMode.MANUAL);
        criteria.setFetchSize(fetchSize);
        if (perfromOrderById) {
            ClassMetadata metadata = sessionFactory.getClassMetadata(entityName);
            String idPropName = metadata.getIdentifierPropertyName();
            if (idPropName != null) {
                criteria.addOrder(Order.asc(idPropName));
            }
        }
        if (from >= 0) {
            if (from > 0)
                criteria.setFirstResult(from);
            criteria.setMaxResults(size);
        }
        return criteria.scroll(ScrollMode.FORWARD_ONLY);
    } else if (sqlQuery != null) {
        Query query = HibernateIteratorUtils.createQueryFromSQLQuery(sqlQuery, session);
        query.setFetchSize(fetchSize);
        if (from >= 0) {
            if (from > 0)
                query.setFirstResult(from);
            query.setMaxResults(size);
        }
        return query.scroll(ScrollMode.FORWARD_ONLY);
    } else if (hQuery != null) {
        Query query = session.createQuery(hQuery);
        query.setFetchSize(fetchSize);
        if (from >= 0) {
            if (from > 0)
                query.setFirstResult(from);
            query.setMaxResults(size);
        }
        query.setCacheMode(CacheMode.IGNORE);
        query.setCacheable(false);
        query.setReadOnly(true);
        return query.scroll(ScrollMode.FORWARD_ONLY);
    } else {
        throw new IllegalStateException("No SQLQuery, entity, or Hibernate Query provided");
    }
}

From source file:org.openspaces.persistency.hibernate.iterator.StatelessScrollableDataIterator.java

License:Open Source License

protected ScrollableResults createCursor() {
    session = sessionFactory.openStatelessSession();
    transaction = session.beginTransaction();
    if (entityName != null) {
        Criteria criteria = session.createCriteria(entityName);
        criteria.setFetchSize(fetchSize);
        if (perfromOrderById) {
            ClassMetadata metadata = sessionFactory.getClassMetadata(entityName);
            String idPropName = metadata.getIdentifierPropertyName();
            if (idPropName != null) {
                criteria.addOrder(Order.asc(idPropName));
            }/*from w  w w.  jav a 2 s.com*/
        }
        if (from >= 0) {
            if (from > 0)
                criteria.setFirstResult(from);
            criteria.setMaxResults(size);
        }
        return criteria.scroll(ScrollMode.FORWARD_ONLY);
    } else if (sqlQuery != null) {
        Query query = HibernateIteratorUtils.createQueryFromSQLQuery(sqlQuery, session);
        query.setFetchSize(fetchSize);
        if (from >= 0) {
            if (from > 0)
                query.setFirstResult(from);
            query.setMaxResults(size);
        }
        return query.scroll(ScrollMode.FORWARD_ONLY);
    } else if (hQuery != null) {
        Query query = session.createQuery(hQuery);
        query.setFetchSize(fetchSize);
        if (from >= 0) {
            if (from > 0)
                query.setFirstResult(from);
            query.setMaxResults(size);
        }
        query.setReadOnly(true);
        return query.scroll(ScrollMode.FORWARD_ONLY);
    } else {
        throw new IllegalStateException("Either SQLQuery or entity must be provided");
    }
}

From source file:org.paxle.data.db.impl.CommandDB.java

License:Open Source License

private List<ICommand> fetchNextCommands(int limit) {
    List<ICommand> result = new ArrayList<ICommand>();

    Session session = null;/*  w ww .ja v a 2 s  . co m*/
    Transaction transaction = null;
    try {
        session = this.sessionFactory.openSession();
        session.setFlushMode(FlushMode.COMMIT);
        session.setCacheMode(CacheMode.IGNORE);
        transaction = session.beginTransaction();

        Query query = session.createQuery("FROM EnqueuedCommand as cmd");
        query.setFetchSize(limit); // this is important for derby because there is no limit support
        query.setMaxResults(limit); // restricting number of returned results
        query.setReadOnly(true); // read-only query
        ScrollableResults sr = query.scroll(ScrollMode.FORWARD_ONLY);

        final Key key = new Key();
        final DynamicBloomFilter bloomFilter = this.bloomFilter;
        final Cache urlExistsCache = this.urlExistsCache;

        // loop through the available commands
        while (sr.next() && result.size() < limit) {
            ICommand cmd = (ICommand) sr.get()[0];

            /* mark command as enqueued */
            session.delete("EnqueuedCommand", cmd);
            session.saveOrUpdate("CrawledCommand", cmd);

            // add command-location into caches
            key.set(cmd.getLocation().toString().getBytes(UTF8), 1.0);
            bloomFilter.add(key);
            Element element = new Element(cmd.getLocation(), null);
            urlExistsCache.put(element);

            result.add(cmd);
        }
        sr.close();

        transaction.commit();
    } catch (Exception e) {
        if (transaction != null && transaction.isActive())
            transaction.rollback();
        this.logger.error("Error while fetching commands", e);
    } finally {
        // closing session
        if (session != null)
            try {
                session.close();
            } catch (Exception e) {
                this.logger.error(
                        String.format("Unexpected '%s' while closing session.", e.getClass().getName()), e);
            }
    }

    return result;
}

From source file:org.rhq.server.metrics.migrator.datasources.ScrollableDataSource.java

License:Open Source License

@Override
public void initialize() {
    if (session != null || results != null) {
        close();//  ww  w  . j  av a  2s. c o  m
    }

    session = ((Session) entityManager.getDelegate()).getSessionFactory().openStatelessSession();

    this.prepareSQLSession();

    if (log.isDebugEnabled()) {
        if (maxResults >= 0) {
            log.debug("Preparing the query with " + maxResults + " results.");
        } else {
            log.debug("Preparing the query with all the results.");
        }
    }

    Query query = session.createSQLQuery(selectNativeQuery);
    if (maxResults >= 0) {
        query.setMaxResults(maxResults);
    }
    query.setFetchSize(30000);
    query.setReadOnly(true);
    query.setTimeout(TIMEOUT);
    results = query.scroll(ScrollMode.FORWARD_ONLY);

    lastMigratedItemIndex = -1;

    if (log.isDebugEnabled()) {
        if (maxResults >= 0) {
            log.debug("Query prepared with " + maxResults + " results.");
        } else {
            log.debug("Query prepared with all the results.");
        }
    }
}

From source file:org.shept.org.springframework.orm.hibernate3.HibernateTemplateExtended.java

License:Apache License

public Object findObjectByNamedParam(final String queryString, final String[] paramNames, final Object[] values)
        throws DataAccessException {

    if (paramNames.length != values.length) {
        throw new IllegalArgumentException("Length of paramNames array must match length of values array");
    }//from   w  ww.j  av a2  s.  c om
    @SuppressWarnings("rawtypes")
    List res = executeWithNativeSession(new HibernateCallback<List>() {
        public List doInHibernate(Session session) throws HibernateException {
            Query queryObject = session.createQuery(queryString);
            prepareQuery(queryObject);
            queryObject.setMaxResults(1);
            queryObject.setFetchSize(1);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    applyNamedParameterToQuery(queryObject, paramNames[i], values[i]);
                }
            }
            return queryObject.list();
        }
    });
    if (CollectionUtils.isEmpty(res))
        return null;
    return res.get(0);

}

From source file:org.shept.org.springframework.orm.hibernate3.HibernateTemplateExtended.java

License:Apache License

public Object findObjectByNamedQuery(final String queryName, final Object[] values) throws DataAccessException {
    @SuppressWarnings("rawtypes")
    List res = (List) executeWithNativeSession(new HibernateCallback<List>() {
        public List doInHibernate(Session session) throws HibernateException {
            Query queryObject = session.getNamedQuery(queryName);
            prepareQuery(queryObject);/* www  .j a  va 2s  .  c o m*/
            queryObject.setMaxResults(1);
            queryObject.setFetchSize(1);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    queryObject.setParameter(i, values[i]);
                }
            }
            return queryObject.list();
        }
    });
    if (CollectionUtils.isEmpty(res))
        return null;
    return res.get(0);
}

From source file:org.shept.org.springframework.orm.hibernate3.HibernateTemplateExtended.java

License:Apache License

public Object findObjectByNamedQueryAndNamedParam(final String queryName, final String[] paramNames,
        final Object[] values) throws DataAccessException {

    if (paramNames != null && values != null && paramNames.length != values.length) {
        throw new IllegalArgumentException("Length of paramNames array must match length of values array");
    }/*from  w w  w.j ava  2s  .  c  o m*/

    @SuppressWarnings("rawtypes")
    List res = executeWithNativeSession(new HibernateCallback<List>() {
        public List doInHibernate(Session session) throws HibernateException {
            Query queryObject = session.getNamedQuery(queryName);
            prepareQuery(queryObject);
            queryObject.setMaxResults(1);
            queryObject.setFetchSize(1);
            if (values != null) {
                for (int i = 0; i < values.length; i++) {
                    applyNamedParameterToQuery(queryObject, paramNames[i], values[i]);
                }
            }
            return queryObject.list();
        }
    });

    if (CollectionUtils.isEmpty(res))
        return null;
    return res.get(0);

}

From source file:org.shept.org.springframework.orm.hibernate3.HibernateTemplateExtended.java

License:Apache License

public List<?> find(final QueryDefinition queryDef, final int firstResult, final int maxResults) {
    return executeWithNativeSession(new HibernateCallback<List<?>>() {
        public List<?> doInHibernate(Session session) throws HibernateException {
            Query queryObject;
            if (isNamedQuery(queryDef.getQuery())) {
                queryObject = session.getNamedQuery(queryDef.getQuery());
            } else {
                queryObject = session.createQuery(queryDef.getQuery());
            }// w  w w . java  2  s .c  o m
            prepareQuery(queryObject);
            if (firstResult >= 0) {
                queryObject.setFirstResult(firstResult);
            }
            if (maxResults > 0) {
                queryObject.setFetchSize(maxResults); // aha added, shouldn't it be everywhere (DetachedCriteria, e.t.c. ? )
                queryObject.setMaxResults(maxResults);
            }
            if (ObjectUtils.isEmpty(queryDef.getParamNames())) {
                // query with '?' as paramter placeholder
                if (queryDef.getValues() != null) {
                    for (int i = 0; i < queryDef.getValues().length; i++) {
                        queryObject.setParameter(i, queryDef.getValues()[i]);
                    }
                }
            } else if (queryDef.getValues() != null) {
                // query with namedParamters[]
                for (int i = 0; i < queryDef.getValues().length; i++) {
                    applyNamedParameterToQuery(queryObject, queryDef.getParamNames()[i],
                            queryDef.getValues()[i]);
                }
            }
            return queryObject.list();
        }
    });
}

From source file:org.springframework.batch.item.database.HibernateCursorItemReaderStatefulIntegrationTests.java

License:Apache License

@Test
public void testStatefulClose() {

    SessionFactory sessionFactory = mock(SessionFactory.class);
    Session session = mock(Session.class);
    Query scrollableResults = mock(Query.class);
    HibernateCursorItemReader<Foo> itemReader = new HibernateCursorItemReader<Foo>();
    itemReader.setSessionFactory(sessionFactory);
    itemReader.setQueryString("testQuery");
    itemReader.setUseStatelessSession(false);

    when(sessionFactory.openSession()).thenReturn(session);
    when(session.createQuery("testQuery")).thenReturn(scrollableResults);
    when(scrollableResults.setFetchSize(0)).thenReturn(scrollableResults);
    when(session.close()).thenReturn(null);

    itemReader.open(new ExecutionContext());
    itemReader.close();/*from   ww  w  .j  a  va  2 s  .  co  m*/
}