List of usage examples for org.hibernate Query scroll
ScrollableResults scroll(ScrollMode scrollMode);
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);// w w w . j a v a 2 s. c o 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);// ww w.j a va2 s . c om 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)); }// ww w .ja v a 2s . c o m } 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 w w .j a va 2s. c o 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.pentaho.reporting.engine.classic.extensions.datasources.hibernate.SimpleHQLDataFactory.java
License:Open Source License
/** * Queries a datasource. The string 'query' defines the name of the query. The Parameterset given here may contain * more data than actually needed.//from w ww .j a va 2s. c om * <p/> * The dataset may change between two calls, do not assume anything! * * @param query * @param parameters * @return */ public synchronized TableModel queryData(final String query, final DataRow parameters) throws ReportDataFactoryException { try { final Query pstmt = getSession().createQuery(query); final String[] params = pstmt.getNamedParameters(); for (int i = 0; i < params.length; i++) { final String param = params[i]; final Object pvalue = parameters.get(param); if (pvalue == null) { // this should work, but some driver are known to die here. // they should be fed with setNull(..) instead; something // we cant do as JDK1.2's JDBC does not define it. pstmt.setParameter(param, null); } else { pstmt.setParameter(param, pvalue); } } final Object queryLimit = parameters.get(DataFactory.QUERY_LIMIT); if (queryLimit instanceof Number) { final Number i = (Number) queryLimit; if (i.intValue() >= 0) { pstmt.setMaxResults(i.intValue()); } } final Object queryTimeout = parameters.get(DataFactory.QUERY_TIMEOUT); if (queryTimeout instanceof Number) { final Number i = (Number) queryLimit; if (i.intValue() >= 0) { pstmt.setTimeout(i.intValue()); } } final ScrollableResults res = pstmt.scroll(ScrollMode.FORWARD_ONLY); return generateDefaultTableModel(res, pstmt.getReturnAliases()); } catch (Exception e) { throw new ReportDataFactoryException("Failed at query: " + query, e); } }
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();/*from ww w . j a v 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.yes.cart.dao.impl.GenericDAOHibernateImpl.java
License:Apache License
/** * {@inheritDoc}/*from w ww. j a v a 2s . co m*/ */ public ResultsIterator<Object> findByQueryIterator(final String hsqlQuery, final Object... parameters) { Query query = sessionFactory.getCurrentSession().createQuery(hsqlQuery); if (parameters != null) { setQueryParameters(query, parameters); } return new ResultsIteratorImpl<Object>(query.scroll(ScrollMode.FORWARD_ONLY)); }
From source file:org.yes.cart.dao.impl.GenericDAOHibernateImpl.java
License:Apache License
/** * {@inheritDoc}/*from w w w.j av a 2 s .c om*/ */ @SuppressWarnings("unchecked") public ResultsIterator<T> findByNamedQueryIterator(final String namedQueryName, final Object... parameters) { Query query = sessionFactory.getCurrentSession().getNamedQuery(namedQueryName); if (parameters != null) { setQueryParameters(query, parameters); } return new ResultsIteratorImpl<T>(query.scroll(ScrollMode.FORWARD_ONLY)); }
From source file:org.yes.cart.dao.impl.GenericDAOHibernateImpl.java
License:Apache License
/** * {@inheritDoc}/*from w w w . j a va2 s . co m*/ */ @SuppressWarnings("unchecked") public ResultsIterator<Object> findQueryObjectByNamedQueryIterator(final String namedQueryName, final Object... parameters) { Query query = sessionFactory.getCurrentSession().getNamedQuery(namedQueryName); setQueryParameters(query, parameters); final ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY); return new ResultsIteratorImpl<Object>(results); }
From source file:org.zanata.dao.HTextFlowTargetStreamingDAO.java
License:Open Source License
/** * * @return scrollable result set of HTextFlowTarget which has all * fields(locale, textflow, document, document locale, project * iteration and project) eagerly fetched. *//*w ww. ja v a 2 s . c o m*/ public ScrollableResults getAllTargetsWithAllFieldsEagerlyFetched() { Query query = getSession().createQuery("from HTextFlowTarget tft " + "join fetch tft.locale " + "join fetch tft.textFlow " + "join fetch tft.textFlow.document " + "join fetch tft.textFlow.document.locale " + "join fetch tft.textFlow.document.projectIteration " + "join fetch tft.textFlow.document.projectIteration.project"); query.setFetchSize(Integer.MIN_VALUE); return query.scroll(ScrollMode.FORWARD_ONLY); }