List of usage examples for org.hibernate Criteria setFetchSize
public Criteria setFetchSize(int fetchSize);
From source file:magoffin.matt.dao.hbm.GenericHibernateDao.java
License:Open Source License
/** * Execute a batch callback against a normal Hibernate Session using a named query. * //from ww w .j av a2 s . com * @param criteriaBuilder the criteria builder * @param callback the callback * @param options the options * @return the number of items processed */ protected Integer executeLiveCriteriaBatchCallback(final CriteriaBuilder criteriaBuilder, final BatchCallback<T> callback, final BatchOptions options) { return getHibernateTemplate().execute(new HibernateCallback<Integer>() { @SuppressWarnings("unchecked") @Override public Integer doInHibernate(Session session) throws HibernateException, SQLException { Criteria criteria = session.createCriteria(type); criteria.setFetchSize(options.getBatchSize()); criteriaBuilder.buildCriteria(criteria); ScrollableResults items = criteria.scroll(ScrollMode.FORWARD_ONLY); int count = 0; OUTER: while (items.next()) { T item = (T) items.get(0); BatchCallbackResult action = callback.handle(item); switch (action) { case DELETE: session.delete(item); break; case UPDATE: case UPDATE_STOP: store(item); if (action == BatchCallbackResult.UPDATE_STOP) { break OUTER; } break; case STOP: break OUTER; case CONTINUE: // nothing to do break; } if (++count % 20 == 0) { session.flush(); session.clear(); } } return count; } }); }
From source file:org.codehaus.grepo.query.hibernate.generator.CriteriaGeneratorBase.java
License:Apache License
protected void applyFetchSizeSetting(HibernateQueryOptions queryOptions, HibernateQueryExecutionContext context, Criteria criteria) { Integer fetchSize = HibernateGeneratorUtils.getFetchSize(queryOptions, context.getFetchSize()); if (fetchSize != null) { criteria.setFetchSize(fetchSize); }// www . j a v a 2s. c om }
From source file:org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsHibernateUtil.java
License:Apache License
/** * Populates criteria arguments for the given target class and arguments map * * @param grailsApplication the GrailsApplication instance * @param targetClass The target class/*from w w w.j av a2 s . co m*/ * @param c The criteria instance * @param argMap The arguments map * */ @SuppressWarnings("rawtypes") public static void populateArgumentsForCriteria(GrailsApplication grailsApplication, Class<?> targetClass, Criteria c, Map argMap) { Integer maxParam = null; Integer offsetParam = null; SimpleTypeConverter converter = new SimpleTypeConverter(); if (argMap.containsKey(ARGUMENT_MAX)) { maxParam = converter.convertIfNecessary(argMap.get(ARGUMENT_MAX), Integer.class); } if (argMap.containsKey(ARGUMENT_OFFSET)) { offsetParam = converter.convertIfNecessary(argMap.get(ARGUMENT_OFFSET), Integer.class); } if (argMap.containsKey(ARGUMENT_FETCH_SIZE)) { c.setFetchSize(converter.convertIfNecessary(argMap.get(ARGUMENT_FETCH_SIZE), Integer.class)); } if (argMap.containsKey(ARGUMENT_TIMEOUT)) { c.setTimeout(converter.convertIfNecessary(argMap.get(ARGUMENT_TIMEOUT), Integer.class)); } if (argMap.containsKey(ARGUMENT_FLUSH_MODE)) { c.setFlushMode(converter.convertIfNecessary(argMap.get(ARGUMENT_FLUSH_MODE), FlushMode.class)); } if (argMap.containsKey(ARGUMENT_READ_ONLY)) { c.setReadOnly(GrailsClassUtils.getBooleanFromMap(ARGUMENT_READ_ONLY, argMap)); } String orderParam = (String) argMap.get(ARGUMENT_ORDER); Object fetchObj = argMap.get(ARGUMENT_FETCH); if (fetchObj instanceof Map) { Map fetch = (Map) fetchObj; for (Object o : fetch.keySet()) { String associationName = (String) o; c.setFetchMode(associationName, getFetchMode(fetch.get(associationName))); } } final String sort = (String) argMap.get(ARGUMENT_SORT); final String order = ORDER_DESC.equalsIgnoreCase(orderParam) ? ORDER_DESC : ORDER_ASC; final int max = maxParam == null ? -1 : maxParam; final int offset = offsetParam == null ? -1 : offsetParam; if (max > -1) { c.setMaxResults(max); } if (offset > -1) { c.setFirstResult(offset); } if (GrailsClassUtils.getBooleanFromMap(ARGUMENT_CACHE, argMap)) { c.setCacheable(true); } if (GrailsClassUtils.getBooleanFromMap(ARGUMENT_LOCK, argMap)) { c.setLockMode(LockMode.PESSIMISTIC_WRITE); } else { if (argMap.get(ARGUMENT_CACHE) == null) { cacheCriteriaByMapping(targetClass, c); } } if (sort != null) { boolean ignoreCase = true; Object caseArg = argMap.get(ARGUMENT_IGNORE_CASE); if (caseArg instanceof Boolean) { ignoreCase = (Boolean) caseArg; } addOrderPossiblyNested(grailsApplication, c, targetClass, sort, order, ignoreCase); } else { Mapping m = GrailsDomainBinder.getMapping(targetClass); if (m != null && !StringUtils.isBlank(m.getSort())) { addOrderPossiblyNested(grailsApplication, c, targetClass, m.getSort(), m.getOrder(), true); } } }
From source file:org.compass.gps.device.hibernate.indexer.PaginationHibernateIndexEntitiesIndexer.java
License:Apache License
public void performIndex(CompassSession session, IndexEntity[] entities) { for (IndexEntity entity : entities) { EntityInformation entityInfo = (EntityInformation) entity; int fetchCount = device.getFetchCount(); int current = 0; while (true) { if (!device.isRunning()) { return; }//from ww w . j a v a2 s . com Session hibernateSession = device.getSessionFactory().openSession(); hibernateSession.setCacheMode(CacheMode.IGNORE); Transaction hibernateTransaction = null; try { hibernateTransaction = hibernateSession.beginTransaction(); if (log.isDebugEnabled()) { log.debug(device.buildMessage("Indexing entity [" + entityInfo.getName() + "] range [" + current + "-" + (current + fetchCount) + "]")); } List values; Criteria criteria = entityInfo.getQueryProvider().createCriteria(hibernateSession, entityInfo); if (criteria != null) { criteria.setFetchSize(device.getFetchCount()); criteria.setFirstResult(current); criteria.setMaxResults(fetchCount); values = criteria.list(); } else { Query query = entityInfo.getQueryProvider().createQuery(hibernateSession, entityInfo) .setFirstResult(current).setMaxResults(fetchCount); values = query.list(); } for (Object value : values) { session.create(value); } session.evictAll(); hibernateTransaction.commit(); session.close(); current += fetchCount; if (values.size() < fetchCount) { break; } } catch (Exception e) { log.error(device.buildMessage("Failed to index the database"), e); if (hibernateTransaction != null) { try { hibernateTransaction.rollback(); } catch (Exception e1) { log.warn("Failed to rollback Hibernate", e1); } } if (!(e instanceof HibernateGpsDeviceException)) { throw new HibernateGpsDeviceException(device.buildMessage("Failed to index the database"), e); } throw (HibernateGpsDeviceException) e; } finally { hibernateSession.close(); } } } }
From source file:org.compass.gps.device.hibernate.indexer.ScrollableHibernateIndexEntitiesIndexer.java
License:Apache License
public void performIndex(CompassSession session, IndexEntity[] entities) { for (IndexEntity entity : entities) { EntityInformation entityInformation = (EntityInformation) entity; if (device.isFilteredForIndex(entityInformation.getName())) { continue; }/*from www. j a v a 2 s . c o m*/ if (!device.isRunning()) { return; } ScrollableResults cursor = null; Session hibernateSession = device.getSessionFactory().openSession(); hibernateSession.setCacheMode(CacheMode.IGNORE); Transaction hibernateTransaction = null; try { hibernateTransaction = hibernateSession.beginTransaction(); if (log.isDebugEnabled()) { log.debug(device.buildMessage("Indexing entities [" + entityInformation.getName() + "] using query [" + entityInformation.getQueryProvider() + "]")); } Criteria criteria = entityInformation.getQueryProvider().createCriteria(hibernateSession, entityInformation); if (criteria != null) { if (performOrderById) { Boolean performOrder = performOrderByPerEntity.get(entityInformation.getName()); if (performOrder == null || performOrder) { ClassMetadata metadata = hibernateSession.getSessionFactory() .getClassMetadata(entityInformation.getName()); String idPropName = metadata.getIdentifierPropertyName(); if (idPropName != null) { criteria.addOrder(Order.asc(idPropName)); } } } criteria.setFetchSize(device.getFetchCount()); cursor = criteria.scroll(ScrollMode.FORWARD_ONLY); } else { Query query = entityInformation.getQueryProvider().createQuery(hibernateSession, entityInformation); cursor = query.scroll(ScrollMode.FORWARD_ONLY); } // store things in row buffer to allow using batch fetching in Hibernate RowBuffer buffer = new RowBuffer(session, hibernateSession, device.getFetchCount()); Object prev = null; while (true) { try { if (!cursor.next()) { break; } } catch (ObjectNotFoundException e) { continue; } Object item = cursor.get(0); if (prev != null && item != prev) { buffer.put(prev); } prev = item; if (buffer.shouldFlush()) { // put also the item/prev since we are clearing the session // in the flush process buffer.put(prev); buffer.flush(); prev = null; } } if (prev != null) { buffer.put(prev); } buffer.close(); cursor.close(); hibernateTransaction.commit(); } catch (Exception e) { log.error(device.buildMessage("Failed to index the database"), e); if (cursor != null) { try { cursor.close(); } catch (Exception e1) { log.warn(device.buildMessage("Failed to close cursor on error, ignoring"), e1); } } if (hibernateTransaction != null) { try { hibernateTransaction.rollback(); } catch (Exception e1) { log.warn("Failed to rollback Hibernate", e1); } } if (!(e instanceof HibernateGpsDeviceException)) { throw new HibernateGpsDeviceException(device.buildMessage("Failed to index the database"), e); } throw (HibernateGpsDeviceException) e; } finally { hibernateSession.close(); session.close(); } } }
From source file:org.compass.gps.device.jpa.indexer.HibernateJpaIndexEntitiesIndexer.java
License:Apache License
public void performIndex(CompassSession session, IndexEntity[] entities) { for (IndexEntity indexEntity : entities) { EntityInformation entityInformation = (EntityInformation) indexEntity; if (jpaGpsDevice.isFilteredForIndex(entityInformation.getName())) { continue; }/* w w w . j a v a 2s . com*/ int fetchCount = jpaGpsDevice.getFetchCount(); if (!jpaGpsDevice.isRunning()) { return; } EntityManagerWrapper wrapper = jpaGpsDevice.getEntityManagerWrapper().newInstance(); ScrollableResults cursor = null; try { wrapper.open(); HibernateEntityManager entityManager = (HibernateEntityManager) wrapper.getEntityManager(); entityManager.getSession().setCacheMode(CacheMode.IGNORE); if (log.isDebugEnabled()) { log.debug(jpaGpsDevice.buildMessage("Indexing entities [" + entityInformation.getName() + "] using query [" + entityInformation.getQueryProvider() + "]")); } if (entityInformation.getQueryProvider() instanceof HibernateJpaQueryProvider) { Criteria criteria = ((HibernateJpaQueryProvider) entityInformation.getQueryProvider()) .createCriteria(entityManager, entityInformation); if (criteria != null) { if (performOrderById) { Boolean performOrder = performOrderByPerEntity.get(entityInformation.getName()); if (performOrder == null || performOrder) { ClassMetadata metadata = entityManager.getSession().getSessionFactory() .getClassMetadata(entityInformation.getName()); String idPropName = metadata.getIdentifierPropertyName(); if (idPropName != null) { criteria.addOrder(Order.asc(idPropName)); } } } criteria.setFetchSize(fetchCount); cursor = criteria.scroll(ScrollMode.FORWARD_ONLY); } } if (cursor == null) { HibernateQuery query = (HibernateQuery) entityInformation.getQueryProvider() .createQuery(entityManager, entityInformation); cursor = query.getHibernateQuery().scroll(ScrollMode.FORWARD_ONLY); } // store things in row buffer to allow using batch fetching in Hibernate RowBuffer buffer = new RowBuffer(session, entityManager.getSession(), fetchCount); Object prev = null; while (true) { try { if (!cursor.next()) { break; } } catch (ObjectNotFoundException e) { continue; } Object item = cursor.get(0); if (item != prev && prev != null) { buffer.put(prev); } prev = item; if (buffer.shouldFlush()) { // put also the item/prev since we are clearing the session // in the flush process buffer.put(prev); buffer.flush(); prev = null; } } if (prev != null) { buffer.put(prev); } buffer.close(); cursor.close(); entityManager.clear(); wrapper.close(); } catch (Exception e) { log.error(jpaGpsDevice.buildMessage("Failed to index the database"), e); if (cursor != null) { try { cursor.close(); } catch (Exception e1) { log.warn(jpaGpsDevice.buildMessage("Failed to close cursor on error, ignoring"), e1); } } wrapper.closeOnError(); if (!(e instanceof JpaGpsDeviceException)) { throw new JpaGpsDeviceException(jpaGpsDevice.buildMessage("Failed to index the database"), e); } throw (JpaGpsDeviceException) e; } } }
From source file:org.eurekastreams.server.persistence.mappers.cache.DomainGroupCacheLoader.java
License:Apache License
/** * Query all domain groups, loading them in the cache. *//*from w ww . j a va 2s . c om*/ private void queryAllDomainGroups() { long start = System.currentTimeMillis(); log.info("Loading up all domain groups with a single query"); Criteria criteria = domainGroupQueryStrategy.getCriteria(getHibernateSession()); // page the data criteria.setFetchSize(FETCH_SIZE); criteria.setCacheMode(CacheMode.IGNORE); ScrollableResults scroll = criteria.scroll(ScrollMode.FORWARD_ONLY); // loop through the results and store in cache long recordCounter = 0; while (scroll.next()) { if (++recordCounter % FETCH_SIZE == 0) { log.info("Loading " + recordCounter + "th domainGroup record, clearing session."); getHibernateSession().clear(); } DomainGroupModelView result = (DomainGroupModelView) scroll.get(0); getCache().set(CacheKeys.GROUP_BY_ID + result.getEntityId(), result); getCache().set(CacheKeys.GROUP_BY_SHORT_NAME + result.getShortName(), result.getEntityId()); } log.info("Completed loading all domain groups in " + (System.currentTimeMillis() - start) + " milliseconds."); }
From source file:org.eurekastreams.server.persistence.mappers.cache.PersonCacheLoader.java
License:Apache License
/** * Query the database for all people, only requesting the fields that we're caching, paging for effeciency. *//*from ww w . j av a2 s . c o m*/ private void queryAllPeople() { Criteria criteria = personQueryStrategy.getCriteria(getHibernateSession()); // page the data criteria.setFetchSize(FETCH_SIZE); criteria.setCacheMode(CacheMode.IGNORE); ScrollableResults scroll = criteria.scroll(ScrollMode.FORWARD_ONLY); // loop through the results and store in cache long recordCounter = 0; while (scroll.next()) { if (++recordCounter % FETCH_SIZE == 0) { log.info("Loading " + recordCounter + "th person record, clearing session."); getHibernateSession().clear(); } PersonModelView result = (PersonModelView) scroll.get(0); getCache().set(CacheKeys.PERSON_BY_ID + result.getEntityId(), result); getCache().set(CacheKeys.PERSON_BY_ACCOUNT_ID + result.getAccountId(), result.getEntityId()); getCache().set(CacheKeys.PERSON_BY_OPEN_SOCIAL_ID + result.getOpenSocialId(), result.getEntityId()); } }
From source file:org.geolatte.featureserver.dbase.StandardFeatureReader.java
License:Open Source License
private void scroll(Criteria crit) { crit.setFetchSize(1024); results = crit.scroll(ScrollMode.FORWARD_ONLY); }
From source file:org.grails.orm.hibernate.cfg.GrailsHibernateUtil.java
License:Apache License
/** * Populates criteria arguments for the given target class and arguments map * * @param datastore the GrailsApplication instance * @param targetClass The target class//w ww . j a va 2 s.com * @param c The criteria instance * @param argMap The arguments map */ @SuppressWarnings("rawtypes") public static void populateArgumentsForCriteria(AbstractHibernateDatastore datastore, Class<?> targetClass, Criteria c, Map argMap, ConversionService conversionService, boolean useDefaultMapping) { Integer maxParam = null; Integer offsetParam = null; if (argMap.containsKey(ARGUMENT_MAX)) { maxParam = conversionService.convert(argMap.get(ARGUMENT_MAX), Integer.class); } if (argMap.containsKey(ARGUMENT_OFFSET)) { offsetParam = conversionService.convert(argMap.get(ARGUMENT_OFFSET), Integer.class); } if (argMap.containsKey(ARGUMENT_FETCH_SIZE)) { c.setFetchSize(conversionService.convert(argMap.get(ARGUMENT_FETCH_SIZE), Integer.class)); } if (argMap.containsKey(ARGUMENT_TIMEOUT)) { c.setTimeout(conversionService.convert(argMap.get(ARGUMENT_TIMEOUT), Integer.class)); } if (argMap.containsKey(ARGUMENT_FLUSH_MODE)) { c.setFlushMode(convertFlushMode(argMap.get(ARGUMENT_FLUSH_MODE))); } if (argMap.containsKey(ARGUMENT_READ_ONLY)) { c.setReadOnly(ClassUtils.getBooleanFromMap(ARGUMENT_READ_ONLY, argMap)); } String orderParam = (String) argMap.get(ARGUMENT_ORDER); Object fetchObj = argMap.get(ARGUMENT_FETCH); if (fetchObj instanceof Map) { Map fetch = (Map) fetchObj; for (Object o : fetch.keySet()) { String associationName = (String) o; c.setFetchMode(associationName, getFetchMode(fetch.get(associationName))); } } final int max = maxParam == null ? -1 : maxParam; final int offset = offsetParam == null ? -1 : offsetParam; if (max > -1) { c.setMaxResults(max); } if (offset > -1) { c.setFirstResult(offset); } if (ClassUtils.getBooleanFromMap(ARGUMENT_LOCK, argMap)) { c.setLockMode(LockMode.PESSIMISTIC_WRITE); c.setCacheable(false); } else { if (argMap.containsKey(ARGUMENT_CACHE)) { c.setCacheable(ClassUtils.getBooleanFromMap(ARGUMENT_CACHE, argMap)); } else { cacheCriteriaByMapping(targetClass, c); } } final Object sortObj = argMap.get(ARGUMENT_SORT); if (sortObj != null) { boolean ignoreCase = true; Object caseArg = argMap.get(ARGUMENT_IGNORE_CASE); if (caseArg instanceof Boolean) { ignoreCase = (Boolean) caseArg; } if (sortObj instanceof Map) { Map sortMap = (Map) sortObj; for (Object sort : sortMap.keySet()) { final String order = ORDER_DESC.equalsIgnoreCase((String) sortMap.get(sort)) ? ORDER_DESC : ORDER_ASC; addOrderPossiblyNested(datastore, c, targetClass, (String) sort, order, ignoreCase); } } else { final String sort = (String) sortObj; final String order = ORDER_DESC.equalsIgnoreCase(orderParam) ? ORDER_DESC : ORDER_ASC; addOrderPossiblyNested(datastore, c, targetClass, sort, order, ignoreCase); } } else if (useDefaultMapping) { Mapping m = GrailsDomainBinder.getMapping(targetClass); if (m != null) { Map sortMap = m.getSort().getNamesAndDirections(); for (Object sort : sortMap.keySet()) { final String order = ORDER_DESC.equalsIgnoreCase((String) sortMap.get(sort)) ? ORDER_DESC : ORDER_ASC; addOrderPossiblyNested(datastore, c, targetClass, (String) sort, order, true); } } } }